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
|
|---|---|---|---|---|---|
Since I’m trying to learn Clojure, and the name of the language is a variant on the term ‘closure’ (with the ‘j’ inserted since it’s based on Java, I assume), it seems appropriate that I should know what, exactly, a closure is. I’ve poked around the web a fair bit, but I couldn’t find a nice, clear (to me, anyway) explanation of what a closure is. I’ve patched together a bit of an understanding from a few places that posted some examples, so I’ll try to produce something that makes sense to me at this point. Hopefully any closure experts who chance on this page will correct me if my understanding is faulty.
Basically, a closure is a function that is created within a program (rather than being hard-coded before the program is compiled), and that contains the functionality and the data that were current when the function was created. In other words, a closure is a function that captures, or closes over, its environment at the time it was created, and preserves that environment throughout its lifetime.
As I haven’t delved deeply enough into Clojure itself yet, I’ll try to illustrate a closure by using some examples from a language with which I am more familiar: C#. Apologies if this isn’t a language that you know, but I had to start somewhere.
C# contains a feature called a delegate. Most C# programmers will be familiar with delegates as things that are used to handle events, but in fact they have many more applications. I’ll give a quick recap on delegates here (I’ll try to put up a more complete post on them soon). A delegate, as its name implies, delegates work to another function or functions. To declare a delegate, we must specify the signature of the type of function that it can deal with.
A typical delegate declaration is something like this:
public delegate int ArithOperation(int num1, int num2);
This declaration is for a delegate with the name ArithOperation and states that this delegate can refer to functions with two int arguments and an int return type. Note that ArithOperation is not the name of a function; it is the name of the delegate, and is a declared data type.
This delegate can be attached to an ordinary function of the required signature. For example, if we had a function:
public int Plus(int num1, int num2) { return num1 + num2; }
we can then initialize the delegate by writing:
ArithOperation arithOp = new ArithOperation(Plus);
Having made this connection, we can then use the delegate by writing something like this:
int sum = arithOp(3, 4);
The arithOp delegate will pass its arguments along to the Plus() function, which will calculate the sum and return it via the delegate, so that sum becomes 7.
Now all of this might look very clumsy, since we could obviously have just called Plus() directly without using the delegate. However, the power of delegates begins to become apparent when we realize that a delegate can be passed as an argument to a function, whereas a raw function name like Plus cannot. Thus the C# delegate provides a way of passing functions around a program just like any other data types.
To illustrate this, we need a program that’s a bit more involved. A common operation is that of sorting data, and a popular sorting algorithm is quicksort. Don’t worry if you don’t know the quicksort algorithm; I won’t be looking in detail at how it works here. All you need to realize is that in any sorting algorithm, we must have a way of ordering the data, so we need a meaning for the ‘less than’ operation. Typically, data come in various forms (not always as bare numbers), and a program cannot anticipate all the types of data it may be required to sort. Thus the ability to define a ‘lessThan’ function on the fly to cope with some new data type that we wish to sort would be quite useful.
First, we’ll give the code for the quicksort algorithm (again, you don’t need to work through the whole thing to follow what I’m going to say):
public class Quicksort<T> { public static List<T> Sort(List<T> data, int left, int right, Func<T, T, bool> lessThan) { int i = left; int j = right; int pivotValue = (left + right) / 2; T x = data[pivotValue]; T w; while (i <= j) { while (lessThan(data[i], x)) { i++; } while (lessThan(x, data[j])) { j--; } if (i <= j) { w = data[i]; data[i++] = data[j]; data[j--] = w; } } if (left < j) { Sort(data, left, j, lessThan); } if (i < right) { Sort(data, i, right, lessThan); } return data; } }
This code uses C#’s generic data types to allow it to sort any type of data. On line 1, the Quicksort class takes a generic data type T, which is the type of data we want to sort. There is only one method in this class, which performs the quicksort algorithm. Line 3 begins the Sort function, which takes a List (declared as a generic type, also containing elements of type T), two ints (left and right) which indicate which portion of the list to sort (these would be set to the beginning and end of the list on the first pass), and a curious object called Func<T, T, bool> lessThan. As you might guess from its name, this is the lessThan function that will be used to determine the order of two data elements in the list.
Func<T, T, bool> is a pre-defined delegate available with later versions of C#. The signature of the functions that it can connect to must have two arguments, both of type T in this case, and a return type of bool. (There are actually 17 varieties of Func allowing for functions with from zero to 16 arguments, so if your program needs a different number of arguments, just use the corresponding version of Func. If you have more than 16 arguments, you need to refactor your code(!))
Having a delegate as a parameter to the Sort() method means we can choose the lessThan function somewhere else and pass it in as a parameter to the program. (If you’re interested in the innards of the quicksort algorithm, you’ll note that the lessThan function is used on lines 12 and 16. Quicksort is recursive, so the same function must be passed along to subsequent calls to Sort() on lines 29 and 33.)
So how do we create a custom lessThan function? Let’s look at the other class in this program.
class FuncTest { static Func<string, string, bool> selectFunc(int choice) { switch (choice) { case 1: return delegate(string s1, string s2) { if (s1.Length < s2.Length) return true; else if (s1.Length > s2.Length) return false; else { if (s1.CompareTo(s2) < 0) return true; return false; } }; case 2: return delegate(string s1, string s2) { return s1.CompareTo(s2) < 0; }; default: return null; } } static void Main(string[] args) { List<string> wordList = new List<string>(); string[] test = "the quick brown fox jumped over the lazy dog".Split(new char[] { ' ' }); for (int word = 0; word < test.Length; word++) { wordList.Add(test[word]); } Console.Write("Sort by size (1) or alphabetical order (2): "); int choice = int.Parse(Console.ReadLine()); Func<string, string, bool> lessThan = selectFunc(choice); if (lessThan == null) { Console.WriteLine("Quitting"); Environment.Exit(0); } List<string> sortedList = Quicksort<string>.Sort(wordList, 0, wordList.Count - 1, lessThan); for (int word = 0; word < sortedList.Count; word++) { Console.WriteLine(sortedList[word]); } } }
Let’s start with the Main() function on line 31. To test the program, we’ll use a List of strings, so we create this and populate it with some words on lines 33 to 38. Then we offer the user two options for sorting. First, the words can be sorted by size (so shorter words come before longer ones), or they can be sorted alphabetically. When the choice has been made, we call selectFunc() on line 43. This function will create the correct lessThan function and return it as a delegate to the function code.
Switch your attention now to selectFunc() on line 3. If the user wants the words sorted by size, we build the correct lessThan function on lines 8 through 20. We are constructing an anonymous function (it has no name). On line 8, we use the C# keyword delegate to create a delegate attached to the function code which follows. After writing delegate, we write out the function as usual, beginning with its argument list on line 8, then adding the rest of the code on lines 9 through 20 (not forgetting to put a semi-colon afterwards). The return type of the function is defined implicitly by the return statements in its definition.
If the user wanted alphabetical sorting, we build another delegate in the same way, on lines 22 to 25.
In case you’re wondering what all this has to do with closures, functions created in this way are closures. They are created within the running program, and capture the environment in which they were created. They can also (via their delegates) be passed as parameters to other functions. This is done back in Main() on line 49, where a call to the Sort() method is made, passing along the lessThan delegate we built earlier.
This example shows that closures allow the separation of the logic for accomplishing a given task from the rest of the code. If we wanted to sort other types of data (for example, database records consisting of several data fields, each of a different data type) we can write another function that determines the lessThan condition for such data, and pass that via its delegate into the Sort() function without having to rewrite the sorting routine.
One thing this example hasn’t shown, however, is how a closure captures data that is current when the closure (the function) is defined. But this post has already reached a fair size, so I’ll leave that till the next post.
Code for this post available here.
|
https://programming-pages.com/tag/func/
|
CC-MAIN-2018-26
|
refinedweb
| 1,699
| 66.67
|
Let be a set of curves for which we want to compute all intersections. We want to avoid testing pairs of curves that are far apart. To find the intersecting pairs we imagine sweeping a line from left to right over the plane, starting from a position left to all curves. While we sweep the plane, we keep track of all curves intersecting it.
This type of algorithm is called a plane sweep algorithm and the line is called the sweep line. The status of the sweep line is the set of curves intersecting it. The status changes while the sweep line moves to the right, but not continuously. The sweep line status is updated at specific points called the event points. These points are actually the endpoints of all curves and their intersection points. The initial set of event points are only the endpoints of the curves. More event points are added as intersection points are calculated.
This chapter describes the Sweep_line_2 class it implements the plane sweep algorithm, and can be used to compute the intersection points of a given collection curves, the disjoint-interior subcurves induced by such a collection, and a few other retaled tasks.
In particular, we take advantage of the implemented sweep line algorithm to construct a Planar Map of intersecting curves efficiently. See CGAL::Pm_with_intersection for more deatils.
Figure: Four input segments
#include <CGAL/Cartesian.h> #include <CGAL/MP_Float.h> #include <CGAL/Quotient.h> #include <CGAL/Arr_segment_cached_traits_2.h> #include <CGAL/Sweep_line_2.h> #include <vector> typedef CGAL::Quotient<CGAL::MP_Float> NT; typedef CGAL::Cartesian<NT> Kernel; typedef CGAL::Arr_segment_cached_traits_2<Kernel> Traits; typedef Traits::Point_2 Point_2; typedef Traits::Curve_2 Curve_2; typedef std::list<Curve_2> CurveList; typedef CurveList::iterator CurveListIter; typedef CGAL::Sweep_line_2<CurveListIter, Traits> Sweep_line; int main() { CurveList segments; Curve_2 c1(Point_2(1,5), Point_2(8,5)); Curve_2 c2(Point_2(1,1), Point_2(8,8)); Curve_2 c3(Point_2(3,1), Point_2(3,8)); Curve_2 c4(Point_2(8,5), Point_2(8,8)); segments.push_back(c1); segments.push_back(c2); segments.push_back(c3); segments.push_back(c4); std::list<Curve_2> subcurves; Sweep_line sl; sl.get_subcurves(segments.begin(), segments.end(), std::back_inserter(subcurves), true); for (std::list<Curve_2>::iterator scv_iter = subcurves.begin(); scv_iter != subcurves.end(); scv_iter++) std::cout << *scv_iter << std::endl; return 0; }
The input segments intersect at three interior points and meet at two endpoints. The program results with ten sub segments. The output of the program follows:
1/1 1/1 -147/-49 -147/-49 1/1 5/1 -147/-49 -245/-49 3/1 1/1 -147/-49 -147/-49 -147/-49 -147/-49 -147/-49 -245/-49 -147/-49 -245/-49 3/1 8/1 -147/-49 -147/-49 245/49 245/49 -147/-49 -245/-49 245/49 245/49 245/49 245/49 8/1 5/1 245/49 245/49 8/1 8/1 8/1 5/1 8/1 8/1
The Sweep_line_2<InputIterator,Traits> class is parameterized with two objects. The sequence of input curves are obtained through the InputIterator. The type of curves processed by the Sweep_line_2<InputIterator,Traits> class is dictated by the injected traits class, a model of the SweepLineTraits concept. Inject the suitable traits class, to handle your desired family of curves. The planar map with intersection comes with a collection of traits classes that handle various types of curves, such as segments, polylines, and conics. Naturally, users may author new traits classes that handle other types or that possesses different carachteristics.
The PlanarMapWithIntersectionsTraits_2 concept is a refinement of the SweepLineTraits_2 concept, as some of the functions required to perform some of the planar map operations are not needed, by the sweep line algorithm. Hence, all the models of the Planar Map With Intersections Traits PlanarMapWithIntersectionsTraits_2 concept are also models of the SweepLineTraits_2 concept.
The sweep line algorithm was implemented according to Bentley and Ottmann [dBvKOS97]. The implementation is robust. It supports general curves and handles all degenerate cases, including overlapping curves, vertical segments, and tangency between curves.
The STL -container is used for the implementation of the event queue, and the STL -container is used for the implementation of the status line. Additional containers are used to accomodate all intersection points for each input curve ordered from left to right, and all the resulting subcurves for each event point.
The complexity of this algorithm is loglog where is the number of the input curves and is the number of intersection points induced by these curves.
|
https://doc.cgal.org/Manual/3.1/doc_html/cgal_manual/Sweep_line_2/Chapter_main.html
|
CC-MAIN-2019-18
|
refinedweb
| 739
| 54.73
|
![: 223
Hello everyone,
I’m using the TMS320F28016 DSP and CCS3.3 compiler. My programme is near to finish, but I have a few loose ends. For example, I would like to save the software version into the .out file . For all this to happen, I have two files:
#define _DESCRIPCION "(xxxxxxxx)--------------"
#define DEVICE_CODE 22
#define MANUFACT_CODE 0
…
#define SW_VERSION 1
#define SW_REVISION 1
#define SW_COMPILATION 0
…
extern const unsigned char informacion[96];
So, after the compilation, I hope to find into the .out file a long string with the value of information, but this doesn’t appear in this file. Any idea? Maybe the CCS is optimizing the code and like information is never used after the initialization, the compiler not write the value in the .out file?
Thanks in advance.
If you're not actually using the const array in your program I don't think the compiler will pull it in to the .out file. If you just want the string somewhere in your .out file, you can do something like:
#include "string.h"
const char informacion[96] = "thisisaverylongstringof......";int L;
main()
{L = strlen(informacion);
Regards,
Rich Poley:
Thank you Richard.
Now, I can find the string into the .out file, but with a dot character between letters. For example, If I wait the string “hello”, I get the string “h.e.l.l.o.”. Any idea?.
|
https://e2e.ti.com/support/microcontrollers/c2000/f/171/t/390233?tisearch=e2e-sitesearch&keymatch=TMS320F28016
|
CC-MAIN-2021-04
|
refinedweb
| 230
| 65.32
|
=head1 NAME perldelta - what's new for perl5.005 =head1 DESCRIPTION This document describes differences between the 5.004 release and this one. =head1 C<1> to C<49>, and development releases (which should be considered "alpha" quality) run from C<50> to C<99>. Perl 5.005 is the combined product of the new dual-track development scheme. =head1 Incompatible Changes =head2 L<INSTALL> for detailed instructions on how to upgrade. =head2 Default installation structure has changed The new Configure defaults are designed to allow a smooth upgrade from 5.004 to 5.005, but you should read L<INSTALL> for a detailed discussion of the changes in order to adapt them to your system. =head2 Perl Source Compatibility When none of the experimental features are enabled, there should be very few user-visible Perl source compatibility issues. If threads are enabled, then some caveats apply. C<@_> and C<$_> become lexical variables. The effect of this should be largely transparent to the user, but there are some boundary conditions under which user will need to be aware of the issues. For example, C<local(@_)> results in a "Can't localize lexical variable @_ ..." message. This may be enabled in a future version. Some new keywords have been introduced. These are generally expected to have very little impact on compatibility. See L<New C<INIT> keyword>, L<New C<lock> keyword>, and L<New C<qr//> operator>. Certain barewords are now reserved. Use of these will provoke a warning if you have asked for them with the C<-w> switch. See L<C<our> is now a reserved word>. =head2 C Source Compatibility There have been a large number of changes in the internals to support the new features in this release. =over 4 =item Core sources now require ANSI C compiler An ANSI C compiler is now B<required> to build perl. See F<INSTALL>. =item All Perl global variables must now be referenced with an explicit prefix All Perl global variables that are visible for use by extensions now have a C<PL_> prefix. New extensions should C<not> refer to perl globals by their unqualified names. To preserve sanity, we provide limited backward compatibility for globals that are being widely used like C<sv_undef> and C<na> (which should now be written as C<PL_sv_undef>, C<PL_na> etc.) If you find that your XS extension does not compile anymore because a perl global is not visible, try adding a C<PL_> prefix to the global and rebuild. It is strongly recommended that all functions in the Perl API that don't begin with C<perl> be referenced with a C<Perl_> prefix. The bare function names without the C<Perl_> prefix are supported with macros, but this support may cease in a future release. See L<perlguts/"API LISTING">. =item Enabling threads has source compatibility issues Perl built with threading enabled requires extensions to use the new C<dTHR> macro to initialize the handle to access per-thread data. If you see a compiler error that talks about the variable C<thr> not being declared (when building a module that has XS code), you need to add C<dTHR;> at the beginning of the block that elicited the error. The API function C<perl_get_sv("@",FALSE)> should be used instead of directly accessing perl globals as C<GvSV(errgv)>. The API call is backward compatible with existing perls and provides source compatibility with threading is enabled. See L<"C Source Compatibility"> for more information. =back =head2 F<INSTALL>. =head2 C<-e> switch do not create temporary files anymore. =head2 Relaxed new mandatory warnings introduced in 5.004 Many new warnings that were introduced in 5.004 have been made optional. Some of these warnings are still present, but perl's new features make them less often a problem. See L<New Diagnostics>. =head2 Licensing Perl has a new Social Contract for contributors. See F L<perl> and the individual perl man pages listed therein. =head1 Core Changes =head2 Threads WARNING: Threading is considered an B<experimental> feature. Details of the implementation may change without notice. There are known limitations and some bugs. These are expected to be fixed in future versions. See L<README.threads>. Mach cthreads (NEXTSTEP, OPENSTEP, Rhapsody) are now supported by the Thread extension. =head2 Compiler WARNING: The Compiler and related tools are considered B<experimental>.. C<B::Lint> is an experimental module to detect and warn about suspicious code, especially the cases that the C<-w> switch does not detect. C<B::Deparse> can be used to demystify perl code, and understand how perl optimizes certain constructs. C<B::Xref> generates cross reference reports of all definition and use of variables, subroutines and formats in a program. C<B::Showlex> show the lexical variables used by a subroutine or file at a glance. C<perlcc> is a simple frontend for compiling perl. See C<ext/B/README>, L<B>, and the respective compiler modules. =head2 Regular Expressions Perl's regular expression engine has been seriously overhauled, and many new constructs are supported. Several bugs have been fixed. Here is an itemized summary: =over 4 =item; =item Many bug fixes Note that only the major bug fixes are listed here. See F; =item New regular expression constructs The following new syntax elements are supported: (?<=RE) (?<!RE) (?{ CODE }) (?i-x) (?i:RE) (?(COND)YES_RE|NO_RE) (?>RE) \z =item New operator for precompiled regular expressions See L<New C<qr//> operator>. =item Other improvements Better debugging output (possibly with colors), even from non-debugging Perl; RE engine code now looks like C, not like assembler; Behaviour of RE modifiable by `use re' directive; Improved documentation; Test suite significantly extended; Syntax [:^upper:] etc., reserved inside character classes; =item Incompatible changes (?i) localized inside enclosing group; $( is not interpolated into RE any more; /RE/g may match at the same position (with non-zero length) after a zero-length match (bug fix). =back See L<perlre> and L<perlop>. =head2 Improved malloc() See banner at the beginning of C<malloc.c> for details. =head2 Quicksort is internally implemented Perl now contains its own highly optimized qsort() routine. The new qsort() is resistant to inconsistent comparison functions, so Perl's C<sort()> will not provoke coredumps any more when given poorly written sort subroutines. (Some C library C<qsort()>s that were being used before used to have this problem.) In our testing, the new C<qsort()> required the minimal number of pair-wise compares on average, among all known C<qsort()> implementations. See C<perlfunc/sort>. =head2 Reliable signals Perl's signal handling is susceptible to random crashes, because signals arrive asynchronously, and the Perl runtime is not reentrant at arbitrary times. However, one experimental implementation of reliable signals is available when threads are enabled. See C<Thread::Signal>. Also see F<INSTALL> for how to build a Perl capable of threads. =head2 Reliable stack pointers. =head2 More generous treatment of carriage returns C<PERL_STRICT_CR> when building perl. Of course, all this has nothing whatever to do with how escapes like C<. =head2 Memory leaks C<substr>, C<pos> and C<vec> don't leak memory anymore when used in lvalue context. Many small leaks that impacted applications that embed multiple interpreters have been fixed. =head2 Better support for multiple interpreters The build-time option C<-DMULTIPLICITY> has had many of the details reworked. Some previously global variables that should have been per-interpreter now are. With care, this allows interpreters to call each other. See the C<PerlInterp> extension on CPAN. =head2 Behavior of local() on array and hash elements is now well-defined See L<perlsub/"Temporary Values via local()">. =head2 C<%!> is transparently tied to the L<Errno> module See L<perlvar>, and L<Errno>. =head2 Pseudo-hashes are supported See L<perlref>. =head2 C<EXPR foreach EXPR> is supported See L<perlsyn>. =head2 Keywords can be globally overridden See L<perlsub>. =head2 C<$^E> is meaningful on Win32 See L<perlvar>. =head2 C<foreach (1..1000000)> optimized C<foreach (1..1000000)> is now optimized into a counting loop. It does not try to allocate a 1000000-size list anymore. =head2 C<Foo::> can be used as implicitly quoted package name Barewords caused unintuitive behavior when a subroutine with the same name as a package happened to be defined. Thus, C<new Foo @args>, use the result of the call to C<Foo()> instead of C<Foo> being treated as a literal. The recommended way to write barewords in the indirect object slot is C<new Foo:: @args>. Note that the method C<new()> is called with a first argument of C<Foo>, not C<Foo::> when you do that. =head2 C<exists $Foo::{Bar::}> tests existence of a package It was impossible to test for the existence of a package without actually creating it before. Now C<exists $Foo::{Bar::}> can be used to test if the C<Foo::Bar> namespace has been created. =head2 Better locale support See L<perllocale>. =head2. =head2 prototype() returns useful results on builtins See L<perlfunc/prototype>. =head2 Extended support for exception handling C<die()> now accepts a reference value, and C<$@> gets set to that value in exception traps. This makes it possible to propagate exception objects. This is an undocumented B<experimental> feature. =head2 Re-blessing in DESTROY() supported for chaining DESTROY() methods See L<perlobj/Destructors>. =head2 All C<printf> format conversions are handled internally See L<perlfunc/printf>. =head2 New C<INIT> keyword C<INIT> subs are like C<BEGIN> and C<END>, but they get run just before the perl runtime begins execution. e.g., the Perl Compiler makes use of C<INIT> blocks to initialize and resolve pointers to XSUBs. =head2 New C<lock> keyword The C<lock> keyword is the fundamental synchronization primitive in threaded perl. When threads are not enabled, it is currently a noop. To minimize impact on source compatibility this keyword is "weak", i.e., any user-defined subroutine of the same name overrides it, unless a C<use Thread> has been seen. =head2 New C<qr//> operator The C<qr//> operator, which is syntactically similar to the other quote-like operators, is used to create precompiled regular expressions. This compiled form can now be explicitly passed around in variables, and interpolated in other regular expressions. See L<perlop>. =head2 C<our> is now a reserved word Calling a subroutine with the name C<our> will now provoke a warning when using the C<-w> switch. =head2 Tied arrays are now fully supported See L<Tie::Array>. =head2 Tied handles support is better Several missing hooks have been added. There is also a new base class for TIEARRAY implementations. See L<Tie::Array>. =head2 4th argument to substr substr() can now both return and replace in one operation. The optional 4th argument is the replacement string. See L<perlfunc/substr>. =head2 Negative LENGTH argument to splice splice() with a negative LENGTH argument now work similar to what the LENGTH did for substr(). Previously a negative LENGTH was treated as 0. See L<perlfunc/splice>. =head2 Magic lvalues are now more magical When you say something like C C<\> or as an argument to a sub that modifies C<@_>.". =head2 E<lt>E<gt> now reads in records If C<$/> is a referenence to an integer, or a scalar that holds an integer, E<lt>E<gt> will read in records instead of lines. For more info, see L<perlvar/$/>. =head2 pack() format 'Z' supported The new format type 'Z' is useful for packing and unpacking null-terminated strings. See L<perlfunc/"pack">. =head1 Significant bug fixes =head2 E<lt>HANDLEE<gt> on empty files With C<$/> set to C<undef>, slurping an empty file returns a string of zero length (instead of C<undef>, as it used to) for the first time the HANDLE is read. Subsequent reads yield C). =head1 Supported Platforms Configure has many incremental improvements. Site-wide policy for building perl can now be made persistent, via Policy.sh. Configure also records the command-line arguments used in F<config.sh>. =head2 New Platforms BeOS is now supported. See L<README.beos>. DOS is now supported under the DJGPP tools. See L<README.dos>. GNU/Hurd is now supported. MiNT is now supported. See L<README.mint>. MPE/iX is now supported. See L<README.mpeix>. MVS (aka OS390, aka Open Edition) is now supported. See L<README.os390>. Stratus VOS is now supported. See L<README.vos>. =head2 Changes in existing support Win32 support has been vastly enhanced. Support for Perl Object, a C++ encapsulation of Perl. GCC and EGCS are now supported on Win32. See F<README.win32>, aka L<perlwin32>. VMS configuration system has been rewritten. See L<README.vms>. The hints files for most Unix platforms have seen incremental improvements. =head1 Modules and Pragmata =head2 New Modules =over =item B Perl compiler and tools. See L<B>. =item Data::Dumper A module to pretty print Perl data. See L<Data::Dumper>. =item Dumpvalue A module to dump perl values to the screen. See L<Dumpvalue>. =item Errno A module to look up errors more conveniently. See L<Errno>. =item File::Spec A portable API for file operations. =item ExtUtils::Installed Query and manage installed modules. =item ExtUtils::Packlist Manipulate .packlist files. =item Fatal Make functions/builtins succeed or die. =item IPC::SysV Constants and other support infrastructure for System V IPC operations in perl. =item Test A framework for writing testsuites. =item Tie::Array Base class for tied arrays. =item Tie::Handle Base class for tied handles. =item Thread Perl thread creation, manipulation, and support. =item attrs Set subroutine attributes. =item fields Compile-time class fields. =item re Various pragmata to control behavior of regular expressions. =back =head2 Changes in existing modules =over =item Benchmark You can now run tests for I)". =item Carp Carp has a new function cluck(). cluck() warns, like carp(), but also adds a stack backtrace to the error message, like confess(). =item CGI CGI has been updated to version 2.42. =item. =item Math::Complex The accessor methods Re, Im, arg, abs, rho, and theta, can now also act as mutators (accessor $z->Re(), mutator $z->Re(3)). =item Math::Trig A little bit of radial trigonometry (cylindrical and spherical) added: radial coordinate conversions and the great circle distance. =item POSIX POSIX now has its own platform-specific hints files. =item DB_File DB_File supports version 2.x of Berkeley DB. See C<ext/DB_File/Changes>. . =item CPAN See <perlmodinstall> and L<CPAN>. =item Cwd Cwd::cwd is faster on most platforms. =item Benchmark Keeps better time. =back =head1 Utility Changes C<h2ph> and related utilities have been vastly overhauled. C<perlcc>, a new experimental front end for the compiler is available. The crude GNU C<configure> emulator is now called C<configure.gnu> to avoid trampling on C<Configure> under case-insensitive filesystems. C<perldoc> used to be rather slow. The slower features are now optional. In particular, case-insensitive searches need the C<-i> switch, and recursive searches need C<-r>. You can set these switches in the C<PERLDOC> environment variable to get the old behavior. =head1 Documentation Changes Config.pm now has a glossary of variables. F<Porting/patching.pod> has detailed instructions on how to create and submit patches for perl. L<perlport> specifies guidelines on how to write portably. L<perlmodinstall> describes how to fetch and install modules from C<CPAN> sites. Some more Perl traps are documented now. See L<perltrap>. L<perlopentut> gives a tutorial on using open(). L<perlreftut> gives a tutorial on references. L<perlthrtut> gives a tutorial on threads. =head1 New Diagnostics =over =item C<use subs> pragma). To silently interpret it as the Perl operator, use the C<CORE::> prefix on the operator (e.g. C<CORE::log($x)>) or by declaring the subroutine to be an object method (see L<attrs>). =item Bad index while coercing array into hash (F) The index looked up in the hash found as the 0'th element of a pseudo-hash is not legal. Index values must be at 1 or greater. See L<perlref>. =item Bareword "%s" refers to nonexistent package (W) You used a qualified bareword of the form C<Foo::>, but the compiler saw no other uses of that namespace before that point. Perhaps you need to predeclare a package? =item); =item Can't check filesystem of script "%s" for nosuid (P) For some reason you can't check the filesystem of the script for nosuid. =item Can't coerce array into hash (F) You used an array where a hash was expected, but the array has no information on how to map from keys to array indices. You can do that only with arrays that have a hash reference at index 0. =item Can't goto subroutine from an eval-string (F) The "goto subroutine" call can't be used to jump out of an eval "string". (You can use it to jump out of an eval {BLOCK}, but you probably don't want to.) =item Can't localize pseudo-hash element (F) You said something like C<local $ar-E<gt>{'key'}>, where $ar is a reference to a pseudo-hash. That hasn't been implemented yet, but you can get a similar effect by localizing the corresponding array element directly -- C<local $ar-E<gt>[$ar-E<gt>[0]{'key'}]>. =item Can't use %%! because Errno.pm is not available (F) The first time the %! hash is used, perl automatically loads the Errno.pm module. The Errno module is expected to tie the %! hash to provide symbolic names for C<$!> errno values. =item Cannot find an opnumber for "%s" (F) A string of a form C<CORE::word> was given to prototype(), but there is no builtin with the name C<word>. %s: Eval-group in insecure regular expression (F) Perl detected tainted data when trying to compile a regular expression that contains the C<(?{ ... })> zero-width assertion, which is unsafe. See L<perlre/(?{ code })>, and L<perlsec>. =item %s: Eval-group not allowed, use re 'eval' (F) A regular expression contained the C<(?{ ... })> zero-width assertion, but that construct is only allowed when the C<use re 'eval'> pragma is in effect. See L<perlre/(?{ code })>. =item %s: Eval-group not allowed at run time (F) Perl tried to compile a regular expression containing the })>. =item Explicit blessing to '' (assuming package main) (W) You are blessing a reference to a zero length string. This has the effect of blessing the reference into the package main. This is usually not what you want. Consider providing a default target package, e.g. bless($ref, $p || 'MyPackage'); =item Illegal hex digit ignored (W) You may have tried to use a character other than 0 - 9 or A - F in a hexadecimal number. Interpretation of the hexadecimal number stopped before the illegal character. =item No such array field (F) You tried to access an array as a hash, but the field name used is not defined. The hash at index 0 should map all valid field names to array indices for that to work. =item. =item Out of memory during ridiculously large request (F) You can't allocate more than 2^31+"small amount" bytes. This error is most likely to be caused by a typo in the Perl program. e.g., C<$arr[time]> instead of C<$arr[$time]>. =item Range iterator outside integer range (F) One (or both) of the numeric arguments to the range operator ".." are outside the range which can be represented by integers internally. One possible workaround is to force Perl to use magical string increment by prepending "0" to your numbers. =item Recursive inheritance detected while looking for method '%s' in package '%s' (F) More than 100 levels of inheritance were encountered while invoking a method. Probably indicates an unintended loop in your inheritance hierarchy. =item B<pairs>. %hash = { one => 1, two => 2, }; # WRONG %hash = [ qw/ an anon array / ]; # WRONG %hash = ( one => 1, two => 2, ); # right %hash = qw( one 1 two 2 ); # also fine =item Undefined value assigned to typeglob (W) An undefined value was assigned to a typeglob, a la C<*foo = undef>. This does nothing. It's possible that you really mean C<undef *foo>. =item C<&> prefix, or using a package qualifier, e.g. C<&our()>, or C<Foo::our()>. =item L<perllocale/"LOCALE PROBLEMS">. =back =head1 Obsolete Diagnostics =over =item Can't mktemp() (F) The mktemp() routine failed for some reason while trying to process a B<-e> switch. Maybe your /tmp partition is full, or clobbered. Removed because B<-e> doesn't use temporary files any more. =item Can't write to temp file for B<-e>: %s (F) The write routine failed for some reason while trying to process a B<-e> switch. Maybe your /tmp partition is full, or clobbered. Removed because B<-e> doesn't use temporary files any more. =item Cannot open temporary file (F) The create routine failed for some reason while trying to process a B<-e> switch. Maybe your /tmp partition is full, or clobbered. Removed because B<-e> doesn't use temporary files any more. =item L<perlre>. =back =head1 Configuration Changes Gurusamy Sarathy <F<gsar@umich.edu>>, with many contributions from The Perl Porters. Send omissions or corrections to <F<perlbug@perl.com>>. =cut
|
https://metacpan.org/changes/release/LBROCARD/perl5.005_03-MAINT22213
|
CC-MAIN-2017-30
|
refinedweb
| 3,582
| 58.38
|
On Sat, Aug 14, 2010 at 2:38 AM, michael rice <nowgate at yahoo.com> wrote: > > The program below takes a text file and unwraps all lines to 72 columns, but I'm getting an end of file message at the top of my output. > > How do I lose the EOF? > > Michael > While many other people have shown you why you need not necessarily answer this question, I think it'd be helpful for you to hear the answer anyway. Your message is being produced because you are trying to getLine when there is no input left. This raises an exception, which, because it is not handled by your program, prints a diagnostic message and exits. Strangely, it prints this before the output of your program - this isn't terribly important, but for the sake of completeness, it's because of the different buffering characteristics of stdout and stderr, which confusingly mean that even though your program produces output and then produces an error, the error is printed immediately while the output waits until the program is terminated to be produced. I think. Something like that, anyway. So, how do you avoid the exception? You can use System.IO.isEOF [1] to check if there is input available on the standard input handle: main = do eof <- isEOF when (not eof) realMain -- when from Control.Monad, see also: unless where realMain = do realStuff Or you can let getLine throw the exception, but catch it and deal with it yourself, rather than letting it kill your program. Catching it is a little less simple, but is considerably more flexible and powerful. The exceptions situation in Haskell is somewhat complicated by the fact that the mechanism used by haskell98 has been improved upon, but the new extensible mechanism is incompatible with the old so both have to hang around. Have a look at Control.Exception [2] and System.IO.Error [3]. In either case you have 'catch' as a sort of basic operation, and more convenient things like 'try' which sort of turn an exception into a pure Either result. I'd do something like this: main = do result <- try getLine case result of Left err -> return () -- or do something diagnostic Right "" -> putStrLn "" >> main Right line -> doStuffWith line On a more general note, your main function looks a little suspect because it *always* recurses into itself - there's no termination condition. A question nearly as important as "how does my program know what to do" is "how does it know when to stop" :) [1] [2] [3]
|
http://www.haskell.org/pipermail/haskell-cafe/2010-August/082014.html
|
CC-MAIN-2014-10
|
refinedweb
| 423
| 58.11
|
Lori Pearce's WebLogAll Things SDK Evolution Platform Developer Build (Build: 5.6.50428.7875)2005-08-02T09:39:00ZIt's Time for the Final Post<P>Friday, December 7th will be my last full day in the office at Microsoft. December 31st will be my last day as a Microsoft employee.</P> <P.</P> <P>I'll be spending the next year working on some home remodeling projects, spending more time in Hawaii and California and in my garden. After that, it will be time to catch up on my traveling and scuba diving.</P> <P> I leave you with two quotes I've grown fond of recently:<>Doubt is not a pleasant condition, but certainty is absurd.</FONT></SPAN></A><FONT face=Calibri> <?xml:namespace prefix = o<o:p></o:p></FONT><>Voltaire</FONT></A><FONT face=Calibri> (1694 - 1778)</FONT></SPAN></B><SPAN style="FONT-SIZE: 11.5pt; COLOR: #454545; LINE-HEIGHT: 120%"><FONT face=Calibri> <o:p></o:p></FONT></SPAN><>Time is an illusion. Lunchtime doubly so.</FONT></SPAN></A><FONT face=Calibri> </FONT></SPAN><SPAN style="FONT-SIZE: 11.5pt; COLOR: #454545; LINE-HEIGHT: 120%; mso-no-proof: yes"><=Picture_x0020_36<v:imagedata<FONT face=Calibri></FONT></v:imagedata></v:shape></SPAN><SPAN style="FONT-SIZE: 13pt; COLOR: #454545; LINE-HEIGHT: 120%"><o:p></o:p><>Douglas Adams</FONT></A><FONT face=Calibri> (1952 - 2001)</FONT></SPAN></B><SPAN style="FONT-SIZE: 11.5pt; COLOR: #454545; LINE-HEIGHT: 120%"><FONT face=Calibri> <o:p></o:p></FONT></SPAN></P> <P>Lori Pearce</P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive and the Optimistic Brain<P>Two articles caught my attention this week. The first was <A class="" title="Mossberg on SYNC" href="" mce_href="">Walt Mossberg's review of SYNC</A>, a joint project between Ford and Microsoft. </P> <BLOCKQUOTE> .)"</P></BLOCKQUOTE> <P>The fact that this system works with just about any USB media device (and not just an IPod) is great news for those of us who prefer devices that don't lock you into one format or one music store. I am currently using a <A class="" title="Creative Zen" href="" mce_href="">Creative Zen</A> player; it's my second Creative Zen device and I really like how well it works with Windows Media Player. </P> <P>The other article that caught my attention was an article on <A class="" title="WSJ Science Journal" href="" mce_href="">optimism and the brain</A> by Robert Lee Hotz.</P> <BLOCKQUOTE> <P>."</P></BLOCKQUOTE> <P>Hope you enjoy learning about <A class="" title="Microsoft SYNC" href="" mce_href="">SYNC</A> and the optimistic brain!</P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive On-Line Color Thesaurus<P>Check out HP's on-line "Color Thesarus" <A class="" title="HP Color Thesarus" href="" mce_href="">here</A>. I submited the ever popular "Burnt Sienna" and it displayed a color square, listed the RGB values for Burnt Sienna and displayed plus four similar (synonym) colors and four antonym colors.</P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive great scientific visualization Nikon Small World Photomicrography competition results are stunning. Check out the winners at: <A href=""></A> .<div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Visualization Challenge Winners<A class="" title=GMSVGMSV</A> pointed me to this interesting <A class="" title="2K7 VCW" href="" mce_href="">site</A> today. There are some folks doing incredible work with scientific visualization out there and 10 have been recognized in this artical. Check it out.<div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive even computers get the math wrong from time to time<P>There was a nice little blog post on <A class="" title=GMSVGood Morning Silicon Valley</A> that led to another, really interesting blog post titled "<A class="" title="Wolfram Blog" href="" mce_href="">Arithmetic is Hard--To Get Right</A>." Turns out there are "...exactly 12 instances out of the 9 quintillion possibilities it [Excel] goes completely bonkers" and 77.1 x 850 is one of them. </P> <P>I tried it and did indeed, get 10000 instead of 65535.</P> <P>The original post is <A class="" title=AppScouthere</A>. </P> <P mce_keep="true"> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive not go 64bit?<P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'"?<SPAN style="mso-spacerun: yes"> </SPAN>Seems like underutilization of expensive hardware to me…must make the hardware engineers cry themselves to sleep at night.<?xml:namespace prefix = o<o:p></o:p></SPAN></P> <P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'"?<o:p></o:p></SPAN></P> <P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'".<SPAN style="mso-spacerun: yes"> </SPAN.<o:p></o:p></SPAN></P> <P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">Of course, it’s a whole other story<SPAN style="mso-spacerun: yes"> </SPAN>when you are talking about server applications like SQL and Exchange.<SPAN style="mso-spacerun: yes"> </SPAN>They can take full advantage of what 64 bit OSs offer.<o:p></o:p></SPAN></P> <P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">Most folks will tell you that it's the lack of good device drivers on 64 bit that is holding up client adoption.<SPAN style="mso-spacerun: yes"> </SPAN>But apparently it’s more than that.<SPAN style="mso-spacerun: yes"> </SPAN>Today, there was an <A href="">article</A> on <A href="">vnunet.com </A><SPAN style="mso-spacerun: yes"> </SPAN>about how poorly anti-virus software is doing on 64 bit Windows Vista.<o:p></o:p></SPAN></P> <P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">And where are the 64 bit games?<SPAN style="mso-spacerun: yes"> It s</SPAN>eems like some of the higher end games could take advantage of 64 bit.<SPAN style="mso-spacerun: yes"> I figure t</SPAN>hey are likely to be waiting on the device drivers and watching the 64bit OS sales figures.<o:p></o:p></SPAN></P> <P><SPAN style="FONT-SIZE: 10pt; FONT-FAMILY: 'Arial','sans-serif'">I believe that when Microsoft starts producing 64 bit versions of its flagship client applications (Office, Visual Studio, etc), we will finally start to see the migration from 32 bit to 64 bit OS installs.<SPAN style="mso-spacerun: yes"> </SPAN>Other developers will follow our lead.<SPAN style="mso-spacerun: yes"> </SPAN>Question is, when will we step up?<o:p></o:p></SPAN></P> <P mce_keep="true"> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive pause that refreshes...<P>Check out this article on an interesting study done by Stanford researchers on what the brain is doing during pauses.</P> <DIV class=articleTitle><A class="" href="" mce_href="">When the music stops, the brain gets going</A></DIV><!--subtitle--> <DIV class=articleSubTitle>IN STANFORD STUDY, SILENT PAUSES LEND CLUES ON MENTAL PROCESSES</DIV><!--byline--> <DIV class=articleByline>By Lisa M. Krieger<BR>Mercury News</DIV> <P><!--date--> </P> <P mce_keep="true"> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive sites to read instead of this one...<P class=MsoNormal<FONT face=Calibri size=3>Why has there been no posting here in a very long time?<SPAN style="mso-spacerun: yes"> </SPAN>Frankly, it’s because I find reading other people’s content more interesting than writing or reading my own. If my blog is not interesting to me, why would it be interesting to you?<SPAN style="mso-spacerun: yes"> </SPAN>On the off chance that you’ll find any of the sites I read regularly as interesting as I do, <SPAN style="mso-spacerun: yes"> </SPAN>this blog post is for you.</FONT></P> <P class=MsoListParagraph<SPAN style="mso-bidi-font-family: Calibri; mso-bidi-theme-font: minor-latin"><SPAN style="mso-list: Ignore"><FONT face=Calibri size=3>1.</FONT><SPAN style="FONT: 7pt 'Times New Roman'"> </SPAN></SPAN></SPAN><FONT size=3><FONT face=Calibri><SPAN style="mso-spacerun: yes"> </SPAN>I read the local news online—I haven’t read an actual hold-in-your-hands newspaper in a long time.<SPAN style="mso-spacerun: yes"> </SPAN>For local news I go to the following web sites:<SPAN style="mso-spacerun: yes"> </SPAN></FONT></FONT><A href="" mce_href=""><FONT face=Calibri size=3>The Seattle Times</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>The Seattle Post-Intelligencer</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>KOMO TV</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>KIRO TV</FONT></A><FONT face=Calibri size=3>.</FONT></P> <P class=MsoNormal<?xml:namespace prefix = o<o:p><FONT face=Calibri size=3> </FONT></o:p></P> <P class=MsoNormal<FONT face=Calibri size=3>Why don’t I check out </FONT><A href="" mce_href=""><FONT face=Calibri color=#0000ff size=3>NWCN</FONT></A><FONT face=Calibri size=3> or </FONT><A href="" mce_href=""><FONT face=Calibri size=3>KING5</FONT></A><FONT face=Calibri size=3>?<SPAN style="mso-spacerun: yes"> </SPAN>Because they want me to register and that bugs me—I avoid sites that require registration whenever possible.<SPAN style="mso-spacerun: yes"> </SPAN>Yeah, I know, I could just provide an anonymous Hotmail account, but why bother?<SPAN style="mso-spacerun: yes"> </SPAN>There are plenty of places to get the news.</FONT></P> <P class=MsoNormal<FONT face=Calibri size=3>I also read a </FONT><A href="" mce_href=""><FONT face=Calibri size=3>SFGate</FONT></A><FONT face=Calibri size=3> since I spent the first 30 years of my life in the Bay Area.<SPAN style="mso-spacerun: yes"> </SPAN>Occasionally I check out the </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Marin Independent Journal</FONT></A><FONT face=Calibri size=3>, the </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Sacramento Bee<>), </FONT></FONT><A href="" mce_href=""><FONT face=Calibri size=3>The Mercury News</FONT></A><FONT face=Calibri size=3> and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>KCRA</FONT></A><FONT face=Calibri size=3> (not nearly as good as KOMO or KIRO) since I have friends and family in the Bay Area and in the Sacramento area.</FONT></P> <P class=MsoNormal<FONT face=Calibri size=3>Another site that makes my required reading list is the </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Bridges Detail</FONT></A><FONT face=Calibri size=3> traffic flow map.< size=3><FONT face=Calibri>For national and international news I check out the usual suspects:<SPAN style="mso-spacerun: yes"> </SPAN></FONT></FONT><A href="" mce_href=""><FONT face=Calibri size=3>CNN</FONT></A><FONT face=Calibri size=3> and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>BBC</FONT></A><FONT face=Calibri size=3> and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>The Wall Street Journal</FONT></A><FONT face=Calibri size=3> (Microsoft employees have access).<SPAN style="mso-spacerun: yes"> </SPAN>I get my stock quotes from </FONT><A href="" mce_href=""><FONT face=Calibri size=3>MSN</FONT></A><FONT face=Calibri size=3>—I am sure there are better sites, but MSN is easy.<SPAN style="mso-spacerun: yes"> </SPAN>I also get </FONT><A href="" mce_href=""><FONT face=Calibri size=3>movie times</FONT></A><FONT size=3><FONT face=Calibri> from MSN.<SPAN style="mso-spacerun: yes"> </SPAN>The main MSN site is a little too “pop culture” for me.<SPAN style="mso-spacerun: yes"> </SPAN></FONT></FONT><A href="" mce_href=""><FONT face=Calibri size=3>Wikipedia</FONT></A><FONT face=Calibri size=3> is also a frequent source of quick info.<>For sports (mostly baseball), I occasionally check out a game with </FONT><A href="" mce_href=""><FONT face=Calibri size=3>ESPN’s GameCast</FONT></A><FONT face=Calibri size=3> or listen in with MLB’s </FONT><A href="" mce_href=""><FONT face=Calibri color=#0000ff size=3>GameDay Audio</FONT></A><FONT face=Calibri size=3>.<>4.</FONT><SPAN style="FONT: 7pt 'Times New Roman'"> </SPAN></SPAN></SPAN><FONT face=Calibri size=3>For tech related news I go to </FONT><A href="" mce_href=""><FONT face=Calibri size=3>CNET</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>ZDNet</FONT></A><FONT face=Calibri size=3> (yeah…I know…it’s mostly the same content), </FONT><A href="" mce_href=""><FONT face=Calibri size=3>InfoWorld</FONT></A><FONT face=Calibri size=3> (I still remember when I used to read the actual hardcopy) and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Silicon Valley.Com</FONT></A><FONT face=Calibri size=3>.<SPAN style="mso-spacerun: yes"> </SPAN>I have been a fan of </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Good Morning Silicon Valley</FONT></A><FONT face=Calibri size=3> for many years and have recently added </FONT><A href="" mce_href=""><FONT face=Calibri size=3>All Things Digital</FONT></A><FONT face=Calibri size=3> to my list of regularly sites after </FONT><A href="" mce_href=""><FONT face=Calibri size=3>John Paczkowski</FONT></A><FONT size=3><FONT face=Calibri> moved there (and Mossberg is always worth a read too <>). I used to visit a lot of other tech related sites but got fed up with ads that cover the screen or the ads they make you watch or skip before getting to the real site.<SPAN style="mso-spacerun: yes"> </SPAN></FONT><>5.</FONT><SPAN style="FONT: 7pt 'Times New Roman'"> </SPAN></SPAN></SPAN><FONT face=Calibri size=3>I am a good corporate citizen and use </FONT><A href="" mce_href=""><FONT face=Calibri size=3></FONT></A><FONT face=Calibri size=3> as my search site.<SPAN style="mso-spacerun: yes"> </SPAN>It works great for me, but if ever fails me, I know who to send feedback to.<SPAN style="mso-spacerun: yes"> </SPAN>My home page at work is the internal Microsoft Web site.<SPAN style="mso-spacerun: yes"> </SPAN>They revamp and refresh the site from time to time and I think they do an excellent job on it overall.<SPAN style="mso-spacerun: yes"> </SPAN>In general, Microsoft has a wealth of internal websites with all the information you could ever need…until they don’t and then you’re hosed and have to find a real, live person to talk to.<SPAN style="mso-spacerun: yes"> </SPAN>Easier said than done.<>6.</FONT><SPAN style="FONT: 7pt 'Times New Roman'"> </SPAN></SPAN></SPAN><FONT face=Calibri><FONT size=3>What do I read “for fun”?<SPAN style="mso-spacerun: yes"> </SPAN>Not much—for fun I usually turn to actual hardcopy books—but I do have a few I check out from time to time.<SPAN style="mso-spacerun: yes"> </SPAN></FONT></FONT><A href="" mce_href=""><FONT face=Calibri size=3>Wet Pixel</FONT></A><FONT face=Calibri size=3> is one of my favorite scuba related sites.<SPAN style="mso-spacerun: yes"> </SPAN>Their </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Photo of the Week</FONT></A><FONT face=Calibri size=3> contest is wonderful.<SPAN style="mso-spacerun: yes"> </SPAN>I also check out </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Kona Web</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Waikoloa Weather</FONT></A><FONT face=Calibri size=3> and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>West Hawaii Today<>) for news about my favorite places in Hawaii.</FONT><>7.</FONT><SPAN style="FONT: 7pt 'Times New Roman'"> </SPAN></SPAN></SPAN><FONT size=3><FONT face=Calibri>And lastly, there are shopping sites.<SPAN style="mso-spacerun: yes"> </SPAN>In general, I hate shopping and shopping malls, so I am an internet retailer’s dream customer.<SPAN style="mso-spacerun: yes"> </SPAN></FONT></FONT><A href="" mce_href=""><FONT face=Calibri size=3>Lands’ End</FONT></A><FONT face=Calibri size=3> and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>LL Bean</FONT></A><FONT face=Calibri size=3> (I swear those two companies were separated at birth), </FONT><A href="" mce_href=""><FONT face=Calibri color=#0000ff size=3>Coldwater Creek</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Amazon.Com</FONT></A><FONT face=Calibri size=3>, and occasionally </FONT><A href="" mce_href=""><FONT face=Calibri size=3>TravelSmith</FONT></A><FONT face=Calibri size=3>, </FONT><A href="" mce_href=""><FONT face=Calibri size=3>Orvis</FONT></A><FONT face=Calibri size=3>, and </FONT><A href="" mce_href=""><FONT face=Calibri size=3>FrontGate</FONT></A><FONT face=Calibri size=3>. With the exception of Amazon, I get paper catalogs from all those companies—the USPS must really hate me around the holidays.</FONT></P> <P class=MsoListParagraphCxSpLast<o:p><FONT face=Calibri size=3> </FONT></o:p></P> <P class=MsoNormal<FONT size=3><FONT face=Calibri>Now that I have bored you silly, I’ll sign off.<SPAN style="mso-spacerun: yes"> </SPAN></FONT></FONT></P> <P class=MsoNormal<FONT size=3><FONT face=Calibri><SPAN style="mso-spacerun: yes"> Lori</SPAN></FONT></FONT></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive's about time...<P><FONT face=Verdana>Hack, cough, cough...man, it's getting really dusty around here...</FONT></P> <P><FONT face=Verdana>Yeah...I know...it's been a while...my bad. No excuses.</FONT></P> <P><FONT face=Verdana>Let me get straight to the new data. The Windows SDK Team recently posted the RC1 version of the Windows SDK for Windows Vista and .NET 3.0 RC1. You can download it </FONT><A href=""><FONT face=Verdana>here</FONT></A><FONT face=Verdana>.</FONT></P> <P><FONT face=Verdana>This summer, we welcomed 7 new team members: </FONT><A href=""><FONT face=Verdana>Tom Archer</FONT></A><FONT face=Verdana>, Karen Dominguez, </FONT><A href=""><FONT face=Verdana>Abhita Chugh</FONT></A><FONT face=Verdana>, Lisa Supinksi, </FONT><A href=""><FONT face=Verdana>Sean Grimaldi</FONT></A><FONT face=Verdana>, Pat Litherland and just this week, Shawn Henry. It's exciting to have so many new faces on the team. I can feel the energy and enthusiams as the newbies dive in to their new roles.</FONT></P> <P> </P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive to the Windows SDK Team Tom!<P><FONT face=Verdana>I'd like to use this post to welcome Tom Archer to the Windows SDK Team. Today is Tom's official first day--though he's been working with us for many months in his prior role as Content Strategist for MSDN.</FONT></P> <P><FONT face=Verdana.</FONT></P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Windows SDK Team is Hiring<P><FONT face=Verdana>We have three Program Manager Openings:</FONT></P> <UL> <LI><FONT face=Verdana><A href="">Program Manager for SDK Tools</A></FONT></LI> <LI><FONT face=Verdana><A href="">Program Manager for SDK Docs</A></FONT></LI> <LI><FONT face=Verdana><A href="">Program Manager for SDK/WinFX/Orcas</A></FONT></LI></UL> <P><FONT face=Verdana.</FONT></P> <P><FONT face=Verdana>If you're a customer focused person who thinks software development can change the world, come join us on the Windows SDK Team.</FONT></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive<P.</P> <P>The gallery can be seen <A HREF="/photos/lori_pearce_msft/default.aspx">here</A>.</P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Windows SDK Team Has A Blog Of Its Own.<FONT face=Verdana size=4>Check out the new </FONT><A HREF="/windowssdk/"><FONT face=Verdana size=4>Windows SDK Team Blog</FONT></A><FONT face=Verdana size=4>. Today is the kickoff and hopefully it will be a busy place full of useful information about the Windows SDK, the Team and Windows Vista.</FONT><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive is the Windows SDK so big?<p><font face=Verdana color=#000000>The flippant answer is: "Because old APIs never die, we just add new ones."</font></p> <p><font face=Verdana color=#000000>The biggest single part of the SDK is the documentaion. The biggest part of the documentation is the WinFX API reference. </font></p> <p><font face=Verdana color=#000000>Below is a breakdown of the January CTP:</font></p> <p><font face=Verdana color=#000000> Win32: 211 MB (reference and conceptual)</font></p> <p><font face=Verdana color=#000000> WinFX: 467 MB</font></p> <p><font face=Verdana color=#000000> - Conceptual/Tools/GenRef/Portals: 47.3 MB</font></p> <p><font face=Verdana color=#000000> - Integrated Samples: 103 MB</font></p> <p><font face=Verdana><font color=#000000> - <strong>Managed Ref: 253 MB</strong></font></font></p> <p><font face=Verdana color=#000000> - Collection-level files: 63.7 MB</font></p> <p><font face="Trebuchet MS" color=#000000>As you can see, the managed API reference pages alone are over 250 MB (that's in a <em>compressed</em> help file). These represent 80 assemblies with 281 namespaces and 10741 types with 103704 members. Each one has a reference page.</font></p> <p><font face="Trebuchet MS" color=#000000.</font></p> <p><font face="Trebuchet MS">The other key parts of the Windows SDK include the tools. In the January CTP we ship a bunch of C++ compilers and other tools.</font></p> <p><font face="Trebuchet MS">Last but not least, are the samples that exist only in the file system--most of the Win32 samples fall into this bucket. Luckily, these compress very well for download.</font></p><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive kinda moldy around here...<P>...and I don't just mean because of all the rain we've had this winter either.</P> <P>The January CTP is out the door. We've noticed an increase in the number of issues with the install of the SDK and I wanted to let folks know why they are occuring.</P> <P.</P> <P.</P> <P>We also hope to have the Web Install back for February with custom install options that allow you to choose which components to install or not install. This should help with the horrendous download size.</P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive SDK for the WinFX Runtime Components November CTP<DIV><FONT face=Arial>I want to pass along some information about the Windows SDK for WinFX Runtime Components November CTP. </FONT></DIV> <P></P> <DIV><FONT face=Arial>As you know, WinFX is an important part of Windows Vista™. As such, the WinFX SDK is now part of the Windows SDK. The SDK team started the work to combine these two behemoth SDKs (PSDK+WinFX SDK) in October and will complete this work early in 2006. </FONT></DIV> <DIV> </DIV> <DIV><FONT face=Arial>For the November CTP of WinFX, we have provided a snapshot of one of our daily builds of the newly <I style="mso-bidi-font-style: normal">recombined</I> Windows SDK (those of you who went to PDC 2003 might remember the Longhorn SDK). This SDK is not at the level of quality that you are used to seeing from us (even for a CTP). We have much more work ahead of us to properly integrate the two SDKs, but for now, everything is crammed together in one big package. I hope you will be patient while we work to combine these two large SDKs into one all encompassing SDK for the Windows platform.</FONT></DIV> <DIV><FONT face=Arial></SPAN></FONT></DIV> <P><SPAN style="FONT-FAMILY: Arial">It's very important to read the <A href="">README.HTM </A><I style="mso-bidi-font-style: normal">before</I> downloading and installing the November CTP SDK. Don't skip this step or you might regret it.</SPAN></P> <P><SPAN style="FONT-FAMILY: Arial"><SPAN style="FONT-FAMILY: Arial">Here are some of the gotchas for the upcoming release (much more detail is provided in the README):</SPAN><SPAN style="FONT-FAMILY: Arial"> <?xml:namespace prefix = o /><o:p></o:p></SPAN></P> <OL dir=ltr> <LI> <DIV class=MsoNormal<SPAN style="FONT-FAMILY: Arial">We are only providing an ISO DVD image. It's <I style="mso-bidi-font-style: normal">really</I> big. 'Nuff said.< should <U>NOT</U> be installed on any currently available build of Windows Vista. It is only supported on Windows XP and Windows Server 2003 as is the WinFX RC November CTP.< only supports the November CTP of the <U>WinFX Runtime Components</U>. Therefore, it only supports <I style="mso-bidi-font-style: normal">managed</I> code development and not native Win32 code development (despite the fact that there are a whole bunch of Win32 headers, libs, samples and documentation in it).<SPAN style="mso-spacerun: yes"> </SPAN>Just ignore the man behind the curtain.">Custom install is not even closed to finished, and frankly doesn’t work very well yet.<SPAN style="mso-spacerun: yes"> </SPAN>You will be able to choose between docs, samples and tools and not much else.<SPAN style="mso-spacerun: yes"> </SPAN>It will eventually get more granular, but it’s going to take us a release or two to get it right (with your help and feedback).">With a work around or two (see the release notes), you can probably do x64 managed code development, but we did not do a full test pass on that, so we don't know how well it will work. We did not do any test pass on IA64.<o:p></o:p></SPAN></DIV></LI></OL> <P class=MsoNormal<SPAN style="FONT-FAMILY: Arial"><o:p></o:p></SPAN></P> <P class=MsoNormal<SPAN style="FONT-FAMILY: Arial">The supported install order is:<o:p></o:p></SPAN></P> <OL> <LI> <DIV class=MsoNormal<SPAN style="FONT-FAMILY: Arial">VS 2005 RTM (optional) (<A href="">DevCenterLink<">WinFX RC November CTP (<A href="">LINK<">Window SDK November CTP (<A href="">LINK</A></SPAN><SPAN style="FONT-FAMILY: Arial">)</SPAN></DIV> <LI> <DIV class=MsoNormal<SPAN style="FONT-FAMILY: Arial">VS 2005 Extensions for WinFX RC November CTP (optional) (<A href="">LINK</A>)</SPAN></DIV></LI></OL> <P class=MsoNormal<SPAN style="FONT-FAMILY: Arial">So, if I haven’t totally put you off downloading the new Windows SDK for the WinFX November CTP, knock yourself out!<SPAN style="mso-spacerun: yes"> </SPAN></SPAN></P></FONT> <DIV><BR>Lori Pearce [MSFT]<BR>Windows SDK Team</DIV></SPAN><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Four at the 2005 PDC<P>Today.</P> <P>I’m going to attend Adam Nathan’s FUN318, “Using Win32/WinFX Integration to Light-Up on Windows Vista: A Case Study” at 5:15 in Halls C&D if there is room.</P> <P>Brent Rector’s FUNL02, “Lap around the WinFX and Win32 SDKs” is being repeated at noon on Friday in 406 AB.</P> <P>I head home tomorrow morning. I hope the diehards that stay through the last panel have a great time. I’ve seen lots of glazed looks already today—a sure symptom of information overload.</P> <P>‘Till the next PDC!</P> <P>Lori Pearce<BR>Windows SDK Team<BR></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Official Day Two<P>As usual, the PDC started with keynotes today. The morning started with Eric Rudder and David Treadwell talking about Windows WorkFlow Foundation followed by <a href="">Steven Sinofsky </A>talking about the new developer features in Office 12. Both presentations went off without a hitch. The highlight was when Steven mimicked the Jim Allchin PDC special, limited time offer and whipped out the Office Steak Knives set. His timing was perfect and the audience loved it.</P> <P>I was fortunate to join <a href="">Raymond Chen </A>at lunch with a first time PDC attendee. Raymond, who, like myself, doesn’t get the “attend” PDCs (only speak at them), wondered what strategy customers employed to decide which sessions to attend. Our customer said that he first highlights <EM>all</EM> the sessions that look interesting and then determines which conflict. After that, tough choices have to be made. Other customers come with clear agendas and try to cover everything that fits their area of interest.</P> <P>The <A href="">Windows Vista Development Forums </A>are up and running with 21 threads as of this writing. Check them out!</P> <P> </P> <P><BR> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Windows Vista Development Forums<P>The following Windows Vista Development forums are now live on <A href=""></A></P> <P>Data Access, Storage, Search and Organize in Windows Vista<BR><A href=""></A></P> <P>Mobile PC and Tablet PC Development<BR><A href=""></A></P> <P>Networking in Windows Vista<BR><A href=""></A></P> <P>Security for Applications in Windows Vista<BR><A href=""></A></P> <P>UI Development for Windows Vista<BR><A href=""></A></P> <P>Windows Communication Foundation ("Indigo")<BR><A href=""></A></P> <P>Windows Presentation Foundation ("Avalon")<BR><A href=""></A></P> <P>Windows Vista Development General<BR><A href=""></A></P> <P>Windows Vista SDK<BR><A href=""></A></P> <P> </P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Official Day One<P>It’s already Tuesday, the official first day of the PDC. I started the day with a nice 20 minute walk from my hotel to the LACC. I arrived at 7:30 am and there was already a line waiting to get into the keynote hall.</P> <P>The organizers ushered all the Microsoft employees into the overflow room to make sure there were plenty of good seats for customers in the main hall. Once the keynote started and all customers were seated, they allowed Microsoft employees to fill the seats in the back.</P> <P.</P> <P>After the keynote, I headed to the “Women and Technology: Dream, Code, Run” panel. The room filled quickly with women and a handful of men. It’s rare that I am in a room talking technology with 95% women instead of 95% men. Kinda fun.</P> <P.</P> <P>Hari Sekhar said that our first ILL was well attended. Mike Mueller was the instructor. Mike and Jeff Chrisope are sharing instructor duties for our labs. Don’t miss it if you’re here at the PDC!</P> <P>That’s all for now!</P> <P>Lori Pearce<BR>Windows SDK Team<BR></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Pre Conf Day Two<P>Yesterday we had tri-athletes and movie crews closing streets and snarling traffic in and around the convention center in LA. Today it was a power outage that apparently affected nearly the entire LA basin that managed to do the same. According to the <A href="">LA Times web site</A>, somebody cut a line they weren’t supposed to. Ooops. Ah well, there’s never a dull moment here in Los Angeles at the PDC. It was a little concerning that it happened just a day after they played that ex-OC twerp’s video threatening LA and Melbourne though.</P> <P>But all is well here in LA…at least as far as the PDC is concerned. Everything is back to normal, the wireless is working well and the place is filling up. I have seen most of my team members already and we’re ready to go. Things seem to be running smoothly and today, like yesterday, the registration lines were short or non-existent (at least by the afternoon that is).</P> <P>I am looking forward to the keynotes tomorrow and the start of regular sessions. There is going to be a ton of energy and excitement here.</P> <P>Signing off for now. If something else of interest occurs (and I have power and wireless) I’ll blog again today.</P> <P>Lori Pearce<BR>Product Unit Manager<BR>Windows SDK Team</P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Pre Conf Day One<P>Getting up at 5am this morning made me realize that the long days of Summer are just about over; it was dark out and it was raining. Ick. It only took about 20 minutes to drive to the Seattle-Tacoma (SeaTac) International Airport at that early hour of the morning so I was sitting at the gate by 6:45; there isn’t much traffic at security screening on an early Sunday morning either.</P> <P>After securing a caffeinated beverage at the nearest C-Concourse Starbucks, I met Shoshanna Budzianowski of the Visual Studio Tools for Office (VSTO) team at the gate. One of her teammates mentioned that he had a rental car so Sho and I had a ride to the hotel secured once we landed in Los Angeles. Wahoo!</P> <P>We saw PDC banners before we even left the airport area.</P> <P>Getting to dowtntown was easy...getting around downtown was another story. Apparently the Los Angeles Triathlon was winding through the downtown streets perilously close to the Los Angeles Convention Center (LACC) so we ended up taking a twisty-turny route to the Westin Bonaventure. I checked into my modest, but nice room, unpacked and headed for the shuttles to take me down to the LACC. </P> <P>There was no waiting to register at noon; I bet Tuesday morning will be quite different. After securing my badge, T-shirt and PDC Bag, I headed to the "Big Room"...it actually has another nickname whose acronym is a synonym for "tavern", but this is a friendly, family blog so I won’t repeat it.</P> <P>In the Big Room I met up with Derek Newkirk (SDK Test) and Mitch Walker (SDK Program Management). There were setting up our machines in the Pavilion and the Hands on Labs areas. I handed over the Windows Vista disk that I brought since the disk that Mitch brought seemed to be scratched or something.</P> <P>From there I grabbed a quick lunch, said “Hi” to Steve Cellini (he’s the guy charge of this incredible event) and sat down in the Fundamentals Track Lounge to write this blog entry (yes, there is wireless at the PDC). Everything looks great and I think the Big Room is going to work out well. Did I mention that the Windows SDK Team Group Program Manager, Steve Goulet, is the Fundamentals Track owner? He has been working like a dog for many months with a lot of other talented Microsoft folks to pull together all the content in that Track. It will be terrific, so don't miss it if you are here at the PDC. I'll be glad to have my GPM back when PDC is over.</P> <P>That's it for today. I’ve got some reading to do and I also hope to catch a football game this afternoon (it is the opening weekend for the NFL after all).</P> <P>Signing out from the Fundamentals Track Lounge in the Big Room at PDC 2005!</P> <P>Lori Pearce</P> <P>Product Unit Manager</P> <P>Windows SDK Team<BR></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive to PDC!<P><FONT face=Tahoma>On Sunday morning I leave for Los Angeles and the PDC. It's going to be a great conference and I look forward to meeting many of you there. </FONT></P> <P><FONT face=Tahoma>The SDK team will be holding a "Meet the SDK Team" gathering at the Tools and Languages Track Lounge on Tuesday and Thursday at 3pm. I'll also be hanging around the SDK booth in the Pavillion and the Hands On and Instructor Led Labs area. If I'm lucky, I'll be able to sneak into the back of some of the less crowded sessions as well.</FONT></P> <P><FONT face=Tahoma>See ya'll in LA!</FONT></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive Windows Vista Beta 1 is Here!<P><FONT face=Verdana>Last week was a very busy week around here and this week looks no different. </FONT></P> <P><FONT face=Verdana>Last week we had a bit of a problem with the WinFX SDK Web Install. While the problem was identified and quickly fixed, it still took a while to verify and therefore delayed customer availabilty. Eventually we got the Web Install and the ISO posted and so far we've not heard any problems. Thanks to everyone for their patience!</FONT></P> <P><FONT face=Verdana>We are now focused entirely on the Windows SDK for Vista Beta 1. This SDK will have lots of information on all the new native Vista APIs found in Beta 1 as well as the headers, libs and other necessary files for building unmanaged Vista applications.</FONT></P> <P><FONT face=Verdana>Next, we'll be working on SDK updates for the WinFX Runtime Components September 2005 CTP and the next IDW for Vista. So much for taking time off this summer! ;-)</FONT></P> <P><STRONG><FONT face=Verdana>Two SDKs one Experience</FONT></STRONG></P> <P><FONT face=Verdana>Right now, The Windows SDK and the WinFX SDK are separately installable SDKs. Eventually, the WinFX SDK will be a part of the Windows SDK (and separately selectable during custom install). The plan is that if both are installed, the developer will have one SDK experience on his/her desktop. </FONT></P> <P><FONT face=Verdana>Why not just merge the two together right now? WinFX CTPs ship more frequently than the Vista OS does. Also the WinFX CTPs are available publically and the Vista Betas go only to MSDN subscribers and folks on the beta program. Therefore, we like having the flexibility to ship the WinFX SDK separately from the Windows SDK during pre-release cycles.</FONT></P><div style="clear:both;"></div><img src="" width="1" height="1">MSDNArchive
|
http://blogs.msdn.com/b/loripe/atom.aspx
|
CC-MAIN-2016-30
|
refinedweb
| 6,539
| 53.21
|
Created on 2015-11-26 07:42 by airween, last changed 2015-11-26 17:54 by airween. This issue is now closed.
Looks like smtplib can send only messages, which contains only 7bit (ascii) characters. Here is the example:
# -*- coding: utf8 -*-
import time
import smtplib
mailfrom = "my@mydomain.com"
rcptto = "me@otherdomain.com"
msg = """%s
From: Me <%s>
To: %s
Subject: Plain text e-mail
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Disposition: inline
Content-Transfer-Encoding: 8bit
happy New Year
Ευτυχισμένο το Νέο Έτος
明けましておめでとうございます
с Новым годом
""" % (time.strftime('%a, %d %b %Y %H:%M:%S +0100', time.localtime()), mailfrom, rcptto)
server = smtplib.SMTP('localhost')
server.sendmail(mailfrom, rcptto, msg)
server.quit()
With Python2 (Python 2.7), this script finished succesfully. With Python3 (Python 3.4), I've got this execption:
Traceback (most recent call last):
File "8bittest.py", line 28, in <module>
server.sendmail(mailfrom, rcptto, msg)
File "/usr/lib/python3.4/smtplib.py", line 765, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 261-271: ordinal not in range(128)
Basicly, I don't understand, why smtplib allows only ascii encoded messages in Python 3. That worked (and works) in Python 2, and I think, that's the correct behavior.
Here is a workaround:
server.sendmail(mailfrom, rcptto, msg.encode("utf8"))
May be this would be better inside of smtplib?
Although that will work for text-only messages if you know what RFC format looks like, you really don't want to do that in the general case, since you can't express messages that have binary non-text content using unicode.. In 3.5 it even supports SMTPUTF8, if you know any servers that do :)
Oh, and as for why this worked in python2: in python2 strings were binary, not unicode, so the non-ascii stuff was already in bytes form.
David,
many thanks for your information.
I think my e-mail format was correct - I've copied it from a maildir, as an "email file".
As I wrote, there is a solution: before the code passes the 'msg' argument to sendmail() function, it needs to encode() it as "utf-8", then it will be a bytestream, instead of unicode (which is the default type of any string in Py3). Meanwhile I realized it :).
Thanks again, and sorry for my mistake.
|
https://bugs.python.org/issue25736
|
CC-MAIN-2020-05
|
refinedweb
| 400
| 68.06
|
Simplistic CSV example
This example is extremely simplistic... CSV may have commas embedded inside quoted strings, which this doesn't handle at all.
need help on reading csv file
hi, i need to read the fields in csv file and assign to var array in html for use . example a field in the csv name file ,need to <a href="file"> click to view</a> .how to assign ?
SD
hi this is fine... but how can i display those extracted data in JList... Thankx
Bug
The above code has bug. If i am having address as 3rd column in csv and my code is
while ((thisLine = myInput.readLine()) != null)
{
String[] data = null;
data = thisLine.split(",");
String address=(data[2]);
}
Its giving me error java
Java Read CSV file
.
Here is a csv file:
Example
import java.io.*;
import java.util.*;
public...Java Read CSV file
In this tutorial, you will learn how to read csv file.
CSV... and
there is no need of using any API to read these files. In the given example, we
have
Exporting data from mysql to csv file
example that retrieves the data from the database and save it into csv file...Exporting data from mysql to csv file Hi friends....
I want to export the data from mysql to csv file... i am having 30 columns in my database.. Eg
storing csv into oracle database
storing csv into oracle database i want jsp code for storing csv file into oracle database
Download CSV File from Database in JSP
Download CSV File from Database in JSP
... to download
CSV file from database in JSP. In this example, we have... a webpage "viewcsv.jsp""
to display and download the CSV
To Upload and insert the CSV file into Database
to upload a CSV file through JSP and
insert it into the database. For this, we have created two jsp pages page.jsp and upload_page.jsp.
The page.jsp is created...
To Upload and insert the CSV file into Database... this values to database table in correct coloumn using java or jsp. how can i do
|
http://www.roseindia.net/tutorialhelp/allcomments/129285
|
CC-MAIN-2014-52
|
refinedweb
| 349
| 76.72
|
This document describes how to create, update, and manage datasets in BigQuery.
Overview
A dataset is contained within a specific project. Datasets enable you by the
patchor
updateAPI methods.
- All tables referenced in a query must be stored in datasets in the same location.
- You can stream data into a US or EU dataset, but inserting data across these locations simultaneously can increase latency and error rates.
- When copying a table, the destination datasets must reside in the same location.
- If you export data from Google Analytics to BigQuery, the destination dataset must be in the US.
- If a dataset has 50,000 or more tables, it will become slower to enumerate them, whether through an API call, the web UI, or querying
__TABLES_SUMMARY__.
- Currently, no limit exists on the number of datasets per project. However, as you approach thousands of datasets in a project, web UI performance begins to degrade.
Creating datasets
When you create a dataset in BigQuery, the dataset name must be unique per project. The dataset name can:
- Contain up to 1,024 characters
- Contain letters (upper or lower case), numbers, and underscores
Dataset names cannot:
- Begin with a number or an underscore
- Contain spaces or special characters (such as &, @, or %)
Creating a dataset requires
bigquery.datasets.create permissions. The
following predefined IAM roles include
bigquery.datasets.create permissions:
For more information on IAM roles and permissions in BigQuery, see access control.
To create a dataset:
Web UI
To create a dataset using the web UI:
Click the down arrow icon
next to your project name in the navigation and click Create new dataset.
In the Create Dataset dialog:
- For Dataset ID, enter a unique dataset name.
For Data location, choose one of the following options:
- Unspecified (default): You have no preference on data location.
- US: BigQuery attempts to store your data in the US.
EU: Your Core BigQuery Customer Data resides in the EU.Core BigQuery Customer Data is defined in the Service Specific Terms.
For Data expiration, choose one of the following options:
- Never: Any table created in the dataset is never automatically deleted. You must delete them manually.
In [INTEGER] days: Any table created in the dataset is deleted after [INTEGER] days.
Click OK.
Command-line
Use the
bq mk command to create a new dataset. Optional parameters include
--data_location,
--default_table_expiration, and
--description:
bq mk --data_location [LOCALE] --default_table_expiration [INTEGER] --description [DESCRIPTION] [DATASET]
Where:
[DATASET]is the name of the dataset you're creating.
[LOCALE]is the data location, either US or EU. If omitted, the default value is "Unspecified".
[INTEGER]is the default lifetime (in seconds) for newly-created tables. The minimum value is 3600 seconds (one hour). The expiration time evaluates to the current time plus the integer value.
[DESCRIPTION]is a description of the dataset in quotes.
For example, the following command creates a dataset named
mydataset with
data location set to
US, a default table expiration of 3600 seconds (1 hour),
and a description of
This is my dataset.
bq mk --data_location US --default_table_expiration 3600 --description "This is my dataset." mydataset
API
Call
datasets.insert
and pass any relevant parameters.
When you create a dataset, you can also apply labels to it. For more information on dataset labels, see Using Labels.
Assigning access controls to datasets
You share access to BigQuery tables and views using project-level IAM roles and dataset-level access controls. Currently, you cannot apply access controls directly to tables or views.
Project-level access controls determine the users and groups allowed to access all datasets, tables, and views within a project. Dataset access controls determine the users (including service accounts) and groups allowed to access the tables and views in a specific dataset.
For example, if you assign the
bigquery.dataOwner role to a user at the project
level, that user can create, update, get, and delete tables and views in all of
the project's datasets. If you assign the
bigquery.dataOwner role at the dataset
level, the user can create, update, get, and delete tables and views only in that
dataset.
If you assign users or groups to a more restrictive role at the project level,
you must also grant access to individual datasets. For example, role, you must also assign access controls to each dataset the
user or group needs to access that wasn't created by the user.
For more information about project-level IAM roles and dataset access controls, see access control.
You can apply access controls to a dataset after the dataset is created using the command-line tool and the web UI. You can apply access controls during or after dataset creation using the API.
To assign access controls to a dataset:
Web UI
Click the drop-down arrow to the right of the dataset and choose Share Dataset.
In the Share Dataset dialog, for Add People, click the drop-down to the left of the field, and choose the appropriate option:
- chose User by e-mail, type the user's email address.
To the right of the Add People field, click Can view and choose the appropriate role from the list.
- "Can view" maps to the bigquery.dataViewer role.
- "Can edit" maps to the bigquery.dataEditor role.
- "Is owner" maps to the bigquery.dataOwner role.
Click Add and then click Save changes.
Command-line
Export the existing access controls to a JSON file using the
showcommand.
bq --format=json show [DATASET] >[DATASET].json
Where:
[DATASET]is the name of your dataset.
Make your changes to the "access" section of the JSON file. You can add or remove any of the special groups:
Project Owners,
Project Writers,
Project Readers, and
All Authenticated Users. You can also add any of the following:
User by e-mail,
Group by e-mail, and
Domain.
For example:
{ "access": [ { "role": "READER", "specialGroup": "projectReaders" }, { "role": "WRITER", "specialGroup": "projectWriters" }, { "role": "OWNER", "specialGroup": "projectOwners" } { "role": "READER", "specialGroup": "allAuthenticatedUsers" } { "role": "READER", "domain": "[DOMAIN_NAME]" } { "role": "WRITER", "userByEmail": "[USER_EMAIL]" } { "role": "READER", "groupByEmail": "[GROUP_EMAIL]" } ], } apply your access controls. For
more information, see Datasets.
Getting information about datasets
You can get information about datasets to which you have access using the web UI, the CLI, and the API.
Getting information about datasets requires
bigquery.datasets.get permissions.
All BigQuery IAM roles include
bigquery.datasets.get permissions
except for
bigquery.jobUser.
For more information on IAM roles and permissions in BigQuery, see Access control.
To get information about datasets:
Web UI
Click the dataset name. The Dataset Details page displays the dataset's description, details, and tables.
CLI
Issue the
bq show command:
bq show --format=prettyjson [DATASET]
Where:
[DATASET]is the name of the dataset.
For example, the following command displays information about
mydataset.
bq show --format=prettyjson mydataset
API
Call the
bigquery.datasets.get
API method and provide any relevant parameters.
Listing datasets
You can list datasets to which you have access using the CLI
bq ls command or
by calling the
bigquery.datasets.list
API method.
You can list datasets to which you have access using the web UI, the CLI, and the API.
Listing datasets requires
bigquery.datasets.list permissions. All BigQuery
IAM roles include
bigquery.datasets.list permissions except for
bigquery.jobUser.
For more information on IAM roles and permissions in BigQuery, see Access control.
To list the datasets in a project:
Web UI
Datasets are listed by project in the web UI's navigation pane.
Command-line
Issue the
bq ls command to list your datasets by dataset ID.
API
To list datasets using the API, call the
bigquery.datasets.list
API method.
C#
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
public List<BigQueryDataset> ListDatasets(BigQueryClient client) { var datasets = client.ListDatasets().ToList(); return datasets; }
Go
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
it := client.Datasets(ctx) for { dataset, err := it.Next() if err == iterator.Done { break } fmt.Println(dataset.DatasetID) }
Java
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
Page<Dataset> datasets = bigquery.listDatasets(DatasetListOption.pageSize(100)); for (Dataset dataset : datasets.iterateAll()) { // do something with the dataset } Page<Dataset> datasets = bigquery.listDatasets(projectId, DatasetListOption.pageSize(100)); for (Dataset dataset : datasets.iterateAll()) { // do something with the dataset }
Node.js
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
// Imports the Google Cloud client library const BigQuery = require('@google-cloud/bigquery'); // The project ID to use, e.g. "your-project-id" // const projectId = "your-project-id"; // Instantiates a client const bigquery = BigQuery({ projectId: projectId }); // Lists all datasets in the specified project bigquery.getDatasets() .then((results) => { const datasets = results[0]; console.log('Datasets:'); datasets.forEach((dataset) => console.log(dataset.id)); }) .catch((err) => { console.error('ERROR:', err); });
PHP
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
use Google\Cloud\BigQuery\BigQueryClient; /** * @param string $projectId The Google project ID. */ function list_datasets($projectId) { $bigQuery = new BigQueryClient([ 'projectId' => $projectId, ]); $datasets = $bigQuery->datasets(); foreach ($datasets as $dataset) { print($dataset->id() . PHP_EOL); } }
Python
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
def list_datasets(project=None): """Lists all datasets in a given project. If no project is specified, then the currently active project is used. """ bigquery_client = bigquery.Client(project=project) for dataset in bigquery_client.list_datasets(): print(dataset.dataset_id)
Ruby
For more on installing and creating a BigQuery client, refer to BigQuery Client Libraries.
# project_id = "Your Google Cloud project ID" require "google/cloud/bigquery" bigquery = Google::Cloud::Bigquery.new project: project_id bigquery.datasets.each do |dataset| puts dataset.dataset_id end
Using meta-tables
BigQuery offers some special tables whose contents represent metadata, such as
the names of your tables. The "meta-tables" are read-only. Normally, you use
one by referencing it in a
SELECT statement.
Meta-tables can be used in other API operations besides a query job, such as
tables.get or
tabledata.list. Meta-tables do not support
tables.insert and
cannot be used as a destination table. Meta-tables also do not support table
decorators in legacy SQL, and they do not appear when you run
tables.list on a
dataset.
The primary meta-table you can reference is:
__TABLES_SUMMARY__. Generally,
__TABLES_SUMMARY__ is reasonably fast for datasets with up to a few
thousand tables. For larger datasets
__TABLES_SUMMARY__ becomes increasingly
slow, and may exceed available resources.
Metadata about tables in a dataset
You can access metadata about the tables in a dataset by using the
__TABLES_SUMMARY__ meta-table.
Use the following syntax to query a meta-table:
SELECT [FIELD] FROM [DATASET].__TABLES_SUMMARY__;
Where
DATASET is the name of your dataset, and
FIELD is one of the following:
Example
The following query retrieves metadata about the tables in the
publicdata:samples dataset.
SELECT * FROM publicdata:samples.__TABLES_SUMMARY__;
Returns:
+------------+------------+-----------------+---------------+------+ | project_id | dataset_id | table_id | creation_time | type | +------------+------------+-----------------+---------------+------+ | publicdata | samples | github_nested | 1348782587310 | 1 | | publicdata | samples | github_timeline | 1335915950690 | 1 | | publicdata | samples | gsod | 1335916040125 | 1 | | publicdata | samples | natality | 1335916045005 | 1 | | publicdata | samples | shakespeare | 1335916045099 | 1 | | publicdata | samples | trigrams | 1335916127449 | 1 | | publicdata | samples | wikipedia | 1335916132870 | 1 | +------------+------------+-----------------+---------------+------+
Updating datasets
You can modify the following dataset properties by using the web UI, CLI, or API:
Updating datasets requires
bigquery.datasets.update permissions. The
following predefined IAM roles include
bigquery.datasets.update permissions:
For more information on IAM roles and permissions in BigQuery, see Access control.
Updating dataset descriptions
To update the dataset description:
Web UI
You cannot add a description when you create a dataset using the web UI. After the dataset is created, you can add a description on the Dataset Details page.
In the navigation pane, select your dataset.
On the Dataset Details page, in the Description section, click Describe this dataset to open the description box.
Enter a description in the box. When you click away from the box, the text is saved.
CLI
Issue the
bq update command with the
--description flag:
bq update --description "[DESCRIPTION]" [DATASET]
Where:
[DESCRIPTION]is the text that describes the dataset in quotes.
[DATASET]is the name of the dataset you're updating.
For example, the following command changes the description of
mydataset to
"Description of mydataset."
bq update --description "Description of mydataset" mydataset
API
Call datasets.update and
use the
description property to apply your dataset description.
Updating default table expiration times
To update the default expiration time for newly created tables in a dataset:
Web UI
To update the default expiration time using the web UI:
In the navigation pane, select your dataset.
On the Dataset Details page, in the Details section, to the right of Default Table Expiration, click Edit.
In the Update Expiration dialog, for Data expiration, click In and enter the expiration time in days. The default value is Never.
CLI
To update the default lifetime for newly created tables in a dataset,
enter the
bq update command with the
--default_table_expiration flag:
bq update --default_table_expiration [INTEGER] [DATASET]
Where:
[INTEGER]is the default lifetime (in seconds) for newly-created tables. The minimum value is 3600 seconds (one hour). The expiration time evaluates to the current time plus the integer value. Specify
0to remove the existing expiration time.
[DATASET]is the name of the dataset you're updating.
For example, the following command sets the default table expiration for tables
created in
mydataset to two hours from the current time:
bq update --default_table_expiration 7200 mydataset
API
Call datasets.update and
use the
defaultTableExpirationMs property to apply your expiration time in
milliseconds.
Renaming datasets
Currently, you cannot change the name of an existing dataset. If you need to change the dataset name, follow these steps:
Deleting datasets
When you delete a dataset using the web UI, tables in the dataset (and the data
they contain) are deleted. When you delete a dataset using the CLI, you must use
the
-r flag to delete the dataset's tables.
Deleting a dataset requires
bigquery.datasets.delete permissions. If the
dataset contains tables,
bigquery.tables.delete is also required. The
following predefined IAM roles include both
bigquery.datasets.delete and
bigquery.tables.delete permissions:
For more information on IAM roles and permissions in BigQuery, see access control.
To delete a dataset:
Web UI
To delete a dataset using the web UI:
Click the down arrow icon
next to your dataset name in the navigation, and then click Delete dataset.
In the Delete Dataset dialog:
- For Dataset ID, enter the name of the dataset to delete.
Click OK.
Command-line
Use the
bq rm command with the
-d flag to delete a dataset. When you use
the CLI to remove a dataset, you must confirm the command. You can use the
-f flag to skip confirmation. In addition, if the dataset contains tables,
you must use the
-r flag to remove all tables in the dataset:
bq rm -r -f -d [DATASET]
Where:
[DATASET]is the name of the dataset you're deleting.
For example, the following command removes
mydataset and all the tables in
it:
bq rm -r -d mydataset
API
Call
datasets.delete to
delete the dataset and pass the
deleteContents parameter to delete the
tables in it.
|
https://cloud.google.com/bigquery/docs/datasets
|
CC-MAIN-2017-47
|
refinedweb
| 2,499
| 57.77
|
This chapter describes the support in Pro*C/C++ for user-defined objects. This chapter contains the following topics:
In addition to the Oracle relational datatypes supported since Oracle8, Pro*C/C++ supports user-defined datatypes, which are:
An object type is a user-defined datatype that has attributes, the variables that form the datatype defined by a CREATE TYPE SQL statement, and methods, functions and procedures that are the set of allowed behaviors of the object type. We consider object types with only attributes in this guide.
For example:
--Defining an object type... CREATE TYPE employee_type AS OBJECT( name VARCHAR2(20), id NUMBER, MEMBER FUNCTION get_id(name VARCHAR2) RETURN NUMBER); / -- --Creating an object table... CREATE TABLE employees OF employee_type; --Instantiating an object, using a constructor... INSERT INTO employees VALUES ( employee_type('JONES', 10042));
LONG, LONG RAW, NCLOB, NCHAR and NCHAR Varying are not allowed as datatypes in attributes of objects.
REF (short for "reference") was also new in Oracle8. It is a reference to an object stored in a database table, instead of the object itself. REF types can occur in relational columns and also as datatypes of an object type. For example, a table employee_tab can have a column that is a REF to an object type employee_t itself:
CREATE TYPE employee_t AS OBJECT( empname CHAR(20), empno INTEGER, manager REF employee_t); / CREATE TABLE employee_tab OF employee_t;
C structures representing the NULL status of object types are generated by the Object Type Translator. You must use these generated structure types in declaring indicator variables for object types.
Other Oracle types do not require special treatment for NULL indicators.
Because object types have internal structure, NULL indicators for object types also have internal structure. A NULL indicator structure for a non-collection object type provides atomic (single) NULL status for the object type as a whole, as well as the NULL status of every attribute. OTT generates a C structure to represent the NULL indicator structure for the object type. The name of the NULL indicator structure is Object_typename_ind where Object_typename is the name of the C structure for the user-defined type in the database.
The object cache is an area of memory on the client that is allocated for your program's use in interfacing with database objects. There are two interfaces to working with objects. The associative interface manipulates "transient" copies of the objects and the navigational interface manipulates "persistent" objects.
Objects that you allocated in the cache with EXEC SQL ALLOCATE statements in Pro*C/C++ are transient copies of persistent objects in the Oracle database. As such, you can update these copies in the cache after they are fetched in, but in order to make these changes persistent in the database, you must use explicit SQL commands. This "transient copy" or "value-based" object caching model is an extension of the relational model, in which scalar columns of relational tables can be fetched into host variables, updated in place, and the updates communicated to the server.
The associative interface manipulates transient copies of objects. Memory is allocated in the object cache with the EXEC SQL ALLOCATE statement.
One object cache is created for each SQLLIB runtime context.
Objects are retrieved by the EXEC SQL SELECT or EXEC SQL FETCH statements. These statements set values for the attributes of the host variable. If a NULL indicator is provided, it is also set.
Objects are inserted, updated, or deleted using EXEC SQL INSERT, EXEC SQL UPDATE, and EXEC SQL DELETE statements. The attributes of the object host variable must be set before the statement is executed.
Transactional statements EXEC SQL COMMIT and EXEC SQL ROLLBACK are used to write the changes permanently on the server or to abort the changes.
You explicitly free memory in the cache for the objects by use of the EXEC SQL FREE statement. When a connection is terminated, Oracle implicitly frees its allocated memory.
Use in these cases:
You allocate space in the object cache with this statement. The syntax is:
EXEC SQL [AT [:]database] ALLOCATE :host_ptr [[INDICATOR]:ind_ptr] ;
Variables entered are:
database (IN)
a zero-terminated string containing the name of the database connection, as established previously through the statement:
EXEC SQL CONNECT :user [AT [:]database];
If the AT clause AT is omitted, or if database is an empty string, the default database connection is assumed.
host_ptr (IN)
a pointer to a host structure generated by OTT for object types, collection object types, or REFs, or a pointer to one of the new C datatypes: OCIDate, OCINumber, OCIRaw, or OCIString.
ind_ptr (IN)
The indicator variable, ind_ptr, is optional, as is the keyword INDICATOR. Only pointers to struct-typed indicators can be used in the ALLOCATE and FREE statements.
host_ptr and ind_ptr can be host arrays.
The duration of allocation is the session. Any instances will be freed when the session (connection) is terminated, even if not explicitly freed by a FREE statement.
For more details, see "ALLOCATE (Executable Embedded SQL Extension)" above statement to free all object cache memory for the specified database connection.
When accessing objects using SQL, Pro*C/C++ applications manipulate transient copies of the persistent objects. This is a direct extension of the relational access interface, which uses SELECT, UPDATE and DELETE statements.
In Figure 17-1, you allocate memory in the cache for a transient copy of the persistent object. with the ALLOCATE statement. The allocated object does not contain data, but it has the form of the struct generated by the OTT.
person *per_p; ... EXEC SQL ALLOCATE :per_p;
You can execute a SELECT statement to populate the cache. Or, use a FETCH statement or a C assignment to populate the cache with data.
EXEC SQL SELECT ... INTO :per_p FROM person_tab WHERE ...
Make changes to the server objects with INSERT, UPDATE or DELETE statements, as shown in the illustration. You can insert the data is into the table by the INSERT statement:
EXEC SQL INSERT INTO person_tab VALUES(:per_p);
Finally, free memory associated with the copy of the object with the FREE statement:
EXEC SQL FREE :per_p;
Use the navigational interface to access the same schema as the associative interface. The navigational interface accesses objects, both persistent and transient) by dereferencing REFs to objects and traversing ("navigating") from one object to another. Some definitions follow.
Pinning an object is the term used to mean dereferencing the object, allowing the program to access it.
Unpinning means indicating to the cache that the object is no longer needed.
Dereferencing can be defined as the server using the REF to create a version of the object in the client. While the cache maintains the association between objects in the cache and the corresponding server objects, it does not provide automatic coherency. You have the responsibility to ensure correctness and consistency of the contents of the objects in the cache.
Releasing an object copy indicates to the cache that the object is not currently being used. To free memory, release objects when they are no longer needed to make them eligible for implicit freeing.
Freeing an object copy removes it from the cache and releases its memory area.
Marking an object tells the cache that the object copy has been updated in the cache and the corresponding server object must be updated when the object copy is flushed.
Un-marking an object removes the indication that the object has been updated.
Flushing an object writes local changes made to marked copies in the cache to the corresponding objects in the server. The object copies in the cache are also unmarked at this time.
Refreshing an object copy in the cache replaces it with the latest value of the corresponding object in the server.
The navigational and associative interfaces can be used together.
Use the EXEC SQL OBJECT statements, the navigational interface, to update, delete, and flush cache copies (write changes in the cache to the server).
Use the navigational interface:
Embedded SQL OBJECT statements are described below with these assumptions:
EXEC SQL [AT [:]database] [FOR [:]count] OBJECT CREATE :obj [INDICATOR]:obj_ind [TABLE tab] [RETURNING REF INTO :ref] ;
where tab is:
{:hv | [schema.]table}
Use this statement to create a referenceable object in the object cache. The type of the object corresponds to the host variable obj. When optional type host variables (
:obj_ind,:ref,:ref_ind) are supplied, they must all correspond to the same type.
The referenceable object can be either persistent (TABLE clause is supplied) or transient (TABLE clause is absent). Persistent objects are implicitly pinned and marked as updated. Transient objects are implicitly pinned.
The host variables are:
obj (OUT)
The object instance host variable, obj, must be a pointer to a structure generated by OTT. This variable is used to determine the referenceable object that is created in the object cache. After a successful execution, obj will point to the newly created object.
obj_ind (OUT)
This variable points to an OTT-generated indicator structure. Its type must match that of the object instance host variable. After a successful execution, obj_ind will be a pointer to the parallel indicator structure for the referenceable object.
tab (IN)
Use the table clause to create persistent objects. The table name can be specified as a host variable, hv, or as an undeclared SQL identifier. It can be qualified with a schema name. Do not use trailing spaces in host variables containing the table name.
hv (IN)
A host variable specifying a table. If a host variable is used, it must not be an array. It must not be blank-padded. It is case-sensitive. When an array of persistent objects is created, they are all associated with the same table.
table (IN)
An undeclared SQL identifier which is case-sensitive.
ref (OUT)
The reference host variable must be a pointer to the OTT-generated reference type. The type of ref must match that of the object instance host variable. After execution, ref contains a pointer to the ref for the newly created object.
Attributes are initially set to null. Creating new objects for object views is not currently supported.
Creating new objects for object views is not currently supported.
EXEC SQL [AT [:]database] [FOR [:]count] OBJECT DEREF :ref INTO :obj [[INDICATOR]:obj_ind] [FOR UPDATE [NOWAIT]] ;
Given an object reference, ref, the OBJECT DEREF statement pins the corresponding object or array of objects in the object cache. Pointers to these objects are returned in the variables obj and obj_ind.
The host variables are:
ref (IN)
This is the object reference variable, which must be a pointer to the OTT-generated reference type. This variable (or array of variables) is dereferenced, returning a pointer to the corresponding object in the cache.
obj (OUT)
The object instance host variable, obj, must be a pointer to an OTT-generated structure. Its type must match that of the object reference host variable. After successful execution, obj contains a pointer to the pinned object in the object cache.
obj_ind (OUT)
The object instance indicator variable, obj_ind, must be a pointer to an OTT-generated indicator structure. Its type must match that of the object reference indicator variable. After successful execution, obj_ind contains a pointer to the parallel indicator structure for the referenceable object.
FOR UPDATE
If this clause is present, an exclusive lock is obtained for the corresponding object in the server.
NOWAIT
If this optional keyword is present, an error is immediately returned if another user has already locked the object.
EXEC SQL [AT [:]database] [FOR [:]count] OBJECT RELEASE :obj ;
This statement unpins the object in the object cache. When an object is not pinned and not updated, it is eligible for implicit freeing.
If an object has been dereferenced n times, it must be released n times to be eligible for implicit freeing from the object cache. Oracle advises releasing all objects that are no longer needed.
EXEC SQL [AT [:]database] [FOR [:]count] OBJECT DELETE :obj ;
For persistent objects, this statement marks an object or array of objects as deleted in the object cache. The object is deleted in the server when the object is flushed or when the cache is flushed. The memory reserved in the object cache is not freed.
For transient objects, the object is marked as deleted. The memory for the object is not freed.
EXEC SQL [AT [:]database] [FOR [:]count] OBJECT UPDATE :obj ;
For persistent objects, this statement marks them as updated in the object cache. The changes are written to the server when the object is flushed or when the cache is flushed.
For transient objects, this statement is a no-op.
EXEC SQL [AT [:]database] [FOR [:]count] OBJECT FLUSH :obj ;
This statement flushes persistent objects that have been marked as updated, deleted, or created, to the server.
See Figure 17-2 for an illustration of the navigational interface.
Use the ALLOCATE statement to allocate memory in the object cache for a copy of the REF to the person object. The allocated REF does not contain data.
person *per_p; person_ref *per_ref_p; ... EXEC SQL ALLOCATE :per_p;
Populate the allocated memory by using a SELECT statement to retrieve the REF of the person object (exact format depends on the application):
EXEC SQL SELECT ... INTO :per_ref_p;
The DEREF statement is then used to pin the object in the cache, so that changes can be made in the object. The DEREF statement takes the pointer per_ref_p and creates an instance of the person object in the client-side cache. The pointer per_p to the person object is returned.
EXEC SQL OBJECT DEREF :per_ref_p INTO :per_p;
Make changes to the object in the cache by using C assignment statements, or by using data conversions with the OBJECT SET statement.
Then you must mark the object as updated. See Figure 17-3. To mark the object in the cache as updated, and eligible to be flushed to the server:
EXEC SQL OBJECT UPDATE :per_p;
You send changes to the server by the FLUSH statement:
EXEC SQL OBJECT FLUSH :per_p;
You release the object:
EXEC SQL OBJECT RELEASE :per_p;
The statements in the next section are used to make the conversions between object attributes and C types.
EXEC SQL [AT [:]database] OBJECT SET [ {'*' | {attr[, attr]} } OF] :obj [[INDICATOR]:obj_ind] TO {:hv [[INDICATOR]:hv_ind] [, :hv [INDICATOR]:hv_ind]]} ;
Use this statement with objects created by both the associative and the navigational interfaces. This statement updates the attributes of the object. For persistent objects, the changes will be written to the server when the object is updated and flushed. Flushing the cache writes all changes made to updated objects to the server.
The OF clause is optional. If absent, all the attributes of obj are set. The same result is achieved by writing:
... OBJECT SET * OF ...
The host variable list can include structures that are exploded to provide values for the attributes. However, the number of attributes in obj must match the number of elements in the exploded variable list.
Host variables and attributes are:
attr
The attributes are not host variables, but rather simple identifiers that specify which attributes of the object will be updated. The first attribute in the list is paired with the first expression in the list, and so on. The attribute must be one of either OCIString, OCINumber, OCIDate, or OCIRef.
obj (IN/OUT)
obj specifies the object to be updated. The bind variable obj must not be an array. It must be a pointer to an OTT-generated structure.
obj_ind (IN/OUT)
The parallel indicator structure that will be updated. It must be a pointer to an OTT-generated indicator structure.
hv (IN)
This is the bind variable used as input to the OBJECT SET statement. hv must be an int, float, OCIRef *, a one-dimensional char array, or a structure of these types.
hv_ind (IN)
This is the associated indicator that is used as input to the OBJECT SET statement. hv_ind must be a 2-byte integer scalar or a structure of 2-byte integer scalars.
Using Indicator Variables:
If a host variable indicator is present, then an object indicator must also be present.
If hv_ind is set to -1, the associated field in the obj_ind is set to -1.
The following implicit conversions are permitted:
EXEC SQL [AT [:]database] OBJECT GET [ { '*' | {attr[, attr]} } FROM] :obj [[INDICATOR]:obj_ind] INTO {:hv [[INDICATOR]:hv_ind] [, :hv [[INDICATOR]:hv_ind]]} ;
This statement converts the attributes of an object into native C types.
The FROM clause is optional. If absent, all the attributes of obj are converted. The same result is achieved by writing:
... OBJECT GET * FROM ...
The host variable list may include structures that are exploded to receive the values of the attributes. However, the number of attributes in obj must match the number of elements in the exploded host variable list.
Host variables and attributes:
attr
The attributes are not host variables, but simple identifiers that specify which attributes of the object will be retrieved. The first attribute in the list is paired with the first host variable in the list, and so on. The attribute must represent a base type. It must be OCIString, OCINumber, OCIRef, or OCIDate.
obj (IN)
This specifies the object that serves as the source for the attribute retrieval. The bind variable obj must not be an array.
hv (OUT)
This is the bind variable used to hold output from the OBJECT GET statement. It can be an int, float, double, a one-dimensional char array, or a structure containing those types. The statement returns the converted attribute value in this host variable.
hv_ind (OUT)
This is the associated indicator variable for the attribute value. It is a 2-byte integer scalar or a structure of 2-byte integer scalars.
Using Indicator Variables:
If no object indicator is specified, it is assumed that the attribute is valid. It is a program error to convert object attributes to C types if the object is atomically NULL or if the requested attribute is NULL and no object indicator variable is supplied. It may not be possible to raise an Oracle error in this situation.
If the object variable is atomically NULL or the requested attribute is NULL, and a host variable indicator (hv_ind) is supplied, then it is set to -1.
If the object is atomically NULL or the requested attribute is NULL, and no host variable indicator is supplied, then an error is raised.
The following implicit conversions are permitted::
An example is:
char *new_format = "DD-MM-YYYY"; char *new_lang = "French"; char *new_date = "14-07-1789"; /* One of the attributes of the license type is dateofbirth */ license *aLicense; ... /* Declaration and allocation of context ... */ EXEC SQL CONTEXT OBJECT OPTION SET DATEFORMAT, DATELANG TO :new_format, :new_ lang; /* Navigational object obtained */ ... EXEC SQL OBJECT SET dateofbirth OF :aLicense TO :new_date; ... these precompiler options:
This option determines which version of the object is returned by the EXEC SQL OBJECT DEREF statement. This gives you varying levels of consistency between cache objects and server objects.
Use the EXEC ORACLE OPTION statement to set it inline. Permitted values are:
If the object has been selected into the object cache in the current transaction, then return that object. If the object has not been selected, it is retrieved from the server. For transactions that are running in serializable mode, this option has the same behavior as VERSION=LATEST without incurring as many network round trips. This value can be safely used with most Pro*C/C++ applications.
If the object does not reside in the object cache, it is retrieved from the database. If it does reside in the object cache, it is refreshed from the server. Use this value with caution because it will incur the greatest number of network round trips. Use it only when it is imperative that the object cache be kept as coherent as possible with the server-side buffer.
If the object already resides in the object cache, then return that object. If the object does not reside in the object cache, retrieve it from the server. This value will incur the fewest number of network round trips. Use in applications that access read-only objects or when a user will have exclusive access to the objects.
Use this precompiler option to set the pin duration used by subsequent EXEC SQL OBJECT CREATE and EXEC SQL OBJECT DEREF statements. Objects in the cache are implicitly unpinned at the end of the duration.
Use with navigational interface only.
You can set this option in the EXEC ORACLE OPTION statement. Permitted values are:
Objects are implicitly unpinned when the transaction completes.
Objects are implicitly unpinned when the connection is terminated.
This precompiler option., is the name of the typefiles generated by OTT. These files are meant to be a read-only input to Pro*C/C++. The information in it, though in plain-text form, might be encoded, and might not necessarily be interpretable by you, the user.
You can provide more than one INTYPE file as input to a single Pro*C/C++ precompilation unit.
This option cannot be used inline in EXEC ORACLE statements.
OTT generates C structure declarations for object types created in the database, and writes type names and version information to a file called the typefile.
An object type may not necessarily have the same name as the C structure type or C++ class type that represents it. This could arise for the following reasons:
Under these circumstances, it is impossible to infer from the structure or class declaration which object type it matches. This information, which is required by Pro*C/C++, is generated by OTT in the type file.
ERRTYPE=filename
Writes errors to the file specified, as well as to the screen. If omitted, errors are directed to the screen only. Only one ERRTYPE is allowed. As is usual with other single-valued command-line options, if you enter multiple values for ERRTYPE on the command line, the last one supersedes the earlier values.
This option cannot be used inline in EXEC ORACLE statements.
Object types and their attributes are represented in a C program according to the C binding of Oracle types. If the precompiler command-line option SQLCHECK is set to SEMANTICS or FULL, Pro*C/C++ verifies during precompilation that host variable types conform to the mandated C bindings for the types in the database schema. In addition, runtime checks are always performed to verify that Oracle types are mapped correctly during program execution. See also "SQLCHECK".
Relational datatypes are checked in the usual manner.
A relational SQL datatype is compatible with a host variable type if the two types are the same, or if a conversion is permitted between the two. Object types, on the other hand, are compatible only if they are the same type. They must
When you specify the option SQLCHECK=SEMANTICS or FULL, during precompilation Pro*C/C++ logs onto the database using the specified userid and password, and verifies that the object type from which a structure declaration was generated is identical to the object type used in the embedded SQL statement.
Pro*C/C++ gathers the type name, version, and possibly schema information for Object, collection Object, and REF host variables, for a type from the input INTYPE file, and stores this information in the code that it generates. This enables access to the type information for Object and REF bind variables at runtime. Appropriate errors are returned for type mismatches.
Let us examine a simple object example. You create a type person and a table person_tab, which has a column that is also an object type, address:
create type person as object ( lastname varchar2(20), firstname char(20), age int, addr address ) / create table person_tab of person;
Insert data in the table, and proceed.
Consider the case of how to change a lastname value from "Smith" to "Smythe", using Pro*C/C++.
Run the OTT to generate C structures which map to person. In your Pro*C/C++ program you must include the header file generated by OTT.
In your application, declare a pointer, person_p, to the persistent memory in the client-side cache. Then allocate memory and use the returned pointer:
char *new_name = "Smythe"; person *person_p; ... EXEC SQL ALLOCATE :person_p;
Memory is now allocated for a copy of the persistent object. The allocated object does not yet contain data.
Populate data in the cache either by C assignment statements or by using SELECT or FETCH to retrieve an existing object:
EXEC SQL SELECT VALUE(p) INTO :person_p FROM person_tab p WHERE lastname = 'Smith';
Changes made to the copy in the cache are transmitted to the server database by use of INSERT, UPDATE, and DELETE statements:
EXEC SQL OBJECT SET lastname OF :person_p TO :new_name; EXEC SQL INSERT INTO person_tab VALUES(:person_p);
Free cache memory in this way:
EXEC SQL FREE :person_p;
Allocate memory in the object cache for a copy of the REF to the object person. The ALLOCATE statement returns a pointer to the REF:
person *person_p; person_ref *per_ref_p; ... EXEC SQL ALLOCATE :per_ref_p;
The allocated REF contains no data. To populate it with data, retrieve the REF of the object:
EXEC SQL SELECT ... INTO :per_ref_p;
Then dereference the REF to put an instance of object in the client-side cache. The dereference command takes the per_ref_p and creates an instance of the corresponding object in the cache:
EXEC SQL OBJECT DEREF :per_ref_p INTO :person_p;
Make changes to data in the cache by using C assignments, or by using OBJECT GET statements:
/* lname is a C variable to hold the result */ EXEC SQL OBJECT GET lastname FROM :person_p INTO :lname; ... EXEC SQL OBJECT SET lastname OF :person_p TO :new_name; /* Mark the changed object as changed with OBJECT UPDATE command */; EXEC SQL OBJECT UPDATE :person_p; EXEC SQL FREE :per_ref_p;
To make the changes permanent in the database, use FLUSH:
EXEC SQL OBJECT FLUSH :person_p;
Changes have been made to the server; the object can now be released. Objects that are released are not necessarily freed from the object cache memory immediately. They are placed on a least-recently used stack. When the cache is full, the objects are swapped out of memory.
Only the object is released; the REF to the object remains in the cache. To release the REF, use the RELEASE statement. for the REF. To release the object pointed to by
person_p:
EXEC SQL OBJECT RELEASE :person_p;
Or, issue a transaction commit and all objects in the cache are released, provided the pin duration has been set appropriately.
The following code example creates four object types:
and one table::
and two tables:
person_tab
customer_tab
The SQL file,
navdemo1.sql, which creates the types and tables, and then inserts values into the tables, is:
connect scott/tiger drop table customer_tab; drop type customer; drop table person_tab; drop type budoka; drop type location; create type location as object ( num number, street varchar2(60), city varchar2(30), state char(2), zip char(10) ); / create type budoka as object ( lastname varchar2(20), firstname varchar(20), birthdate date, age int, addr location ); / create table person_tab of budoka; create type customer as object ( account_number varchar(20), aperson ref budoka ); / create table customer_tab of customer; insert into person_tab values ( budoka('Seagal', 'Steven', '14-FEB-1963', 34, location(1825, 'Aikido Way', 'Los Angeles', 'CA', 45300))); insert into person_tab values ( budoka('Norris', 'Chuck', '25-DEC-1952', 45, location(291, 'Grant Avenue', 'Hollywood', 'CA', 21003))); insert into person_tab values ( budoka('Wallace', 'Bill', '29-FEB-1944', 53, location(874, 'Richmond Street', 'New York', 'NY', 45100))); insert into person_tab values ( budoka('Van Damme', 'Jean Claude', '12-DEC-1964', 32, location(12, 'Shugyo Blvd', 'Los Angeles', 'CA', 95100))); insert into customer_tab select 'AB123', ref(p) from person_tab p where p.lastname = 'Seagal'; insert into customer_tab select 'DD492', ref(p) from person_tab p where p.lastname = 'Norris'; insert into customer_tab select 'SM493', ref(p) from person_tab p where p.lastname = 'Wallace'; insert into customer_tab select 'AC493', ref(p) from person_tab p where p.lastname = 'Van Damme'; commit work;:
/************************************************************************* * * This is a simple Pro*C/C++ program designed to illustrate the * Navigational access to objects in the object cache. * * To build the executable: * * 1. Execute the SQL script, navdemo1.sql in SQL*Plus * 2. Run OTT: (The following command should appear on one line) * ott intype=navdemo1.typ hfile=navdemo1.h outtype=navdemo1_o.typ * code=c user=scott/tiger * 3. Precompile using Pro*C/C++: * proc navdemo1 intype=navdemo1_o.typ * 4. Compile/Link (This step is platform specific) * *************************************************************************/ #include "navdemo1.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sqlca.h> void whoops(errcode, errtext, errtextlen) int errcode; char *errtext; int errtextlen; { printf("ERROR! sqlcode=%d: text = %.*s", errcode, errtextlen, errtext); EXEC SQL WHENEVER SQLERROR CONTINUE; EXEC SQL ROLLBACK WORK RELEASE; exit(EXIT_FAILURE); } void main() { char *uid = "scott/tiger"; /* The following types are generated by OTT and defined in navdemo1.h */ customer *cust_p; /* Pointer to customer object */ customer_ind *cust_ind; /* Pointer to indicator struct for customer */ customer_ref *cust_ref; /* Pointer to customer object reference */ budoka *budo_p; /* Pointer to budoka object */ budoka_ref *budo_ref; /* Pointer to budoka object reference */ budoka_ind *budo_ind; /* Pointer to indicator struct for budoka */ /* These are data declarations to be used to insert/retrieve object data */ VARCHAR acct[21]; struct { char lname[21], fname[21]; int age; } pers; struct { int num; char street[61], city[31], state[3], zip[11]; } addr; EXEC SQL WHENEVER SQLERROR DO whoops( sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc, sqlca.sqlerrm.sqlerrml); EXEC SQL CONNECT :uid; EXEC SQL ALLOCATE :budo_ref; /* Create a new budoka object with an associated indicator * variable returning a REF to that budoka as well. */ EXEC SQL OBJECT CREATE :budo_p:budo_ind TABLE PERSON_TAB RETURNING REF INTO :budo_ref; /* Create a new customer object with an associated indicator */ EXEC SQL OBJECT CREATE :cust_p:cust_ind TABLE CUSTOMER_TAB; /* Set all budoka indicators to NOT NULL. We * will be setting all attributes of the budoka. */ budo_ind->_atomic = budo_ind->lastname = budo_ind->firstname = budo_ind->age = OCI_IND_NOTNULL; /* We will also set all address attributes of the budoka */ budo_ind->addr._atomic = budo_ind->addr.num = budo_ind->addr.street = budo_ind->addr.city = budo_ind->addr.state = budo_ind->addr.zip = OCI_IND_NOTNULL; /* All customer attributes will likewise be set */ cust_ind->_atomic = cust_ind->account_number = cust_ind->aperson = OCI_IND_NOTNULL; /* Set the default CHAR semantics to type 5 (STRING) */; addr.num = 1893; strcpy((char *)addr.street, (char *)"Rumble Street"); strcpy((char *)addr.city, (char *)"Bronx"); strcpy((char *)addr.state, (char *)"NY"); strcpy((char *)addr.zip, (char *)"92510"); /* Convert native C types to OTS types */ EXEC SQL OBJECT SET :budo_p->addr TO :addr; acct.len = strlen(strcpy((char *)acct.arr, (char *)"FS926")); /* Convert native C types to OTS types - Note also the REF type */ EXEC SQL OBJECT SET account_number, aperson OF :cust_p TO :acct, :budo_ref; /* Mark as updated both the new customer and the budoka */ EXEC SQL OBJECT UPDATE :cust_p; EXEC SQL OBJECT UPDATE :budo_p; /* Now flush the changes to the server, effectively * inserting the data into the respective tables. */ EXEC SQL OBJECT FLUSH :budo_p; EXEC SQL OBJECT FLUSH :cust_p; /* Associative access to the REFs from CUSTOMER_TAB */ EXEC SQL DECLARE ref_cur CURSOR FOR SELECT REF(c) FROM customer_tab c; EXEC SQL OPEN ref_cur; printf("\n"); /* Allocate a REF to a customer for use below */ EXEC SQL ALLOCATE :cust_ref; EXEC SQL WHENEVER NOT FOUND DO break; while (1) { EXEC SQL FETCH ref_cur INTO :cust_ref; /* Pin the customer REF, returning a pointer to a customer object */ EXEC SQL OBJECT DEREF :cust_ref INTO :cust_p:cust_ind; /* Convert the OTS types to native C types */ EXEC SQL OBJECT GET account_number FROM :cust_p INTO :acct; printf("Customer Account is %.*s\n", acct.len, (char *)acct.arr); /* Pin the budoka REF, returning a pointer to a budoka object */ EXEC SQL OBJECT DEREF :cust_p->aperson INTO :budo_p:budo_ind; /* Convert the OTS types to native C types */ EXEC SQL OBJECT GET lastname, firstname, age FROM :budo_p INTO :pers; printf("Last Name: %s\nFirst Name: %s\nAge: %d\n", pers.lname, pers.fname, pers.age); /* Do the same for the address attributes as well */ EXEC SQL OBJECT GET :budo_p->addr INTO :addr; printf("Address:\n"); printf(" Street: %d %s\n City: %s\n State: %s\n Zip: %s\n\n", addr.num, addr.street, addr.city, addr.state, addr.zip); /* Unpin the customer object and budoka objects */ EXEC SQL OBJECT RELEASE :cust_p; EXEC SQL OBJECT RELEASE :budo_p; } EXEC SQL CLOSE ref_cur; EXEC SQL WHENEVER NOT FOUND DO whoops( sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc, sqlca.sqlerrm.sqlerrml); /* Associatively select the newly created customer object */ EXEC SQL SELECT VALUE(c) INTO :cust_p FROM customer_tab c WHERE c.account_number = 'FS926'; /* Mark as deleted the new customer object */ EXEC SQL OBJECT DELETE :cust_p; /* Flush the changes, effectively deleting the customer object */ EXEC SQL OBJECT FLUSH :cust_p; /* Associatively select a REF to the newly created budoka object */ EXEC SQL SELECT REF(p) INTO :budo_ref FROM person_tab p WHERE p.lastname = 'Chan'; /* Pin the budoka REF, returning a pointer to the budoka object */ EXEC SQL OBJECT DEREF :budo_ref INTO :budo_p; /* Mark the new budoka object as deleted in the object cache */ EXEC SQL OBJECT DELETE :budo_p; /* Flush the changes, effectively deleting the budoka object */ EXEC SQL OBJECT FLUSH :budo_p; /* Finally, free all object cache memory and log off */ EXEC SQL OBJECT CACHE FREE ALL; EXEC SQL COMMIT WORK RELEASE; exit(EXIT_SUCCESS); }
When the program is executed, the result is:
Customer Account is AB123 Last Name: Seagal First Name: Steven Birthdate: 02-14-1963 Age: 34 Address: Street: 1825 Aikido Way City: Los Angeles State: CA Zip: 45300 Customer Account is DD492 Last Name: Norris First Name: Chuck Birthdate: 12-25-1952 Age: 45 Address: Street: 291 Grant Avenue City: Hollywood State: CA Zip: 21003 Customer Account is SM493 Last Name: Wallace First Name: Bill Birthdate: 02-29-1944 Age: 53 Address: Street: 874 Richmond Street City: New York State: NY Zip: 45100 Customer Account is AC493 Last Name: Van Damme First Name: Jean Claude Birthdate: 12-12-1965 Age: 32 Address: Street: 12 Shugyo Blvd City: Los Angeles State: CA Zip: 95100 Customer Account is FS926 Last Name: Chan First Name: Jackie Birthdate: 10-10-1959 Age: 38 Address: Street: 1893 Rumble Street City: Bronx State: NY Zip: 92510
Before Oracle8, Pro*C/C++ allowed you to specify a C structure as a single host variable in a SQL SELECT statement. In such cases, each member of the structure is taken to correspond to a single database column in a relational table; that is, each member represents a single item in the select list returned by the query.
In Oracle8i and later versions, an object type in the database is a single entity and can be selected as a single item. This introduces an ambiguity with the Oracle7 notation: is the structure for a group of scalar variables, or for an object?
Pro*C/C++ uses the following rule to resolve the ambiguity:
A host variable that is a C structure is considered to represent an object type only if its C declaration was generated using OTT, and therefore its type description appears in a typefile specified in an INTYPE option to Pro*C/C++. All other host structures are assumed to be uses of the Oracle7 syntax, even if a datatype of the same name resides in the database.
Thus, if you use new object types that have the same names as existing structure host variable types, be aware that Pro*C/C++ uses the object type definitions in the INTYPE file. This can lead to compilation errors. To correct this, you might rename the existing host variable types, or use OTT to choose a new name for the object type.
The above rule extends transitively to user-defined datatypes that are aliased to OTT-generated datatypes. To illustrate, let emptype be a structure generated by OTT in a header file
dbtypes.h and you have the following statements in your Pro*C/C++ program:
#include <dbtypes.h> typedef emptype myemp; myemp *employee;
The typename myemp for the variable employee is aliased to the OTT-generated typename emptype for some object type defined in the database. Therefore, Pro*C/C++ considers the variable employee to represent an object type.
The above rules do not imply that a C structure having or aliased to an OTT-generated type cannot be used for fetches of non-object type data. The only implication is that Pro*C/C++ will not automatically expand such a structure -- the user is free to employ the "longhand syntax" and use individual fields of the structure for selecting or updating single database columns.
The REF type denotes a reference to an object, instead of the object itself. REF types may occur in relational columns and also in attributes of an object type.
The C representation for a REF to an object type is generated by OTT during type translation. For example, a reference to a user-defined PERSON type in the database may be represented in C as the type "Person_ref". The exact type name is determined by the OTT options in effect during type translation. The OTT-generated typefile must be specified in the INTYPE option to Pro*C/C++ and the OTT-generated header #included in the Pro*C/C++ program. This scheme ensures that the proper type-checking for the REF can be performed by Pro*C/C++ during precompilation.
A REF type does not require a special indicator structure to be generated by OTT; a scalar signed 2-byte indicator is used instead.
A host variable representing a REF in Pro*C/C++ must be declared as a pointer to the appropriate OTT-generated type.
Unlike object types, the indicator variable for a REF is declared as the signed 2-byte scalar type
OCIInd. As always, the indicator variable is optional, but it is a good programming practice to use one for each host variable declared.
REFs reside in the object cache. However, indicators for REFs are scalars and cannot be allocated in the cache. They generally reside in the user stack.
Prior to using the host structure for a REF in embedded SQL, allocate space for it in the object cache by using the EXEC SQL ALLOCATE command. After use, free using the EXEC SQL FREE or EXEC SQL CACHE FREE ALL commands.
Memory for scalar indicator variables is not allocated in the object cache, and hence indicators are not permitted to appear in the ALLOCATE and FREE commands for REF types. Scalar indicators declared as
OCIInd reside on the program stack. At runtime, the ALLOCATE statement causes space to be allocated in the object cache for the specified host variable. For the navigational interface, use EXEC SQL GET and EXEC SQL SET, not C assignments.
Pro*C/C++ supports REF host variables in associative SQL statements and in embedded PL/SQL blocks.
These OCI types are new C representations for a date, a varying-length zero-terminated string, an Oracle number, and varying-length binary data respectively. In certain cases, these types provide more functionality than earlier C representations of these quantities. For example, the OCIDate type provides client-side routines to perform DATE arithmetic, which in earlier releases required SQL statements at the server.
The OCI* types appear as object type attributes in OTT-generated structures, and you use them as part of object types in Pro*C/C++ programs. Other than their use in object types, Oracle recommends that the beginner-level C and Pro*C/C++ user avoid declaring individual host variables of these types. An experienced Pro*C/C++ user may wish to declare C host variables of these types to take advantage of the advanced functionality these types provide. The host variables must be declared as pointers to these types, for example,
OCIString *s. The associated (optional) indicators are scalar signed 2-byte quantities, declared, for example,
OCIInd s_ind.
Space for host variables of these types may be allocated in the object cache using EXEC SQL ALLOCATE. Scalar indicator variables are not permitted to appear in the ALLOCATE and FREE commands for these types. You allocate such indicators statically on the stack, or dynamically on the heap. De-allocation of space can be done using the statement EXEC SQL FREE, EXEC SQL CACHE FREE ALL, or automatically at the end of the session.
Except for
OCIDate, which is a structure type with individual fields for various date components: year, month, day, hour and so on., the other OCI types are encapsulated, and are meant to be opaque to an external user. In contrast to the way existing C types like VARCHAR are currently handled in Pro*C/C++, you include the OCI header file
oci.h and employ its functions to perform DATE arithmetic, and to convert these types to and from native C types such as int, char, above, including the new object types, REF, Nested Table, Varying Array, NCHAR, NCHAR Varying and LOB types.
The older Dynamic SQL method 4 is generally restricted to the Oracle types supported by Pro*C/C++ prior to release 8.0. It does allow host variables of the NCHAR, NCHAR Varying and LOB datatypes. Dynamic method 4 is not available for object types, Nested Table, Varying Array, and REF types.
Instead, use ANSI Dynamic SQL Method 4 for all new applications, because it supports all datatypes introduced in Oracle8i.
|
http://docs.oracle.com/cd/A91202_01/901_doc/appdev.901/a89861/pc_17obj.htm
|
CC-MAIN-2016-40
|
refinedweb
| 6,854
| 52.7
|
Fix for CVE-2015-3222 which allows for root escalation via syscheck - Affected versions: 2.7 - 2.8.1 Beginning is OSSEC 2.7 (d88cf1c9) a feature was added to syscheck, which is the daemon that monitors file changes on a system, called "report_changes". This feature is only available on *NIX systems. It's purpose is to help determine what about a file has changed. The logic to do accomplish this is as follows which can be found in src/syscheck/seechanges.c: 252 /* Run diff */ 253 date_of_change = File_DateofChange(old_location); 254 snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\"> \"%s/local/%s/diff.%d\" " 255 "2>/dev/null", 256 tmp_location, old_location, 257 DIFF_DIR_PATH, filename + 1, (int)date_of_change); 258 if (system(diff_cmd) != 256) { 259 merror("%s: ERROR: Unable to run diff for %s", 260 ARGV0, filename); 261 return (NULL); 262 } Above, on line 258, the system() call is used to shell out to the system's "diff" command. The raw filename is passed in as an argument which presents an attacker with the possibility to run arbitrary code. Since the syscheck daemon runs as the root user so it can inspect any file on the system for changes, any code run using this vulnerability will also be run as the root user. An example attack might be creating a file called "foo-$(touch bar)" which should create another file "bar". Again, this vulnerability exists only on *NIX systems and is contingent on the following criteria: 1. A vulnerable version is in use. 2. The OSSEC agent is configured to use syscheck to monitor the file system for changes. 3. The list of directories monitored by syscheck includes those writable by underprivileged users. 4. The "report_changes" option is enabled for any of those directories. The fix for this is to create temporary trusted file names that symlink back to the original files before calling system() and running the system's "diff" command.
Related ExploitsTrying to match CVEs (1): CVE-2015-3222
Trying to match OSVDBs (1): 123222
Trying to match setup file: c2ffd25180f760e366ab16eeb82ae382
Other Possible E-DB Search Terms: OSSEC 2.7 <= 2.8.1, OSSEC 2.7, OSSEC
|
https://www.exploit-db.com/exploits/37265/
|
CC-MAIN-2016-44
|
refinedweb
| 355
| 63.49
|
User Details
- User Since
- Nov 12 2012, 12:47 PM (447 w, 5 d)
Dec 14 2020
*ping*
Dec 6 2020
Per Richard's suggestion, instead of including the cached tokens into the decltype annotation, i revert the cache to match the end of where we think the (broken) decltype annotated token should end.
Nov 25 2020
Nov 23 2020
*ping*
Nov 21 2020
committed here:
Nov 20 2020
*ping*
Nov 19 2020
Nov 17 2020
Based on Richards Feedback, this update includes the following changes:
- avoids calling the fragile getZextValue() for comparing against bit-field width, and uses APSInt's comparison operator overload
- suppresses/avoids the warning for unnamed bit-fields
- simplifies the test case and avoids preprocessor cleverness (and thus an extra pass).
Nov 15 2020
Committed here: .
Nov 14 2020
Thanks Thorsten - if no one else does it - i'll try and commit this for you
later today :)
This diff makes the following changes to the previous patch (based on feedback from Richard, Aaron and Wyatt):
- avoid introducing an initialism (FDK) into the clang namespace and unabbreviated each corresponding use to 'FunctionDefinitionKind'. Let me know if it seems too verbose - if so, perhaps a compromise along Wyatt's suggestion might behoove our source.
- changed the destination type from 'unsigned' to 'unsigned char' in our static_casts.
- is that preferred, or should i have left it as 'unsigned'?
- is there any real benefit here to specifying an underlying type of 'unsigned char' for our enum (that is never used as an opaque enum).
Nov 12 2020
This revision includes the following changes to the initial patch:
- revert the bit-field to unsigned from enum (so as to avoid that nettlesome gcc warning)
- specified a fixed underlying type of 'unsigned char' for the enum FunctionDefinitionKind
- added static_casts when initiatilizing or assigning to the bit-field (which as Aaron astutely noticed was confined to the ctor and setter)
Nov 11 2020
Nov 10 2020
Nov 9 2020
Nov 8 2020
Nov 7 2020
May 16 2020
Apr 25 2018
Apr 24 2018
Apr 4 2018
LGTM - can you commit?
Thank you!
Thanks Erik!
Apr 3 2018
Thanks for working on this fairly embarrassing bug (let's fix this before the week is over :)
Mar 14 2018 ...
Jan 1 2018
Dec 31 2017
Dec 30 2017
Dec 29 2017
Dec 28 2017
Dec 27 2017
Dec 25 2017
Dec 24 2017
I think this looks good enough to commit - do you have commit privileges - or do you need one of us to commit it for you?
thank you!
Dec 23 2017
Dec 21 2017
Added via
Dec 20 2017
Miyuki - please take a look at the patch and let me know if you agree with the changes - or have any concerns...
Sounds good - if I don't get this done over the next seven days - would you mind just pinging me!
Dec 19 2017
Hmm - I think i might make some tweaks to this patch (to be largely symmetric with the similar handling of invalid decl-specifiers on function parameters in Sema::Actions.ActOnParamDeclarator)...
Dec 17 2017
Otherwise, I think this looks good enough to commit.
Thanks for working on this! :)
Dec 16 2017
Dec 1 2017
Nov 11 2017
Just added an additional bit-field to FunctionDecl in
Oct 25 2017
Incorporated Aaron's feedback (although not sure if I caugh tall the white space issues).
|
https://reviews.llvm.org/p/faisalv/
|
CC-MAIN-2021-25
|
refinedweb
| 565
| 55.71
|
From Middle English este, from Old English ēst (“will, consent, favour, grace, liberality, munificence, bounty, kindness, love, good pleasure, harmony, liberal gifts, luxuries”)
Est is a mixin library based on Less which helps you write Less code more efficiently.
Est provides over 100 handy mixins which generate style rules only when you call them. Est doesn't provide any styles for specific HTML classe names because such “visual classe names” may contaminate HTML semantics. You can build your own style library based on est to accelerate your development.
est can be included in three ways:
import in your Less code:
Download the latest version: .zip or .tar.gz
or just clone it:
$ git clone
// quick import'est/src/all.less';// override global variables@support-ie-version: 10;@default-font-size: 14px;// ...your own awesome less code starts here...
include using compile options:
install Less plugin:
$ npm install -g less-plugin-est
use the plugin:
$ lessc styles.less --est
use it programatically in Node.js apps:
var less = ;var Est = ;var src = '.box { .clearfix(); }';less;
Est Less plugin can take two arguments for now:
autoImport
Automatically import est code before everything.
true by default. Only works from Less
2.4.0.
uniqueDirectives
Eliminate duplicate named at-rules (Less calls them directives). This enables you to define
@keyframes inside mixins and don't have to worry about duplicate output if you call those mixins for several times.
true by default.
You can specify arguments like this to turn off unwanted features:
$ lessc style.less --est="autoImport=false&uniqueDirectives=false"
When used as a plugin, est requires Less to be
2.0.0 or above. When included using
@import in a Less file, the minimal Less version is
2.3.0.
Less supports auto import by plugins only after version
2.4.0. So if you are using older versions, you have to import est using
@import directive in your Less code.
When used as a plugin, est provides
isruleset function (which est used) which is not supported by Less before
2.3.0.
Please feel free to submit issues or just make pull requests.
Test cases are under
test/specs. One directory for each module and each module can have one or more spec files.
Run this under est project directory:
$ npm install$ npm test
|
https://www.npmjs.com/package/less-plugin-est
|
CC-MAIN-2018-05
|
refinedweb
| 383
| 67.25
|
Blog Map
Sometimes you want to convert an XmlNode to an XElement and back again. Some programming libraries define methods that take XmlNode objects as parameters. These libraries also may contain properties and methods that return XmlNode objects. However, it is more convenient to work with LINQ to XML instead of the classes in System.Xml (XmlDocument, XmlNode, etc.) This post presents a bit of code to do these conversions.
This blog is inactive.New blog: EricWhite.com/blogBlog TOC(Update March 5, 2009 - I've written a blog post that shows how to convert from XDocument to XmlDocument (and vice versa). The code presented in that post is a superset of the code presented in this code.)
As an example of where you need these methods, you can do a lot with SharePoint using web services. The proxy classes that wsdl.exe creates contain methods that use classes in System.Xml.
It is convenient to write these conversions as extension methods. When converting to and from classes in System.Xml, the code reads much better when you tack an extension method on the end instead of surrounding the expression with a method call. The following code shows how to call the GetListItems method of the Lists web service using the GetXmlNode and GetXElement extension methods:
XElement queryOptions = new XElement("QueryOptions", new XElement("Folder", "Open XML Documents"), new XElement("ViewAttributes", new XAttribute("Scope", "Recursive")));XElement viewFields = new XElement("ViewFields", new XElement("FieldRef", new XAttribute("Name", "GUID")), new XElement("FieldRef", new XAttribute("Name", "ContentType")), new XElement("FieldRef", new XAttribute("Name", "BaseName")), new XElement("FieldRef", new XAttribute("Name", "Modified")), new XElement("FieldRef", new XAttribute("Name", "EncodedAbsUrl")));XElement listContent = wsList .GetListItems(documentLibraryGUID, null, null, viewFields.GetXmlNode(), null, queryOptions.GetXmlNode(), webId) .GetXElement();
To create an XmlNode from an XElement, you create an XmlReader using the XNode.CreateReader method, create an XmlDocument, and load the document using the XmlReader. XmlDocument inherits XmlNode.
To create an XElement from an XmlNode, you create an XDocument, create an XmlWriter using the XContainer.CreateWriter method, write the XmlNode to the XDocument, and return the root element of the XDocument.
The following example contains the extension methods and some code that shows their use:
using System;using System.Collections.Generic;using System.Linq;using System.Xml;using System.Xml.Linq; } }}class Program{ static void Main(string[] args) { XElement e = new XElement("Root", new XElement("Child", new XAttribute("Att", "1") ) ); XmlNode xmlNode = e.GetXmlNode(); Console.WriteLine(xmlNode.OuterXml); XElement newElement = xmlNode.GetXElement(); Console.WriteLine(newElement); }}
Code is attached.
Sometimes you want to work with Open XML documents in memory. This blog post presents a bit of code that shows how to work with in-memory documents as a MemoryStream. The code works with either Open XML SDK V1 or CTP1 of the Open XML SDK V2.
By combining LINQ to SQL with LINQ to Objects in this fashion, you can write some pretty simple C# code that uses LINQ to join data across two separate, disparate data sources.
This post describes the issues and presents a minimal amount of code that shows how to open an Open XML document from a SharePoint list, modify it, and then save it back to either the same location, or a different one if you desire.
There is an approach using LINQ to XML that provides some of the benefits of a strongly typed document object model. The approach consists of declaring a static class with static, initialized XName and XNamespace fields in the class, and then using those XName and XNamespace objects in the LINQ to XML code that creates and queries XML trees.
|
http://blogs.msdn.com/b/ericwhite/archive/2008/12.aspx?PostSortBy=MostViewed&PageIndex=1
|
CC-MAIN-2014-41
|
refinedweb
| 600
| 55.64
|
The
numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.
To use
numpy you need to import the module, using for example:
from numpy import *
In the
numpy package the terminology used for vectors, matrices and higher-dimensional data sets is array.
numpyarrays
There are a number of ways to initialize new numpy arrays, for example from
arange,
linspace, etc.
For example, to create new vector and matrix arrays from Python lists we can use the
numpy.array function.
# a vector: the argument to the array function is a Python list v = array([1,2,3,4]) v
# a matrix: the argument to the array function is a nested Python list M = array([[1, 2], [3, 4]]) M
The
v and
M objects are both of the type
ndarray that the
numpy module provides.
type(v), type(M)
The difference between the
v and
M arrays is only their shapes. We can get information about the shape of an array by using the
ndarray.shape property.
v.shape
M.shape
The number of elements in the array is available through the
ndarray.size property:
M.size
Equivalently, we could use the function
numpy.shape and
numpy.size
shape(M)
size(M)
So far the
numpy.ndarray looks awefully much like a Python list (or nested list). Why not simply use Python lists for computations instead of creating a new array type?
There are several reasons:
numpyarrays can be implemented in a compiled language (C and Fortran is used).
Using the
dtype (data type) property of an
ndarray, we can see what type the data of an array has:
M.dtype
We get an error if we try to assign a value of the wrong type to an element in a numpy array:
M[0,0] = "hello"
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-a09d72434238> in <module>() ----> 1 M[0,0] = "hello"
ValueError: invalid literal for long() with base 10: 'hello'
If we want, we can explicitly define the type of the array data when we create it, using the
dtype keyword argument:
M = array([[1, 2], [3, 4]], dtype=complex) M
Common data types that can be used with
dtype are:
int,
float,
complex,
bool,
object, etc.
We can also explicitly define the bit size of the data types, for example:
int64,
int16,
float128,
complex128.
For larger arrays it is inpractical to initialize the data manually, using explicit python lists. Instead we can use one of the many functions in
numpy that generate arrays of different forms. Some of the more common are:
# create a range x = arange(0, 10, 1) # arguments: start, stop, step x
x = arange(-1, 1, 0.1) x
# using linspace, both end points ARE included linspace(0, 10, 25)
logspace(0, 10, 10, base=e)
x, y = mgrid[0:5, 0:5] # similar to meshgrid in MATLAB
x
y
from numpy import random
# uniform random numbers in [0,1] random.rand(5,5)
# standard normal distributed random numbers random.randn(5,5)
# a diagonal matrix diag([1,2,3])
# diagonal with offset from the main diagonal diag([1,2,3], k=1)
zeros((3,3))
ones((3,3))
A very common file format for data files is comma-separated values (CSV), or related formats such as TSV (tab-separated values). To read data from such files into Numpy arrays we can use the
numpy.genfromtxt function. For example,
!head stockholm_td_adj.dat
data = genfromtxt('stockholm_td_adj.dat')
data.shape
fig, ax = plt.subplots(figsize=(14,4)) ax.plot(data[:,0]+data[:,1]/12.0+data[:,2]/365, data[:,5]) ax.axis('tight') ax.set_title('tempeatures in Stockholm') ax.set_xlabel('year') ax.set_ylabel('temperature (C)');
Using
numpy.savetxt we can store a Numpy array to a file in CSV format:
M = random.rand(3,3) M
savetxt("random-matrix.csv", M)
!cat random-matrix.csv
savetxt("random-matrix.csv", M, fmt='%.5f') # fmt specifies the format !cat random-matrix.csv
Useful when storing and reading back numpy array data. Use the functions
numpy.save and
numpy.load:
save("random-matrix.npy", M) !file random-matrix.npy
load("random-matrix.npy")
M.itemsize # bytes per element
M.nbytes # number of bytes
M.ndim # number of dimensions
We can index elements in an array using square brackets and indices:
# v is a vector, and has only one dimension, taking one index v[0]
# M is a matrix, or a 2 dimensional array, taking two indices M[1,1]
If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)
M
M[1]
The same thing can be achieved with using
: instead of an index:
M[1,:] # row 1
M[:,1] # column 1
We can assign new values to elements in an array using indexing:
M[0,0] = 1
M
# also works for rows and columns M[1,:] = 0 M[:,2] = -1
M
Index slicing is the technical name for the syntax
M[lower:upper:step] to extract part of an array:
A = array([1,2,3,4,5]) A
A[1:3]
Array slices are mutable: if they are assigned a new value the original array from which the slice was extracted is modified:
A[1:3] = [-2,-3] A
We can omit any of the three parameters in
M[lower:upper:step]:
A[::] # lower, upper, step all take the default values
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array
A[:3] # first three elements
A[3:] # elements from index 3
Negative indices counts from the end of the array (positive index from the begining):
A = array([1,2,3,4,5])
A[-1] # the last element in the array
A[-3:] # the last three elements
Index slicing works exactly the same way for multidimensional arrays:
A = array([[n+m*10 for n in range(5)] for m in range(5)]) A
# a block from the original array A[1:4, 1:4]
# strides A[::2, ::2]
Fancy indexing is the name for when an array or list is used in-place of an index:
row_indices = [1, 2, 3] A[row_indices]
col_indices = [1, 2, -1] # remember, index -1 means the last element A[row_indices, col_indices]
We can also use index masks: If the index mask is an Numpy array of data type
bool, then an element is selected (True) or not (False) depending on the value of the index mask at the position of each element:
B = array([n for n in range(5)]) B
row_mask = array([True, False, True, False, False]) B[row_mask]
# same thing row_mask = array([1,0,1,0,0], dtype=bool) B[row_mask]
This feature is very useful to conditionally select elements from an array, using for example comparison operators:
x = arange(0, 10, 0.5) x
mask = (5 < x) * (x < 7.5) mask
x[mask]
The index mask can be converted to position index using the
where function
indices = where(mask) indices
x[indices] # this indexing is equivalent to the fancy indexing x[mask]
With the diag function we can also extract the diagonal and subdiagonals of an array:
diag(A)
diag(A, -1)
The
take function is similar to fancy indexing described above:
v2 = arange(-3,3) v2
row_indices = [1, 3, 5] v2[row_indices] # fancy indexing
v2.take(row_indices)
But
take also works on lists and other objects:
take([-3, -2, -1, 0, 1, 2], row_indices)
Constructs an array by picking elements from several arrays:
which = [1, 0, 1, 0] choices = [[-2,-2,-2,-2], [5,5,5,5]] choose(which, choices)
Vectorizing code is the key to writing efficient numerical calculation with Python/Numpy. That means that as much as possible of a program should be formulated in terms of matrix and vector operations, like matrix-matrix multiplication.
We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.
v1 = arange(0, 5)
v1 * 2
v1 + 2
A * 2, A + 2
When we add, subtract, multiply and divide arrays with each other, the default behaviour is element-wise operations:
A * A # element-wise multiplication
v1 * v1
If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:
A.shape, v1.shape
A * v1
What about matrix mutiplication? There are two ways. We can either use the
dot function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments:
dot(A, A)
dot(A, v1)
dot(v1, v1)
Alternatively, we can cast the array objects to the type
matrix. This changes the behavior of the standard arithmetic operators
+, -, * to use matrix algebra.
M = matrix(A) v = matrix(v1).T # make it a column vector
v
M * M
M * v
# inner product v.T * v
# with matrix objects, standard matrix algebra applies v + M*v
If we try to add, subtract or multiply objects with incomplatible shapes we get an error:
v = matrix([1,2,3,4,5,6]).T
shape(M), shape(v)
M * v
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-100-995fb48ad0cc> in <module>() ----> 1 M * v
/Users/rob/miniconda/envs/py27-spl/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.pyc in __mul__(self, other) 339 if isinstance(other, (N.ndarray, list, tuple)) : 340 # This promotes 1-D vectors to row vectors --> 341 return N.dot(self, asmatrix(other)) 342 if isscalar(other) or not hasattr(other, '__rmul__') : 343 return N.dot(self, other)
ValueError: shapes (5,5) and (6,1) not aligned: 5 (dim 1) != 6 (dim 0)
See also the related functions:
inner,
outer,
cross,
kron,
tensordot. Try for example
help(kron).
Above we have used the
.T to transpose the matrix object
v. We could also have used the
transpose function to accomplish the same thing.
Other mathematical functions that transform matrix objects are:
C = matrix([[1j, 2j], [3j, 4j]]) C
conjugate(C)
Hermitian conjugate: transpose + conjugate
C.H
We can extract the real and imaginary parts of complex-valued arrays using
real and
imag:
real(C) # same as: C.real
imag(C) # same as: C.imag
Or the complex argument and absolute value
angle(C+1) # heads up MATLAB Users, angle is used instead of arg
abs(C)
linalg.inv(C) # equivalent to C.I
C.I * C
linalg.det(C)
linalg.det(C.I)
Often it is useful to store datasets in Numpy arrays. Numpy provides a number of functions to calculate statistics of datasets in arrays.
For example, let's calculate some properties from the Stockholm temperature dataset used above.
# reminder, the tempeature dataset is stored in the data variable: shape(data)
# the temperature data is in column 3 mean(data[:,3])
The daily mean temperature in Stockholm over the last 200 years has been about 6.2 C.
std(data[:,3]), var(data[:,3])
# lowest daily average temperature data[:,3].min()
# highest daily average temperature data[:,3].max()
d = arange(0, 10) d
# sum up all elements sum(d)
# product of all elements prod(d+1)
# cummulative sum cumsum(d)
# cummulative product cumprod(d+1)
# same as: diag(A).sum() trace(A)
We can compute with subsets of the data in an array using indexing, fancy indexing, and the other methods of extracting data from an array (described above).
For example, let's go back to the temperature dataset:
!head -n 3 stockholm_td_adj.dat
The dataformat is: year, month, day, daily average temperature, low, high, location.
If we are interested in the average temperature only in a particular month, say February, then we can create a index mask and use it to select only the data for that month using:
unique(data[:,1]) # the month column takes values from 1 to 12
mask_feb = data[:,1] == 2
# the temperature data is in column 3 mean(data[mask_feb,3])
With these tools we have very powerful data processing capabilities at our disposal. For example, to extract the average monthly average temperatures for each month of the year only takes a few lines of code:
months = arange(1,13) monthly_mean = [mean(data[data[:,1] == month, 3]) for month in months] fig, ax = plt.subplots() ax.bar(months, monthly_mean) ax.set_xlabel("Month") ax.set_ylabel("Monthly avg. temp.");
When functions such as
min,
max, etc. are applied to a multidimensional arrays, it is sometimes useful to apply the calculation to the entire array, and sometimes only on a row or column basis. Using the
axis argument we can specify how these functions should behave:
m = random.rand(3,3) m
# global max m.max()
# max in each column m.max(axis=0)
# max in each row m.max(axis=1)
Many other functions and methods in the
array and
matrix classes accept the same (optional)
axis keyword argument.
The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays.
A
n, m = A.shape
B = A.reshape((1,n*m)) B
B[0,0:5] = 5 # modify the array B
A # and the original variable is also changed. B is only a different view of the same data
We can also use the function
flatten to make a higher-dimensional array into a vector. But this function create a copy of the data.
B = A.flatten() B
B[0:5] = 10 B
A # now A has not changed, because B's data is a copy of A's, not refering to the same data
With
newaxis, we can insert new dimensions in an array, for example converting a vector to a column or row matrix:
v = array([1,2,3])
shape(v)
# make a column matrix of the vector v v[:, newaxis]
# column matrix v[:,newaxis].shape
# row matrix v[newaxis,:].shape
Using function
repeat,
tile,
vstack,
hstack, and
concatenate we can create larger vectors and matrices from smaller ones:
a = array([[1, 2], [3, 4]])
# repeat each element 3 times repeat(a, 3)
# tile the matrix 3 times tile(a, 3)
b = array([[5, 6]])
concatenate((a, b), axis=0)
concatenate((a, b.T), axis=1)
vstack((a,b))
hstack((a,b.T))
To achieve high performance, assignments in Python usually do not copy the underlaying objects. This is important for example when objects are passed between functions, to avoid an excessive amount of memory copying when it is not necessary (technical term: pass by reference).
A = array([[1, 2], [3, 4]]) A
# now B is referring to the same array data as A B = A
# changing B affects A B[0,0] = 10 B
A
If we want to avoid this behavior, so that when we get a new completely independent object
B copied from
A, then we need to do a so-called "deep copy" using the function
copy:
B = copy(A)
# now, if we modify B, A is not affected B[0,0] = -5 B
A
Generally, we want to avoid iterating over the elements of arrays whenever we can (at all costs). The reason is that in a interpreted language like Python (or MATLAB), iterations are really slow compared to vectorized operations.
However, sometimes iterations are unavoidable. For such cases, the Python
for loop is the most convenient way to iterate over an array:
v = array([1,2,3,4]) for element in v: print(element)
M = array([[1,2], [3,4]]) for row in M: print("row", row) for element in row: print(element)
When we need to iterate over each element of an array and modify its elements, it is convenient to use the
enumerate function to obtain both the element and its index in the
for loop:
for row_idx, row in enumerate(M): print("row_idx", row_idx, "row", row) for col_idx, element in enumerate(row): print("col_idx", col_idx, "element", element) # update the matrix M: square each element M[row_idx, col_idx] = element ** 2
# each element in M is now squared M
As mentioned several times by now, to get good performance we should try to avoid looping over elements in our vectors and matrices, and instead use vectorized algorithms. The first step in converting a scalar algorithm to a vectorized algorithm is to make sure that the functions we write work with vector inputs.
def Theta(x): """ Scalar implemenation of the Heaviside step function. """ if x >= 0: return 1 else: return 0
Theta(array([-3,-2,-1,0,1,2,3]))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-165-6658efdd2f22> in <module>() ----> 1 Theta(array([-3,-2,-1,0,1,2,3]))
<ipython-input-164-9a0cb13d93d4> in Theta(x) 3 Scalar implemenation of the Heaviside step function. 4 """ ----> 5 if x >= 0: 6 return 1 7 else:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
OK, that didn't work because we didn't write the
Theta function so that it can handle a vector input...
To get a vectorized version of Theta we can use the Numpy function
vectorize. In many cases it can automatically vectorize a function:
Theta_vec = vectorize(Theta)
Theta_vec(array([-3,-2,-1,0,1,2,3]))
We can also implement the function to accept a vector input from the beginning (requires more effort but might give better performance):
def Theta(x): """ Vector-aware implemenation of the Heaviside step function. """ return 1 * (x >= 0)
Theta(array([-3,-2,-1,0,1,2,3]))
# still works for scalars as well Theta(-1.2), Theta(2.6)
When using arrays in conditions,for example
if statements and other boolean expressions, one needs to use
any or
all, which requires that any or all elements in the array evalutes to
True:
M
if (M > 5).any(): print("at least one element in M is larger than 5") else: print("no element in M is larger than 5")
if (M > 5).all(): print("all elements in M are larger than 5") else: print("all elements in M are not larger than 5")
Since Numpy arrays are statically typed, the type of an array does not change once created. But we can explicitly cast an array of some type to another using the
astype functions (see also the similar
asarray function). This always create a new array of new type:
M.dtype
M2 = M.astype(float) M2
M2.dtype
M3 = M.astype(bool) M3
%reload_ext version_information %version_information numpy
|
https://share.cocalc.com/share/d8d2faccf6f6373d5e0a57a2849cbf76273d673e/scientific-python-lectures/Lecture-2-Numpy.ipynb?viewer=share
|
CC-MAIN-2020-16
|
refinedweb
| 3,090
| 50.26
|
A common question readers ask is how to make D3 force-directed graphs work with React. It's a little tricky.
You'd think it's obvious – use D3 to drive the force simulation, React for rendering. That's the approach I teach in React For Dataviz.
But something changed in recent versions of D3 and I racked my brain for hours. It nearly killed me. 😂
What are force-directed graphs
Force-directed graphs are one of D3's magic tricks. A feature that demos nicely and solves an important problem.
You can use them to layout complex data.
Simulate collisions.
And even cloth simulations, if you squint hard enough.
Finding the best layout for a complex graph is hard. Even impossible in some cases. Force-directed graphs solve the problem by simulating physical forces between nodes, which leads to visually pleasing results.
The downside is that you have to wait for the simulation. You can pre-generate the final result before rendering, but you're waiting at some point somewhere.
Luckily the animations look nice 😊
Build a force-directed graph with React and D3
D3's d3-force module gives you the tools to simulate forces.
You create a new simulation with
d3.forceSimulation(), add different forces with
.force('name', func), pass-in data with
.nodes(), and update your visuals on each tick of the animation with
.on('tick', func).
Where it gets tricky in a React context is that
d3.forceSimulation() assumes it's running on DOM nodes directly. It wants to change attributes.
Force-less React & D3 force-directed graph
Let's start with a force simulation that has no forces.
Nothing happens so the simulation is not very interesting. But it sets us up.
We have a
ForceGraph component that accepts a list of
nodes as its prop and renders a circle for each. This is the "React handles rendering" part.
function ForceGraph({ nodes }) {const [animatedNodes, setAnimatedNodes] = useState([])// ...return (<g>{animatedNodes.map((node) => (<circlecx={node.x}cy={node.y}r={node.r}key={node.id}))}</g>)}
We render from
animatedNodes in state instead of the
nodes prop. Our force simulation is going to change these values over time, which means they have to become part of state.
The animation runs in a
useEffect.
// re-create animation every time nodes changeuseEffect(() => {const simulation = d3.forceSimulation()// update state on every framesimulation.on("tick", () => {setAnimatedNodes([...simulation.nodes()])})// copy nodes into simulationsimulation.nodes([...nodes])// slow down with a small alphasimulation.alpha(0.1).restart()// stop simulation on unmountreturn () => simulation.stop()}, [nodes])
Any time the
ForceGraph component mounts or the
nodes prop changes, we start a new simulation.
Visual updates happen by updating component state on every tick of the animation. You can think of these as frames.
// update state on every framesimulation.on("tick", () => {setAnimatedNodes([...simulation.nodes()])})
You have to make a copy of the nodes array or React won't realize there's a change.
d3.forceSimulation mutates state in-place, which fails the JavaScript equality test – it's the same object.
simulation.nodes() returns the current state of our simulation.
We return
simulation.stop() to clean up after ourselves when the component unmounts or a new effect starts.
Add a centering force
Let's add a centering force to make our visualization more visible. You can have one centering force per graph.
We've got some action now! The cluster of nodes moves towards the
(400, 300) coordinates at the center of our SVG.
const simulation = d3.forceSimulation().force("x", d3.forceX(400)).force("y", d3.forceY(300))
d3.forceX and
d3.forceY create a 1-dimensional force towards the given coordinate. This force acts on every node in your graph and you can't change that. I tried.
If you want a multi-focal graph like in my tweet, you'll need to overlay multiple
ForceGraph components. Each with its own centering force.
A neat trick would be to define the centering coordinates with a mouse click. I'll let you play with that, you can get inspiration for correctly detecting mouse position from my Free-hand mouse drawing with D3v6 and React Hooks article.
Add a many-body force to repel or attract nodes
A many-body force lets nodes push or pull against each other.
You can think of this force as a "charge" between electrons.
const simulation = d3.forceSimulation().force("x", d3.forceX(400)).force("y", d3.forceY(300)).force("charge", d3.forceManyBody().strength(2))
A positive value makes nodes attract, negative pushes them apart. The bigger the value the stronger the force.
Try the slider to see what happens :)
We wrapped the initial node generation in a
useMemo to avoid re-creating the nodes when you change the slider. That way
d3.forceSimulation() can look stable through changes.
const nodes = useMemo(() =>d3.range(50).map((n) => {return { id: n, r: 5 }}),[])
Add collisions to set smallest distance between nodes
A high charge looked weird and the nodes eventually overlapped into a single circle. That's not good.
We add a collision force to ensure that can't happen.
No matter how hard you squeeze, the nodes won't overlap 💪
const simulation = d3.forceSimulation().force("x", d3.forceX(400)).force("y", d3.forceY(300)).force("charge", d3.forceManyBody().strength(charge)).force("collision", d3.forceCollide(5))
d3.forceCollide takes an argument that specifies collision radius. We set it at
5 because that's how big our nodes are. You can pass a function to adjust this radius for individual nodes.
d3.forceCollide((node) => node.r)
That lets you support different sizes, enforce a gap, or allow some overlap.
What about links between nodes?
Links work similarly. You'll need a list of links between nodes, like this:
{source: node.id,target: node.id}
Pass it into your simulation with
.links() and create a link force using
force('links', d3.forceLink()). Usually this is an attracting force but it doesn't have to be! Go wild
Rendering your links is similar to rendering your nodes: Iterate through the links, render an element. Lines are a popular choice.
Don't forget to update your animation tick to re-render links.
// update state on every framesimulation.on("tick", () => {setAnimatedNodes([...simulation.nodes()])setAnimatedLinks([...simulation.links()])})
React ensures both updates happen in the same frame.
Give it a shot and lemme know if that doesn't work. Exercise for the reader and all that 😛
Cheers,
~Swizec
About the Author React for Data Visualization — a proper video course. Designed for busy people with real lives like you. Over 8 hours of video material, split into chunks no longer than 5 minutes, a bunch of new chapters, and techniques I discovered along the way.
React for Data Visualization is the best way to learn how to build scalable dataviz components your whole team can understand.
Some of my work has been featured in 👇
|
https://reactfordataviz.com/articles/force-directed-graphs-with-react-and-d3v7/
|
CC-MAIN-2022-40
|
refinedweb
| 1,141
| 60.51
|
in reply to Namespace error when parsing with XML::LibXML
My understanding of properly formed XML is that those namespace attributes should only have a single URI in them -- not two URIs separated by a space. It appears XML::LibXML would agree with me.
So if the XML is not well formed, I see only two optoins: You must either fix it at the source or munge the XML before trying to parse it. If you can't fix it at the source, I'd just hack in a very specific string substitution to convert that literal double-URI string into a single URI string..
My spouse
My children
My pets
My neighbours
My fellow monks
Wild Animals
Anybody
Nobody
Myself
Spies
Can't tell (I'm NSA/FBI/HS/...)
Others (explain your deviation)
Results (50 votes). Check out past polls.
|
http://www.perlmonks.org/?node_id=863791
|
CC-MAIN-2016-50
|
refinedweb
| 141
| 69.21
|
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. Typically, scope is used to define the extent of information hiding – that is, the visibility or accessibility of variables from different parts of the program. Scopes can:
- contain declarations or definitions of identifiers;
- contain statements and/or expressions which define an executable algorithm or part thereof;
- nest or be nested.
Scope dynamic contexts in which the module’s code may be invoked.
It is important to have a good understanding of scope because if you try to use an Identifier that’s not in scope, you will get the compiler error. An Identifier is available only after its definition has ended, meaning that is not usually possible to define an Identifier in terms of itself. The portion of the program where an identifier can be used is known as its scope. For example, when we declare a local variable in a block, it can be referenced only in that block and in blocks nested within that block. The type of scope is always determined by the location of which you declare the Identifier (except for labels which always have function scope) There are four type of scopes: function, file, block and function prototype.
1. Block Scope
Objective-C code is divided into sequences of code blocks and files that define the structure of a program. Each block, referred to as a statement block, is encapsulated by braces ({}). Each block has its own scope. No conflict occurs if the same identifier is declared in two blocks. If one block encloses the other, the declaration in the enclosed block hides that in the enclosing block until the end of the enclosed block is reached. We may also state that when the block is exited, the names declared in the block are no longer available.
When one block is nested inside another, the variables from the outer block are usually visible in the nested block. However, if the declaration of a variable in a nested block has the same name as a variable that is declared in an enclosing block, the declaration in the nested block hides the variable that was declared in the enclosing block. The original declaration is restored when program control returns to the outer block. This is called block visibility. For example:
#include <stdio.h> int main(){ int i = 32; /* block scope 1*/ printf("Within the outer block: i=%d\n", i); { int i, j; /* block scope 2, int i hides the outer int i*/ printf("Within the inner block:\n"); for (i=0, j=10; i<=10; i++, j--){ printf("i=%2d, j=%2d\n", i, j); } } /* the end of the inner block */ printf("Within the outer block: i=%d\n", i); return 0; }
Program Output:
2. Function scope
A label is the only kind of identifier that has function scope. A label is declared implicitly by its use in a statement. Label names must be unique within a function.
3. File scope
Identifiers appearing outside of any block, function, or function prototype, have file scope. Identifier names with file scope are often called “global” or “external.” The scope of a global identifier begins at the point of its definition or declaration and terminates at the end of the translation unit. Unlike other scopes, multiple declarations of the same identifier with file scope can exist in a compilation unit, so long as the declarations are compatible.
Some coding guidelines documents recommend that the number of objects declared at file scope be minimized. However, there have been no studies showing that alternative design/coding techniques would have a more worthwhile cost/benefit associated with their use. Identifiers declared as types must appear at file scope if:
- objects declared to have these types appear at file scope,
- objects declared to have these types appear within more than one function definition (having multiple, textual, declarations of the same type in different block scopes is likely to increase the cost of maintenance and C does not support the passing of types as parameters),
- other types, at files scope, reference these types in their own declaration.
Any program using file scope objects can be written in a form that does not use file scope objects. This can be achieved either by putting all statements in the function main, or by passing, what were file scope, objects as parameters. The following are some of the advantages of defining objects at file scope (rather than passing the values they contain via parameters) include:
- Efficiency of execution. Accessing objects at file scope does not incur any parameter passing overheads. The execution-time efficiency and storage issues are likely to be a consideration in a freestanding environment, and unlikely to be an issue in a hosted environment.
- Minimizes the cost of adding new function definitions to existing source code. If the information needed by the new function is not available in a visible object, it will have to be passed as an argument.
The function calling the new function now has a requirement to access this information, to pass it as a parameter. This requirement goes back through all call chains that go through the newly created function. If the objects that need to be accessed have file scope, there will be no need to add any new arguments to function calls and parameters to existing function definitions.
The following are some of the disadvantages of defining objects at file scope:
- Storage is used for the duration of program execution.
- There is a single instance of object. Most functions are not recursive, so separate objects for nested invocations of a function are not usually necessary.
- Reorganizing a program by moving function definitions into different translation units requires considering the objects they access. These may need to be given external linkage.
- Greater visibility of identifiers reduces the developer effort needed to access them, leading to a greater number of temporary accesses.
- Information flow between functions is implicit. Developers need to make a greater investment in comprehending which calls cause which objects to be modified. Experience shows that developers tend to overestimate the reliability of their knowledge of which functions access which file scope identifiers.
- When reading the source of a translation unit, it is usually necessary to remember all of the file scope objects defined within it. Reducing the number of file scope objects reduces the amount of information that needs to be in developers long-term memory.
The only checks made on references to file scope objects is that they are visible and that the necessary type requirements are met. For issues, such as information flow, objects required to have certain values at certain points are not checked (such checking is in the realm of formal checking against specifications). Passing information via parameters does not guarantee that mistakes will not be made; but the need to provide arguments acts as a reminder of the information accessed by a function and the possible consequences of the call.
4. Function prototype
The declarator or type specifier for an identifier with function-prototype scope appears within the list of parameter declarations in a function prototype (not part of the function declaration). Its scope terminates at the end of the function declarator.For example:
int students ( int david, int susan, int mary, int john );.
INTERNATIONAL STANDARD – Programming languages – C, described the Scopes of an Identifiers as under:
1. An identifier can denote an object; a function; and macro parameters are not considered further here, because prior to the semantic phase of program translation any occurrences of macro names in the source file are replaced by the preprocessing token sequences that constitute their macro definitions.
2. For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope. Different entities designated by the same identifier either have different scopes, or are in different name spaces. There are four kinds of scopes: function, file, block, and function prototype. (A function prototype is a declaration of a function that declares the types of its parameters.)
3. A label name is the only kind of identifier that has function scope. It can be used (in a goto statement) anywhere in the function in which it appears, and is declared implicitly by its syntactic appearance (followed by a : and a statement). end of end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.
5. Unless explicitly stated otherwise, where this International Standard uses the term ‘‘identifier’’ to refer to some entity (as opposed to the syntactic construct), it refers to the entity in the relevant name space whose declaration is visible at the point the identifier occurs.
6. Two identifiers have the same scope if and only if their scopes terminate at the same point..
8. As a special case, a type name (which is not a declaration of an identifier) is considered to have a scope that begins just after the place within the type name where the omitted identifier would appear where it not omitted.
30.756074 76.787399
Advertisements
|
https://vineetgupta22.wordpress.com/2011/11/09/scope-of-identifier/
|
CC-MAIN-2017-30
|
refinedweb
| 1,555
| 50.26
|
Hi,
I'm kinda new to JScripting. Tried to implement the resize features as desribed in the SIlverlight documentation () but that doesn't seem to work with 1.1 anymore. Any clues?
Paul.
I imagine it's not working for the same reason that you can't programmatically trigger full-screen; MS doesn't want that to be possible from non-user-interaction (according to the full-screen docs). It's understandable, I guess; remember the days of annoying JavaScript popup advertising... I guess if you want to implement resize, then it has to be the plugin being actively resized by the user (or as a result of clicking some control within the plugin).
Guten Abend Paul,
The kind of "liquid" resizing behavior you want (if I understand correctly) does work and is demonstrated by the Silverlight Airlines 1.1 example:Search this page for "Airlines":
Good article by the guy who wrote the sample:
The key to the resizing is the Javascript "resize" event handler in Default.html.js.
It looks like you could also handle the resizing in C# (my preference) rather than Javascript. The code below shows what that looks like. I added a handler for the BrowserHost.Resize event to Silverlight Airlines Default.xaml.cs. (I haven't fully tested this, but it should get you started.)
For a bit more about resize handling see this (search for "resize"):
Alan Cobb------------------- Code --------------------using System.Windows.Interop;using System.Diagnostics;
public class DefaultCanvas : Canvas{ private void PageLoaded(object obj, EventArgs evt) { InitializeComponent(); ...
// 2007-09-03: ASC: Added: BrowserHost.Resize+= new EventHandler( BrowserHost_Resize );
}
// 2007-09-03: ASC: Added: void BrowserHost_Resize( object sender, EventArgs e ) { Debug.WriteLine( "@.49 BrowserHost.ActualHeight:" + BrowserHost.ActualHeight + " BrowserHost.ActualWidth:" + BrowserHost.ActualWidth ); }
Hi Alan,
Thanks for the quick reply. No, doesn't work. I had already found that out and tried it. Below is the code I wrote to get resizing to work. As the Plugin is displayed for the first time it does receive a resize event, but that is the only one received.
public void Page_Loaded ( object o, EventArgs e ) {
// Required to initialize variablesInitializeComponent ();MouseMove += new MouseEventHandler ( Page_MouseMove ); Test.MouseLeftButtonDown += new MouseEventHandler ( Test_MouseLeftButtonDown );BrowserHost.Resize += new EventHandler ( BrowserHost_Resize );
}void BrowserHost_Resize ( object sender, EventArgs e ) {
Test.Text = "Resize";
// Required to initialize variablesInitializeComponent ();MouseMove += new MouseEventHandler ( Page_MouseMove ); Test.MouseLeftButtonDown += new MouseEventHandler ( Test_MouseLeftButtonDown );BrowserHost.Resize += new EventHandler ( BrowserHost_Resize );
}
Test.Text =
}
}
}
Just to be complete. Here the xaml content:
<
>
</
Hi Paul,
Here is the problem (and again, I'm just borrowing this from the Silverlight Airlines sample) :
For the resizing to work you also need a couple alterations to the default app-wizard generated TestPage.html. First you need to change the fixed pixel width and height to percentages. Second you need to give the elements "html" and "body" (or at least just "body") a percentage-based height also.
Alan Cobb
------------------- Code ----------------------
Altered fragment of TestPage.html:
<head> <title>Silverlight Project Test Page </title> <style type="text/css">
/* Stock version:
.silverlightHost { width: 640px; height: 480px; }*/
/* Replace the above with these two styles: */
.silverlightHost { width: 100%; height: 100%; }
html,body { height:100%; margin: 0; } </style></head>
Alan,
Thanks again. I'll try that out tonight. Must take a look at the Airlines Example too.
I've managed to get this functionality, compatable with RC1.0. I'm just ironing out a few issues (such as plugin not resizing to fill browser in firefox onload because of some crazy caching issue firefox has. need to implement a onpageload() method) Everything works fine in IE though.
Once i've got everythng working propperly i'll upload a full example including how to use max available space keeping height/width ratio of your actual content constant.
Hopefully this will be in a few days or so.
Hi law~,
>issues on Firefox vs IE:
It's funny how even with SL, we still can't get away 100% from cross-browser issues .Alan Cobb
"Funny" is _not_ my word of choice for it!
Got it to work ok. The weird thing is that it wouldn't work in FireFox. After I added a Style in the 'SilverLightControlHost' - Div it also showed up in FireFox.
This code works in both IE and FireFox:
<!-- saved from url=(0014)about:internet -->
font-family:Arial;color:#817C90;
</style>
</style>
<
createSilverlight();
createSilverlight();
I've created a working example of:
1. Getting the plug-in 100% Browser Width and Height2. Stretching my xaml content to fill the available plug-in space3. Retaining height/width ratio and centering the xaml content in the plug-in4. Setting a minimum and maximum size for the plug-in to change to.
I've rushed it but i'll return to it to explain the process properly when i get time at my shiny new blog at: a direct link to the example can be found there.
Hope this is of use!
law~
Hi law~,Thanks for posting that. Your demo runs OK for me under IE7 and FF.One FF "nit": Under Firefox the resizing doesn't seem to happen dynamically as you move the side of the browser window. OTOH, the Silverlight Airlines sample does do the smooth dynamic resizing on both IE and FF. Here's the URL if you want to compare:(Search for "Airlines").Alan Cobb
My main quibble about how it runs in FF is that my function to resize the plugin and perform the scale transform on my canvas doesn't always run on load. I believe that to be because of this: It's something i'm going to look into when i have a chance. The obvious point to make about the Silverlight Airlines example is that that's implemented in 1.1 (!) and i'm trying to concentrate on 1.0 until 1.1 becomes a public release.
Thanks for checking that for me.
update: updated! here
I take it back. This HTML piece of code suddenly doesn't work in Firefox anymore.
Hi Paul, I put together another sample that handles browser resizing, so far it seems to work in both IE and FF. Two samples, one that just repositions the content while resizing the browser the other rescales the content with resizing of the browser...
and source...
if these dont work out for ya I know in previous releases of Silverlight I had to wait a few milliseconds (like 150) after the the actual resize event fired to retrieve the correct width/height values of the plugin and then place the content appropriately. These samples didn't seem to need the timeout though. Let me know if these aren't working correctly for you.
Cheers.
dandobbs - developer - -
I use Silverlight 1.1, how can I make the same thing that you have in this samples (in C#)?
Thanks
law~:
update: updated! here
law~
Hi The link is not working. Thanks.
|
http://silverlight.net/forums/p/4331/12930.aspx
|
crawl-002
|
refinedweb
| 1,139
| 66.33
|
Issue Type: Bug Created: 2012-01-10T18:31:51.000+0000 Last Updated: 2012-02-26T06:07:58.000+0000 Status: Resolved Fix version(s): - 1.11.12 (22/Jun/12)
Reporter: Moshe Teutsch (moteutsch) Assignee: Adam Lundrigan (adamlundrigan) Tags: - Zend_Cache
Related issues: - ZF-9832
Attachments:
Zend_Cache::_makeBackend and Zend_Cache::_makeFrontend throw exceptions if custom backend class name contains backslashes ("\") and therefore doesn't allow namespace custom backends.
Posted by Adam Lundrigan (adamlundrigan) on 2012-02-26T06:05:22.000+0000
Fixed in trunk r24655 r24656 Merged to release-1.11 in r24657
Zend\Cache has been completely refactored in ZF2, and so this code does not need to be forward-ported
|
https://framework.zend.com/issues/browse/ZF-11988?page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel
|
CC-MAIN-2016-30
|
refinedweb
| 112
| 51.24
|
.
def adder(x,y,z):
print("sum:",x+y+z)
adder(10,12,13).
adder()
Lets see what happens when we pass more than 3 arguments in the adder() function.
def adder(x,y,z):
print("sum:",x+y+z)
adder(5,10,15,20,25)
def adder(x,y,z):
print("sum:",x+y+z)
adder(5,10,15,20,25)
TypeError: adder() takes 3 positional arguments but 5 were given
In the above program, we passed 5 arguments to the adder() function instead of 3 arguments due to which we got TypeError.
TypeError
In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols:
We use *args and **kwargs as an argument when we are unsure about the number of arguments to pass in the functions. *.
*
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6))
Data type of argument: <class 'dict'>
Firstname is Sita
Lastname is Sharma
Age is 22
Phone is 1234567890
Data type of argument: <class 'dict'>
Firstname is John
Lastname is Wood.
intro()
|
https://cdn.programiz.com/python-programming/args-and-kwargs
|
CC-MAIN-2019-47
|
refinedweb
| 227
| 68.94
|
Sometimes, when writing a program, you need to create a way to get the attention of the user to bring their focus back to the program. Alerts are a very useful way to do that. If you want to make alerts in C, read on!
Steps
Part 1 of 3:
Character alert
- 1If you want your alert to be portable and work on every computer, you can use the escape code "\a".
- 2Use this example code.
printf("\a");Advertisement
Part 2 of 3:
Beep()
- 1On Windows operating systems, you can use the Beep(int frequency, int ms). It makes a beep of a specified duration and frequency.[2]
- On the Windows7 operating system, this function sends the beep to the sound card. This works only if the computer has speakers or headphones.
- On previous Windows versions, it sends the beep to the motherboard. This works on most computers and no external devices are required.
- 2Include the windows library. Add the following code at the beginning of your program:
#include <windows.h>
- 3When you need a beep, use the following code:
Beep(500, 500);
- 4Change the first number with the frequency of the beep you want. 500 is close to the beep you get with \a.
- 5Change the second number with the duration of the beep in milliseconds. 500 is a half of a second.Advertisement
Part 3 of 3:
Sample Code
- 1Try a program that uses \a to make a beep when a key is pressed, uses ESC to exit:
#include <stdio.h> #include <conio.h> int main() { while(getch() != 27) // Loop until ESC is pressed (27 = ESC) printf("\a"); // Beep. return 0; }
- 2Try a program that makes a beep of a given frequency and duration:
#include <stdio.h> #include <windows.h> int main() { int freq, dur; // Declare the variables printf("Enter the frequency (HZ) and duration (ms): "); scanf("%i %i", &freq, &dur); Beep(freq, dur); // Beep. return 0; }Advertisement
Community Q&A
Search
- QuestionMy system appears to be missing windows.h. How do I solve this?KommaHTop AnswererEnsure that you are on the Windows operating system and that you have the Windows SDK installed. Also, make sure that you are using a C Compiler that is capable of using the Windows API.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.Submit
Advertisement
Tips
- Thanks!
Advertisement
Warnings
- If you need your code to run on Linux, do not use Beep().Thanks!
Advertisement
References
About This Article
Thanks to all authors for creating a page that has been read 27,526 times.
Is this article up to date?
Advertisement
|
https://m.wikihow.com/Create-an-Alert-in-C
|
CC-MAIN-2020-10
|
refinedweb
| 439
| 75.61
|
In my last post, we covered what is XSS and why it’s so hard to prevent, which can seem overwhelming, given what we know now. With even major web sites making mistakes should the rest of us just give up unplug our internet connections and go read a book? Of course not, there are a number of techniques that the community has developed to mitigate the risks of XSS. Here’s what we can do to prevent XSS attacks.
Training
The first line of defense is Training the developers. At this point, it is rare to come across a developer that has not at least heard of SQL injection. I’d like to thank Randall Munroe who’s xkcd comic on Bobby tables has become almost mandatory for a lecture on SQL injection.
If you train your developers to fear user generated content as dangerous they can try to protect your app by constant vigilance and paranoia.
The limitations of this approach are obvious; your developers are human and make mistakes. Sooner or later they will miss something or have a mistaken assumption on which they base the decision to escape.
Static analysis
In large software development shops when an XSS is found the OpSec team will usually write some kind of signature and scan the entire code base for similar security flaws.
Linters
Over time these scanners have become formidable linters agent a number of recognizable errors. Particularly in conjunction with web frameworks that try to make escaping the user content the obvious thing to do when it is needed. These tools add lots of value; however, like all pattern-based matches, there is a limit to the soundness of their conclusions.
Taint tracking
The gold standard of static analysis is taint tracking. This is where the system tracks the origin and destination of every string. This enables software to determine if a string moves from one context to another without being escaped.
In a typed language, this can be accomplished by creating new subtypes of string. HTML_string , SQL_string , JS_string , OS_cmd_string , CSS_string None of the string
types are able to be concatenated with each other
In [1]: HTML_str(‘hello ‘)+’world’
TypeError: cannot concatenate ‘HTML_str’ and ‘str’ objects
In [2]: HTML_str(‘hello ‘) + HTML_str.escape(‘world’)
<HTML_str “hello world”>
If there is an improper concatenation the code will not even compile (or in the case of interpreted languages throw an exception).
This technique can also be used in any language that lacks a typing tradition using the metadata pattern.
{“some_value”:”<html>”}
Can be transformed to have a meta_dict that describes the object.
{“some_value”:[{“metadata”: true,
“str_type”: “text/html”} “<html>”]}
By replacing the object with the list [meta_dict object] we can now add keys to the meta_dict for our strings and our software systems can enforce that the templates will only take strings with meta_dicts that contain the correct tags. Once you have metadata that can flow around your system with the data you will be surprised how many things get simpler.
The drawback to this kind of system is that it is difficult to ensure that this tainting metadata stays with the data as it is passed through libraries and micro-services. Even when your micro-services alertly pass meta_dict tagged objects. It can be done and in critical systems, it will be but it remains a daunting task.
Active scanning
Scanning is the penetration testers bread and butter. This is the technique that treats the application as a black box. Start at the main page and find every form and field where the user can put text. Get parameters, post parameters, HTTP headers, and more can be user-generated data. If the user can put a string there, the pen-tester wants to send it something it did not expect. If the scanner sends a string like the one below
key: !!python/object/apply:os.system [“curl”] and your server opens an HTTP connection to the pen-tester’s server, you have a problem.
To use this technique, you don’t have to plum metadata throw your system or drive your developers to paranoia. You just find the bugs and fix them.
Automatic scanners can be used to run through your site constantly monitoring for the introduction of new XSS vulnerabilities. When the automatic scanner is randomly generating attack payloads this is known as fuzzing and is a rich source of bug reports.
There is, of course, a downside to this method. What the black box nature of this testing bought us it costs us in the usefulness of the report. Where the static analysis told us a file line and character at which the bug was detected, the scanner just tells us which API endpoint and field. We are left to go spelunking through our architecture trying to figure out where this field goes who processed it. Was it stored in a data base? There can sometimes be a notable gap from finding a bug with the active scanner and fixing it.
Runtime protection
Now, we come to my favorite mitigation. The runtime protection is the last line of defense. To get here the developers have written code, the static analysis passed it, the active scanners missed it, and yet here is an XSS that has appeared on your site in production. How did this happen? What do you I am your teacher.”
Mazer Rackham, Ender’s Game p.184 By Orson Scott Card
Why did the flaws show up in production? Because you protected against everything you could think of and the hacker did something else.
WAF
There is a long history in the network security world of making lists of things not to do. The firewall in the network layer was a list of IPs to not talk to. In the transport layer, we list the ports not to talk on. Now, the firewall has reached the application layer.
The application layer is not like the lower layers with a small amount of highly regular data. HTTP has lots of places to put state. The URL has the subdomain, an arbitrarily deep nested namespace. The URL has a path the second arbitrarily nested namespace. The method a field which changes the meaning of other fields. The get parameters from the URL and the post payload with arbitrary contents. Just for good measure, the headers are a string to string key value map that has been used in a plethora of ways. Many of the headers are effectively their own small programming languages. It is a miracle that this stuff works at all never the less securely.
So, the WAF has the simple task of looking at this crazy data structure and deciding if this data will harm the application that it is protecting. This gives us a remarkable power if you have been running active scanners. The ability to take the output from that scan an API-endpoint field and data that caused a venerable and block traffic on those conditions.
The real power from a WAF comes from when you combine the data from many WAFs across the web. The WAF can never block all attacks but if we are monitoring the campaigns that are ongoing across the internet, by the time it reaches your servers the signature has been detected elsewhere on the web and your servers can ignore the traffic from that campaign.
The speed and attack centric nature of the WAF make it a powerful tool in the quiver of anyone charged with the protection of a web application. It does, however, have its limitations. Unlike the taint tracking and static analysis, the WAF has no idea what the application is doing or why. It can block on things that look like a SQL injection but what if my app is a database of exploits? It should be possible to make such an app but the WAF will think it is being attacked.
RASP
“The best material model of a cat is another, or preferably the same, cat.“
A. Rosenblueth, Philosophy of Science, 1945
The next step beyond the WAF is the RASP Runtime Application Self-protection. By hooking into the application itself, we see not just the traffic from the web like the WAF but we see what the app did in response. The WAF can guess that !!python/object/apply:os.system [“curl”] is an attempt to execute an OS command but a RASP can see that a call to os.system was attempted. The WAF reacts to what looks bad, the RASP reacts to what is bad. In this way, we can set rules that are stricter. eg.
my.site.com/about never gets to run OS command and never gets to read the database. It is only allowed to increment the view count in memcached. If you want to move from a set of signatures to a set of permissions. You need visibility into the app. We cannot do this from the outside looking in. Each API endpoint has a responsibility and should receive only privileges commensurate with those responsibilities.
With the network firewall, we started with all ports open and only blocked a port once there was a known attack that used the port. Now we only open the ports we need. The database only accepts connections from the IP’s of our web servers and on the ports we set. This reduced the attack service and made our data far safer. RASP enables us to move from a blacklist model to a whitelist model in the application layer.
As an added benefit of using the RASP in conjunction with active scanners is we now have back the transparency we lost by black box probes. When the scanners manage to execute a command, we can catch that with the RASP and grab a stack-trace. Unlike before when we did not know how the scanners were getting through now we get an injection event. This event gives us the information we need to make a WAF rule to block the attack immediately and the underlying trace we need to fix the actual problem.
The RASP feeds off the scanners and feeds the WAF, the static analysis, and the training material. It gives you the visibility that you need in order for your enemy to teach you how to defend yourself.
Client-side protection
The problem of XSS has been fought on the server for years but we are not done yet. With the injection of unexpected content in queries, comments, names, addresses, basically every string the user can effect we take the fight to the client. While progress has been made server side, the browser community has decided to take on the fight. Let me introduce you to CSP Content Security Policy. This is an HTTP header. (Yes, that is correct we added another header to our HTTP traffic with its own small language for the WAFs to have to deal with, oh joy.) This header instructs the browser of the origins that we expect to see interacting with our page. Continuing to use the ad example from my last post, if you know the domain of your ad network, and your analytics collector, then if an attacker succeeds in injecting a script or iframe its src will not be on your list and the content will not be loaded. Inline scripts will be identified by a hash and remote ones by a domain name, a hash, or both. This too acts like a whitelist of the acceptable content for your page. While this will not prevent all injection of content it makes the content that is injected much safer.
CSP has two main roles one of protection and one of transparency. The protection is accomplished by not loading content from untrusted origins. The transparency is accomplished by reporting the scripts that are blocked to a server of your choosing. As I discussed in the RASP section we need to be able to see who is attacking us and how in order to update our rules and stay one step ahead.
This is a powerful tool, but not the limit of what client-side protection can accomplish. We can do even more by loading our own custom JavaScript. Reflecting on the DOM, we can learn a lot about what nodes are present. This is how we will go beyond what the server sees it sent to the client to the page the client sees. For example, if a client had an ad stealing malware that replaced all the ads on our site with iframes from their ad network, the server could not detect this. A JavaScript loaded in the HTML page, on the other hand, could see that the nodes had been replaced in the DOM and report the error to the server.
Conclusions
If you’ve read both posts “Why is Cross Site Scripting So Hard?” and now this one, we have looked at the browser’s security model and why the same origin policy can make the web safe for so many different activities. We learned how user generated content can inject unwanted scripting into the page. We looked at how sanitizing that user data with escape functions can prevent these attackers from harming us. Then, we walked through some of the ways we mitigate the risks posed by XSS.
In the end, XSS is a hard problem that has no one magic bullet to solve. But we do have ways to protect our users. There is no need to give up hope by taking an all-of-the-above approach. We can make this web safe. Whether this is an early introduction to web application security to you or a refresher on a long-studied topic, I hope you learned something.
– Aaron David Goldman, Senior Security Researcher
|
https://www.rapid7.com/blog/post/2017/08/09/how-to-prevent-xss-attacks/
|
CC-MAIN-2021-43
|
refinedweb
| 2,303
| 71.04
|
import an Excel spreadsheet into an Access database?
-- IE
Hey, IE. Wait! Don’t tell us; let us guess. Just a moment … we’re picking up the vibrations now … the sensation is getting stronger and more distinct … OK, got it: you’d like to know how to import an Excel spreadsheet into an Access database, wouldn’t you? Are we right? That’s what we thought.
Granted, some of you don’t seem too impressed by that. “Big deal,” you say. “Anyone could ‘predict’ what question IE was going to ask; all you have to do is read the question at the start of the column.” Oh ye of little faith. Sure, it’s true that we could have simply read IE’s question ahead of time and then made a “prediction.” However, how do you explain this: in yesterday’s column we predicted that today we would cover importing an Excel spreadsheet into an Access database. It’s true; just take a look at this quote from the April 3rd column:
“Does that mean that we could use a similar script to import data? As a matter of fact it does, and in tomorrow’s column we’ll show you how to do that very thing.”
That’s OK, no need to apologize; we’re used to dealing with skeptics. And for those of you wondering how we were able to make such an uncanny prediction, well, to tell you the truth, we don’t know; it’s just a gift. But don’t worry: the Scripting Guys vow to use this gift only for good, never for evil.
Well, maybe a little evil. But not much.
Of course, throughout the ages seers and psychics have been a dime-a-dozen; does the name Nostradamus ring a bell with anyone? But there’s one thing that separates the Scripting Guys from their fellow prophets and soothsayers: as near as we can tell, Nostradamus never wrote a script that imports an Excel spreadsheet into an Access database. Score one for the Scripting Guys:
Const acImport = 0 Const acSpreadsheetTypeExcel9 = 8 Set objAccess = CreateObject("Access.Application") objAccess.OpenCurrentDatabase "C:\Scripts\Test.mdb" objAccess.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ "Employees", "C:\Scripts\Employees.xls", True
Guess what: we knew you were going to take one look at this and think “Wow; that’s easy.” And you’re right: it is. As you can see, we start out by defining a constant name acImport and setting the value to 0; this tells the script that we want to import data (as opposed to exporting it). We then define a second constant, this one named acSpreadsheetTypeExcel9, and set the value to 8; this tells the script that we’re planning to import an Excel 2003 worksheet. Are there other spreadsheet formats that we can import into Access? You bet there are:
After we define our constants we then use these two lines of code to create an instance of the Access.Application object and open the database C:\Scripts\Test.mdb (something we do by calling the OpenCurrentDatabase method):
Set objAccess = CreateObject("Access.Application") objAccess.OpenCurrentDatabase "C:\Scripts\Test.mdb"
At that point all we have to do is invoke the TransferSpreadsheet method and import the spreadsheet data into the database:
objAccess.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ "Employees", "C:\Scripts\Employees.xls", True
Ah, yes, we had a feeling you were going to ask that; here’s what the parameters passed to the TransferSpreadsheet method represent:
We should also add that it’s important that the data types match as well. If you have a database field named EmployeeID, a field that only accepts numeric data, don’t try importing spreadsheet data that includes non-numeric data (e.g., an employee ID of 1234ABC). That’s not going to work.
Oh, and here’s another thing we should add: there’s actually an optional sixth parameter (following HasFieldNames) that enables you to limit your import to a specified range of data. For example, suppose your spreadsheet has 6 columns of data (columns A through F) and you only want to import the first 25 rows in that spreadsheet. Okey-doke. That means that the range of data to be imported runs from cells A1 through cell F25 (A1:F25 in Excel-speak). In turn, that means you can import just those 25 records by using this command:
objAccess.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ "Employees", "C:\Scripts\Employees.xls", True, "A1:F25"
We’ve already thought of that: suppose you would like to import the spreadsheet into a brand-new database (as opposed to importing the data into an existing database). Is that possible? Not if you’re Nostradamus. But if you’re the Scripting Guys, well, then it’s a different story:
Const acImport = 0 Const acSpreadsheetTypeExcel9 = 8 Set objAccess = CreateObject("Access.Application") objAccess.NewCurrentDatabase "C:\Scripts\New.mdb" objAccess.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _ "Employees", "C:\Scripts\Employees.xls", True
You’re right: this does look a lot like the first script we showed you, doesn’t it? In fact, there’s only one difference: this time we don’t use the OpenCurrentDatabase method in order to open an existing database file. Instead, we use the NewCurrentDatabase method to create a brand-new database (C:\Scripts\New.mdb):
objAccess.NewCurrentDatabase "C:\Scripts\New.mdb"
At this point in time it’s hard to believe that anyone could possibly doubt the Scripting Guys and their power of clairvoyance. Just in case, however, we might note that the Scripting Guy who writes this column won the annual NCAA college basketball challenge by, among other things, correctly foreseeing a Florida victory over Ohio State. (Sorry; over the Ohio State University. Sheesh.) Furthermore, he already has a prediction for next year’s championship game: the University of Washington 78, North Carolina 65. Remember, you read it here first.
Unless it turns out that we’re wrong. In that case, you didn’t read it here at all, and we have no idea what you’re talking about.
|
http://www.microsoft.com/technet/scriptcenter/resources/qanda/apr07/hey0404.mspx
|
crawl-002
|
refinedweb
| 1,009
| 63.7
|
Projects
- Starting Out
- The Directory Structure
- Naming And Finding Projects
- Running Project Tasks
- Setting Project Properties
- Resolving Paths
- Defining The Project
- Writing Your Own Tasks
Starting Out
In Java, most projects are built the same way: compile source code, run test cases, package the code, release it. Rinse, repeat.
Feed it a project definition, and Buildr will set up all these tasks for you. The only thing you need to do is specify the parts that are specific to your project, like the classpath dependencies, whether you’re packaging a JAR or a WAR, etc.
The remainder of this guide deals with what it takes to build a project. But first, let’s pick up a sample project to work with. We’ll call it killer-app:
require 'buildr' VERSION_NUMBER = '1.0' AXIS2 = 'org.apache.axis2:axis2:jar:1.2' AXIOM = group('axiom-api', 'axiom-impl', 'axiom-dom', :under=>'org.apache.ws.commons.axiom', :version=>'1.2.4') AXIS_OF_WS = [AXIOM, AXIS2] OPENJPA = ['org.apache.openjpa:openjpa-all:jar:0.9.7', 'net.sourceforge.serp:serp:jar:1.12.0'] repositories.remote << '' desc 'Code. Build. ??? Profit!' define 'killer-app' do project.version = VERSION_NUMBER project.group = 'acme' manifest['Copyright'] = 'Acme Inc (C) 2007' compile.options.target = '1.5' desc 'Abstract classes and interfaces' define 'teh-api' do package :jar end desc 'All those implementation details' define 'teh-impl' do compile.with AXIS_OF_WS, OPENJPA compile { open_jpa_enhance } package :jar end desc 'What our users see' define 'la-web' do test.using AXIS_OF_WS package(:war).with :libs=>projects('teh-api', 'teh-impl') end javadoc projects package :javadoc end
A project definition requires four pieces of information: the project name, group identifier, version number and base directory. The project name … do we need to explain why its necessary? The group identifier and version number are used for packaging and deployment, we’ll talk more about that in the Packaging section. The base directory lets you find files inside the project.
Everything else depends on what that particular project is building. And it
all goes inside the project definition block, the piece of code that comes
between
define <name> .. do and
end.
The Directory Structure
Buildr follows a convention we picked from years of working with Apache projects.
Java projects are laid out so the source files are in the
src/main/java
directory and compile into the
target/classes directory. Resource files go
in the
src/main/resources directory, also copied over to
target/classes.
Likewise, unit tests come from
src/test/java and
src/test/resources, and
end life in
target/test/classes.
WAR packages pick up additional files from the aptly named
src/main/webapp.
And most stuff, including generated source files are parked under the
target
directory. Test cases and such may generate reports in the, you guessed it,
reports directory.
Other languages will use different directories, but following the same general
conventions. For example, Scala code compiles from the
src/main/scala
directory, RSpec tests are found in the
src/test/rspec directory, and Flash
will compile to
target/flash. Throughout this document we will show examples
using mostly Java, but you can imagine how this pattern applies to other
languages.
When projects grow big, you split them into smaller projects by nesting projects inside each other. Each sub-project has a sub-directory under the parent project and follows the same internal directory structure. You can, of course, change all of that to suite your needs, but if you follow these conventions, Buildr will figure all the paths for you.
Going back to the example above, the directory structure looks like this:
./buildfile <- Top of the world (killer-app) | |__ teh-api | |__ src | | |__ main | | |__ java <- Java sources | | | |__ target <- JAR goes here | | |__ classes <- Generated bytecode | |__ reports <- From test cases, | |__ junit <- like JUnit | |__ teh-impl | |__ src | | |__ main | | | |__ java | | | |__ resources | | |__ test | | |__ java | | | |__ target | | |__ classes | |__ reports | |__ la-web | |__ src | | |__ main | | |__ webapp <- Webapp files | | | |__ target <- The WAR goes here | |__ reports |__ junit <- For all test cases
Notice the
buildfile at the top. That’s your project build script, the one
Buildr runs.
When you run the
buildr command, it picks up the
buildfile (which here
we’ll just call Buildfile) from the current directory, or if not there, from
the closest parent directory. So you can run
buildr from any directory
inside your project, and it will always pick up the same Buildfile. That also
happens to be the base directory for the top project. If you have any
sub-projects, Buildr assumes they reflect sub-directories under their parent.
And yes, you can have two top projects in the same Buildfile. For example, you can use that to have one project that groups all the application modules (JARs, WARs, etc) and another project that groups all the distribution packages (binary, sources, javadocs).
When you start with a new project you won’t see the
target or
reports
directories. Buildr creates these when it needs to. Just know that they’re
there.
Naming And Finding Projects
Each project has a given name, the first argument you pass when calling
define. The project name is just a string, but we advise to stay clear of
colon (
:) and slashes (
/ and
\), which could conflict with other task and
file names. Also, avoid using common Buildr task names, don’t pick
compile
or
build for your project name.
Since each project knows its parent project, child projects and siblings, you
can reference them from within the project using just the given name. In other
cases, you’ll need to use the full name. The full name is just
parent:child.
So if you wanted to refer to teh-impl, you could do so with either
project('killer-app:teh-impl') or
project('killer-app').project('teh-impl').
The
project method is convenient when you have a dependency from one project
to another, e.g. using the other project in the classpath, or accessing one of
its source files. Call it with a project name and it will return that object
or raise an error. You can also call it with no arguments and it will return
the project itself. It’s syntactic sugar that’s useful when accessing project
properties.
The
projects method takes a list of names and returns a list of projects. If
you call it with no arguments on a project, it returns all its sub-projects.
If you call it with no argument in any other context, it returns all the
projects defined so far.
Let’s illustrate this with a few examples:
puts projects.inspect => [project("killer-app"), project("killer-app:teh-api") ... ] puts project('killer-app').projects.inspect => [project("killer-app:teh-api"), project("killer-app:teh-impl") ... ] puts project('teh-api') => No such project teh-api puts project('killer-app:teh-api').inspect => project("killer-app:teh-api") puts project('killer-app').project('teh-api').inspect => project("killer-app:teh-api")
To see a list of all projects defined in your Buildfile:
$ buildr help:projects
Running Project Tasks
Most times, you run tasks like
build or
package that operate on the current
project and recursively on its sub-projects. The “current project” is the one
that uses the current working directory. So if you’re in the
la-web/src
directory looking at source files, la-web is the current project. For
example:
# build killer-app and all its sub-projects $ buildr build # switch to and test only teh-impl $ cd teh-impl $ buildr test # switch to and package only la-web $ cd ../la-web $ buildr package
You can use the project’s full name to invoke one of its tasks directly, and it doesn’t matter which directory you’re in. For example:
# build killer-app and all its sub-projects $ buildr killer-app:build # test only teh-impl $ buildr killer-app:teh-impl:test # package only la-web $ buildr killer-app:la-web:package
Buildr provides the following tasks that you can run on the current project, or on a specific project by prefixing them with the project’s full name:
clean # Clean files generated during a build compile # Compile all projects build # Build the project upload # Upload packages created by the project install # Install packages created by the project javadoc # Create the Javadocs for this project package # Create packages test # Run all test cases uninstall # Remove previously installed packages
To see a list of all the tasks provided by Buildr:
$ buildr help:tasks
Setting Project Properties
We mentioned the group identifier, version number and base directory. These are project properties. There are a few more properties we’ll cover later on.
There are two ways to set project properties. You can pass them as a hash when
you call
define, or use accessors to set them on the project directly. For
example:
define 'silly', :version=>'1.0' do project.group = 'acme' end puts project('silly').version => 1.0 puts project('silly').group => acme
Project properties are inherited. You can specify them once in the parent project, and they’ll have the same value in all its sub-projects. In the example, we only specify the version number once, for use in all sub-projects.
Resolving Paths
You can run
buildr from any directory in your project. To keep tasks
consistent and happy, it switches over to the Buildfile directory and executes
all the tasks from there, before returning back to your working directory.
Your tasks can all rely on relative paths that start from the same directory as
the Buildfile.
But in practice, you’ll want to use the
path_to method. This method
calculates a path relative to the project, a better way if you ever need to
refactor your code, say turn a ad hoc task into a function you reuse.
The
path_to method takes an array of strings and concatenates them into a
path. Absolute paths are returned as they are, relative paths are expanded
relative to the project’s base directory. Slashes, if you don’t already know,
work very well on both Windows, Linux and OS/X. And as a shortcut, you can use
_.
For example:
# Relative to the current project path_to('src', 'main', 'java') # Exactly the same thing _('src/main/java') # Relative to the teh-impl project project('teh-impl')._('src/main/java')
Defining The Project
The project definition itself gives you a lot of pre-canned tasks to start with, but that’s not enough to build a project. You need to specify what gets built and how, which dependencies to use, the packages you want to create and so forth. You can configure existing tasks, extend them to do additional work, and create new tasks. All that magic happens inside the project definition block.
Since the project definition executes each time you run Buildr, you don’t want to perform any work directly inside the project definition block. Rather, you want to use it to specify how different build task work when you invoke them. Here’s an example to illustrate the point:
define 'silly' do puts 'Running buildr' build do puts 'Building silly' end end
Each time you run Buildr, it will execute the project definition and print out
“Running buildr”. We also extend the
build task, and whenever we run it, it
will print “Building silly”. Incidentally,
build is the default task, so if
you run Buildr with no arguments, it will print both messages while executing
the build. If you run Buildr with a different task, say
clean, it will only
print the first message.
The
define method gathers the project definition, but does not execute it
immediately. It executes the project definition the first time you reference
that project, directly or indirectly, for example, by calling
project with
that project’s name, or calling
projects to return a list of all projects.
Executing a project definition will also execute all its sub-projects’
definitions. And, of course, all project definitions are executed once the
Buildfile loads, so Buildr can determine how to execute each of the build
tasks.
If this sounds a bit complex, don’t worry. In reality, it does the right thing. A simple rule to remember is that each project definition is executed before you need it, lazy evaluation of sort. The reason we do that? So you can write projects that depend on each other without worrying about their order.
In our example, the la-web project depends on packages created by the teh-api and teh-impl projects, the later requiring teh-api to compile. That example is simple enough that we ended up specifying the projects in order of dependency. But you don’t always want to do that. For large projects, you may want to group sub-projects by logical units, or sort them alphabetically for easier editing.
One project can reference another ahead of its definition. If Buildr detects a cyclic dependency, it will let you know.
In this example we define one project in terms of another, using the same dependencies, so we only need to specify them once:
define 'bar' do compile.with project('foo').compile.dependencies end define 'foo' do compile.with ..lots of stuff.. end
One last thing to remember. Actually three, but they all go hand in hand.
Self is project Each of these project definition blocks executes in the
context of that project, just as if it was a method defined on the project. So
when you call the
compile method, you’re essentially calling that method on
the current project:
compile,
self.compile and
project.compile are all
the same.
Blocks are closures The project definition is also a closure, which can reference variables from enclosing scopes. You can use that, for example, to define constants, variables and even functions in your Buildfile, and reference them from your project definition. As you’ll see later on, in the Artifacts section, it will save you a lot of work.
Projects are namespaces While executing the project definition, Buildr
switches the namespace to the project name. If you define the task “do-this”
inside the teh-impl project, the actual task name is
“killer-app:teh-impl:do-this”. Likewise, the
compile task is actually
“killer-app:teh-impl:compile”.
From outside the project you can reference a task by its full name, either
task('foo:do') or
project('foo').task('do'). If you need to reference a
task defined outside the project from within the project, prefix it with
“rake:”, for example,
task('rake:globally-defined').
Writing Your Own Tasks
Of all the features Buildr provide, it doesn’t have a task for making coffee. Yet. If you need to write your own tasks, you get all the power of Rake: you can use regular tasks, file tasks, task rules and even write your own custom task classes. Check out the Rake documentation for more information.
We mentioned projects as namespaces before. When you call
task on a project,
it finds or defines the task using the project namespace. So given a project
object,
task('do-this') will return it’s “do-this” task. If you lookup the
source code for the
compile method, you’ll find that it’s little more than a
shortcut for
task('compile').
Another shortcut is the
file method. When you call
file on a project,
Buildr uses the
path_to method to expand relative paths using the project’s
base directory. If you call
file('src') on teh-impl, it will return you a
file task that points at the
teh-impl/src directory.
In the current implementation projects are also created as tasks, although you don’t invoke these tasks directly. That’s the reason for not using a project name that conflicts with an existing task name. If you do that, you’ll find quick enough, as the task will execute each time you run Buildr.
So now that you know everything about projects and tasks, let’s go and build some code.
|
http://incubator.apache.org/buildr/projects.html
|
crawl-001
|
refinedweb
| 2,681
| 63.7
|
Hi guys,
I am working on project where I am using an arduino mega and a bluetooth module to send a simple text to the andriod phone. I can build the program but I cant get to send the signal over to the phone. The program structure is such , Once the led is high , the buzzer goes on and the signal is sent out to the HTC phone. Can somebody with a kind soul please help me with my program below.
best regards
nash
#include <MeetAndroid.h>
MeetAndroid meetAndroid;
int buzzer = 48; // Buzzer connected to digital pin 48
int ledPin = 50; // the number of the LED pin 50
// variables will change:
int ledState = 0; // variable for reading the led status
void setup()
{
pinMode(ledPin,INPUT); // pin 13 led as OUTPUT
pinMode(buzzer, OUTPUT); // pin 48 buzzer as OUTPUT
Serial.begin(115200); // start serial communication at 115200bps
}
void loop()
{
ledState = digitalRead(ledPin);
if( ledState == HIGH ) // if ‘HIGH’ was received
{
digitalWrite(buzzer, HIGH); // turn ON the buzzer
delay(1000);
Serial.print(“Door is opened\r\n”); // print the message when the Mega received input from Serial1
delay(5000); // delay 5 seconds
meetAndroid.receive(); // read input pin and send result to Android
meetAndroid.send(digitalRead(ledPin)); // add a little delay otherwise the phone is pretty busy
delay(1000);
}
else
{
digitalWrite(buzzer, LOW); // otherwise turn it OFF
delay(1000); // wait 1000ms for next reading
}
}
|
https://forum.arduino.cc/t/arduino-communication-with-a-android/21855
|
CC-MAIN-2021-39
|
refinedweb
| 230
| 58.72
|
go
/
/
fd679df69f9cbbb8e8be61c4700dfbe8d0aed06d
/
.
/
content
/
module-compatibility.article
blob: 9ade469affdde1746bf8b3766f4fd5a27eba0701 [
file
] [
log
] [
blame
]
# Keeping Your Modules Compatible
7 Jul 2020
Tags: tools, versioning
Summary: How to keep your modules compatible with prior minor/patch versions.
Jean de Klerk
Jonathan Amsterdam
## Introduction
This post is part 5 in a series.
- Part 1 — [Using Go Modules](/using-go-modules)
- Part 2 — [Migrating To Go Modules](/migrating-to-go-modules)
- Part 3 — [Publishing Go Modules](/publishing-go-modules)
- Part 4 — [Go Modules: v2 and Beyond](/v2-go-modules)
- **Part 5 — Keeping Your Modules Compatible** (this post)
Your modules will evolve over time as you add new features, change behaviors, and reconsider parts of the module's public surface. As discussed in [Go Modules: v2 and Beyond](/v2-go-modules), breaking changes to a v1+ module must happen as part of a major version bump (or by adopting a new module path).
However, releasing a new major version is hard on your users. They have to find the new version, learn a new API, and change their code. And some users may never update, meaning you have to maintain two versions for your code forever. So it is usually better to change your existing package in a compatible way.
In this post, we'll explore some techniques for introducing non-breaking changes. The common theme is: add, don’t change or remove. We’ll also talk about how to design your API for compatibility from the outset.
## Adding to a function
Often, breaking changes come in the form of new arguments to a function. We’ll describe some ways to deal with this sort of change, but first let’s look at a technique that doesn’t work.
When adding new arguments with sensible defaults, it’s tempting to add them as a variadic parameter. To extend the function
```
func Run(name string)
```
with an additional `size` argument which defaults to zero, one might propose
```
func Run(name string, size ...int)
```
on the grounds that all existing call sites will continue to work. While that is true, other uses of `Run` could break, like this one:
```
package mypkg
var runner func(string) = yourpkg.Run
```
The original `Run` function works here because its type is `func(string)`, but the new `Run` function’s type is `func(string, ...int)`, so the assignment fails at compile time.
This example illustrates that call compatibility is not enough for backward compatibility. There is, in fact, no backward-compatible change you can make to a function’s signature.
Instead of changing a function’s signature, add a new function. As an example, after the `context` package was introduced, it became common practice to pass a `context.Context` as the first argument to a function. However, stable APIs could not change an exported function to accept a `context.Context` because it would break all uses of that function.
Instead, new functions were added. For example, the `database/sql` package's `Query` method’s signature was (and still is)
```
func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
```
When the `context` package was created, the Go team added a new method to `database/sql`:
```
func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)
```
To avoid copying code, the old method calls the new one:
```
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
return db.QueryContext(context.Background(), query, args...)
}
```
Adding a method allows users to migrate to the new API at their own pace. Since the methods read similarly and sort together, and `Context` is in the name of the new method, this extension of the `database/sql` API did not degrade readability or comprehension of the package.
If you anticipate that a function may need more arguments in the future, you can plan ahead by making optional arguments a part of the function’s signature. The simplest way to do that is to add a single struct argument, as the [crypto/tls.Dial]() function does:
```
func Dial(network, addr string, config *Config) (*Conn, error)
```
The TLS handshake conducted by `Dial` requires a network and address, but it has many other parameters with reasonable defaults. Passing a `nil` for `config` uses those defaults; passing a `Config` struct with some fields set will override the defaults for those fields. In the future, adding a new TLS configuration parameter only requires a new field on the `Config` struct, a change that is backward-compatible (almost always—see "Maintaining struct compatibility" below).
Sometimes the techniques of adding a new function and adding options can be combined by making the options struct a method receiver. Consider the evolution of the `net` package’s ability to listen at a network address. Prior to Go 1.11, the `net` package provided only a `Listen` function with the signature
```
func Listen(network, address string) (Listener, error)
```
For Go 1.11, two features were added to `net` listening: passing a context, and allowing the caller to provide a “control function” to adjust the raw connection after creation but before binding. The result could have been a new function that took a context, network, address and control function. Instead, the package authors added a [`ListenConfig`]() struct in anticipation that more options might be needed someday. And rather than define a new top-level function with a cumbersome name, they added a `Listen` method to `ListenConfig`:
```
type ListenConfig struct {
Control func(network, address string, c syscall.RawConn) error
}
func (*ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)
```
Another way to provide new options in the future is the “Option types” pattern, where options are passed as variadic arguments, and each option is a function that changes the state of the value being constructed. They are described in more detail by Rob Pike's post [Self-referential functions and the design of options](). One widely used example is [google.golang.org/grpc]()'s [DialOption]().
Option types fulfill the same role as struct options in function arguments: they are an extensible way to pass behavior-modifying configuration. Deciding which to choose is largely a matter of style. Consider this simple usage of gRPC's `DialOption` option type:
```
grpc.Dial("some-target",
grpc.WithAuthority("some-authority"),
grpc.WithMaxDelay(time.Second),
grpc.WithBlock())
```
This could also have been implemented as a struct option:
```
notgrpc.Dial("some-target", ¬grpc.Options{
Authority: "some-authority",
MaxDelay: time.Minute,
Block: true,
})
```
Functional options have some downsides: they require writing the package name before the option for each call; they increase the size of the package namespace; and it's unclear what the behavior should be if the same option is provided twice. On the other hand, functions which take option structs require a parameter which might almost always be `nil`, which some find unattractive. And when a type’s zero value has a valid meaning, it is clumsy to specify that the option should have its default value, typically requiring a pointer or an additional boolean field.
Either one is a reasonable choice for ensuring future extensibility of your module's public API.
## Working with interfaces
Sometimes, new features require changes to publicly-exposed interfaces: for example, an interface needs to be extended with new methods. Directly adding to an interface is a breaking change, though—how, then, can we support new methods on a publicly-exposed interface?
The basic idea is to define a new interface with the new method, and then wherever the old interface is used, dynamically check whether the provided type is the older type or the newer type.
Let's illustrate this with an example from the [`archive/tar`]() package. [`tar.NewReader`]() accepts an `io.Reader`, but over time the Go team realized that it would be more efficient to skip from one file header to the next if you could call [`Seek`](). But, they could not add a `Seek` method to `io.Reader`: that would break all implementers of `io.Reader`.
Another ruled-out option was to change `tar.NewReader` to accept [`io.ReadSeeker`]() rather than `io.Reader`, since it supports both `io.Reader` methods and `Seek` (by way of `io.Seeker`). But, as we saw above, changing a function signature is also a breaking change.
So, they decided to keep `tar.NewReader` signature unchanged, but type check for (and support) `io.Seeker` in `tar.Reader` methods:
```
package tar
type Reader struct {
r io.Reader
}
func NewReader(r io.Reader) *Reader {
return &Reader{r: r}
}
func (r *Reader) Read(b []byte) (int, error) {
if rs, ok := r.r.(io.Seeker); ok {
// Use more efficient rs.Seek.
}
// Use less efficient r.r.Read.
}
```
(See [reader.go]() for the actual code.)
When you run into a case where you want to add a method to an existing interface, you may be able to follow this strategy. Start by creating a new interface with your new method, or identify an existing interface with the new method. Next, identify the relevant functions that need to support it, type check for the second interface, and add code that uses it.
This strategy only works when the old interface without the new method can still be supported, limiting the future extensibility of your module.
Where possible, it is better to avoid this class of problem entirely. When designing constructors, for example, prefer to return concrete types. Working with concrete types allows you to add methods in the future without breaking users, unlike interfaces. That property allows your module to be extended more easily in the future.
Tip: if you do need to use an interface but don't intend for users to implement it, you can add an unexported method. This prevents types defined outside your package from satisfying your interface without embedding, freeing you to add methods later without breaking user implementations. For example, see [`testing.TB`'s `private()` function]().
```
// TB is the interface common to T and B.
type TB interface {
Error(args ...interface{})
Errorf(format string, args ...interface{})
// ...
// A private method to prevent users implementing the
// interface and so future additions to it will not
// violate Go 1 compatibility.
private()
}
```
This topic is also explored in more detail in Jonathan Amsterdam's "Detecting Incompatible API Changes" talk ([video](), [slides]()).
## Add configuration methods
So far we've talked about overt breaking changes, where changing a type or a function would cause users' code to stop compiling. However, behavior changes can also break users, even if user code continues to compile. For example, many users expect [`json.Decoder`]() to ignore fields in the JSON that are not in the argument struct. When the Go team wanted to return an error in that case, they had to be careful. Doing so without an opt-in mechanism would mean that the many users relying on those methods might start receiving errors where they hadn’t before.
So, rather than changing the behavior for all users, they added a configuration method to the `Decoder` struct: [`Decoder.DisallowUnknownFields`](). Calling this method opts a user in to the new behavior, but not doing so preserves the old behavior for existing users.
## Maintaining struct compatibility
We saw above that any change to a function’s signature is a breaking change. The situation is much better with structs. If you have an exported struct type, you can almost always add a field or remove an unexported field without breaking compatibility. When adding a field, make sure that its zero value is meaningful and preserves the old behavior, so that existing code that doesn’t set the field continues to work.
Recall that the authors of the `net` package added `ListenConfig` in Go 1.11 because they thought more options might be forthcoming. Turns out they were right. In Go 1.13, the [`KeepAlive` field]() was added to allow for disabling keep-alive or changing its period. The default value of zero preserves the original behavior of enabling keep-alive with a default period.
There is one subtle way a new field can break user code unexpectedly. If all the field types in a struct are comparable—meaning values of those types can be compared with `==` and `!=` and used as a map key—then the overall struct type is comparable too. In this case, adding a new field of uncomparable type will make the overall struct type non-comparable, breaking any code that compares values of that struct type.
To keep a struct comparable, don’t add non-comparable fields to it. You can write a test for that, or rely on the upcoming [gorelease]() tool to catch it.
To prevent comparison in the first place, make sure the struct has a non-comparable field. It may have one already—no slice, map or function type is comparable—but if not, one can be added like so:
```
type Point struct {
_ [0]func()
X int
Y int
}
```
The `func()` type is not comparable, and the zero-length array takes up no space. We can define a type to clarify our intent:
```
type doNotCompare [0]func()
type Point struct {
doNotCompare
X int
Y int
}
```
Should you use `doNotCompare` in your structs? If you’ve defined the struct to be used as a pointer—that is, it has pointer methods and perhaps a `NewXXX` constructor function that returns a pointer—then adding a `doNotCompare` field is probably overkill. Users of a pointer type understand that each value of the type is distinct: that if they want to compare two values, they should compare the pointers.
If you are defining a struct intended to be used as a value directly, like our `Point` example, then quite often you want it to be comparable. In the uncommon case that you have a value struct that you don’t want compared, then adding a `doNotCompare` field will give you the freedom to change the struct later without having to worry about breaking comparisons. On the downside, the type won’t be usable as a map key.
## Conclusion
When planning an API from scratch, consider carefully how extensible the API will be to new changes in the future. And when you do need to add new features, remember the rule: add, don't change or remove, keeping in mind the exceptions—interfaces, function arguments, and return values can't be added in backwards-compatible ways.
If you need to dramatically change an API, or if an API begins to lose its focus as more features are added, then it may be time for a new major version. But most of the time, making a backwards-compatible change is easy and avoids causing pain for your users.
|
https://go.googlesource.com/blog/+/fd679df69f9cbbb8e8be61c4700dfbe8d0aed06d/content/module-compatibility.article
|
CC-MAIN-2021-17
|
refinedweb
| 2,420
| 63.19
|
This article provides a workaround for multiple models in a single view in MVC.
The following are the methods that help us to get all the teachers and students.
Required output
ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime. Using this ExpandoObject, we can create a new object and can add our list of teachers and students into it as a property. We can pass this dynamically created object to the view and render list of the teacher and student. Controller Code
We can define our model as dynamic (not a strongly typed model) using the @model dynamic keyword.
View Code
Controller code
View code
View Code
RenderTeacher.cshtml
RenderStudent.cshtml
View All
|
https://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/
|
CC-MAIN-2019-22
|
refinedweb
| 136
| 59.3
|
I have been working on a horizontal FlatList in React Native. The idea is, a user can remove the item by clicking on the item. So once the item is removed, I need to :
- Remove the item from the list with a nice opacity animation
- At the same time, I need to fill up space with the next items sliding in to fill it up properly.
At first, I was trying it out with react native Animated library but it was getting messier and I could not achieve the effects that I wanted. However, with LayoutAnimation from react-native, this can be done easily. Let’s start then. First, we will put the initial set up for our horizontal FlatList.
const { height, width } = Dimensions.get("window"); const dummyData = [ { id: 1, name: "orange card", color: "orange", }, { id: 2, name: "red card", color: "red", }, { id: 3, name: "green card", color: "green", }, { id: 4, name: "blue card", color: "blue", }, { id: 5, name: "cyan card", color: "cyan", }, ]; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", paddingTop: 120, backgroundColor: "#ecf0f1", padding: 8, }, flatList: { paddingHorizontal: 16, paddingVertical: 16, }, cardContainer: { height: 100, width: width * 0.5, marginRight: 8, }, card: { height: 100, width: width * 0.5, borderRadius: 12, padding: 10, }, text: { color: "white", fontWeight: 'bold' } }); export default function App() { const [data, setData] = React.useState(dummyData); return ( <View style={styles.container}> <FlatList showsHorizontalScrollIndicator={false} contentContainerStyle={styles.flatList} horizontal={true} data={data} keyExtractor={(item) => item.id.toString()} renderItem={({ item }) => { return ( <TouchableOpacity style={styles.cardContainer} onPress={() => removeItem(item.id)} > <Card style={[styles.card, {backgroundColor: item.color}]}> <Text style={styles.text}>{item.name}</Text> </Card> </TouchableOpacity> ); }} /> </View> ); }
With this, we get the following output.
Now it is time for removing the item from the FlatList, we can just pass the id of the item to our FlatList and remove the items that match the id. Like so:
const removeItem = (id) => { let arr = data.filter(function(item) { return item.id !== id }) setData(arr); };
if we click our item, the items will be removed from the FlatList but without any animation. This will like odd. The output will be like the following -
Okay, now let's start the animation. With LayoutAnimation we can easily create a layout config that will have the effect.
const layoutAnimConfig = { duration: 300, update: { type: LayoutAnimation.Types.easeInEaseOut, }, delete: { duration: 100, type: LayoutAnimation.Types.easeInEaseOut, property: LayoutAnimation.Properties.opacity, }, }; const removeItem = (id) => { let arr = data.filter(function(item) { return item.id !== id }) setData(arr); // after removing the item, we start animation LayoutAnimation.configureNext(layoutAnimConfig) };
If we check the config, we can see the animation that we are doing while deleting the item from the list. The type is easeInEaseOut and the property is opacity. So let us see the final result with the LayoutAnimation effect.
One last important thing to note that, ensure your key extractor returns a unique key for each item. Do not return index.toString() in your keyExtractor function of the FlatList. Otherwise, the animation will not work. I was stuck with this for quite a long time. :D
You can check out the full demo here
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/saadbashar/remove-item-with-animation-in-a-horizontal-flatlist-in-react-native-o26
|
CC-MAIN-2021-17
|
refinedweb
| 513
| 60.61
|
creating>
creating browse button - Java Beginners
creating browse button how can we create a browse button along... ActionListener {
JButton button;
JTextField field;
public BrowsePath () {
this.setLayout(null);
button = new JButton("browse
browse image
browse image how to browse the image in image box by browse button and save image in database by save button by swing
import java.sql.... img;
JTextField text=new JTextField(20);
JButton browse,save;
JPanel p=new
Browse Button Enlarge Field - Development process
Browse Button Enlarge Field How can I enlarge the browse text field... the browse button and selecting my document, only about 20 characters....
Set the "size" to enlarge the browse button.
For any more problem
how to
struts - Struts
struts How to use back button in struts
Browse an image
Browse an image hi................
i want to browse an image from... text=new JTextField(20);
JButton browse,save;
JPanel p=new JPanel(new... UploadImage() {
browse = new JButton("Upload");
save = new JButton("Save
struts - Struts
of a struts application Hi friend,
Code to help in solving the problem :
In the below code having two submit button's its values are different.So,
it can be handle different submit button :
class MyAction extends
Struts - Struts
used in a struts aplication.
these are the conditions
1. when u entered into this page the NEXT BUTTON must disabled
2. if u enter any text in the TextBOX, then the NEXT BUTTON must ENABLE
for this i used javascript add save,discard,& cancel button in a message box - Struts
how to add save,discard,& cancel button in a message box how to add save,discard,& cancel button in a message box
how to read data from excel file through browse and insert into oracle database using jsp or oracle???
a browse button which can upload a excelfile and after uploading the data should...how to read data from excel file through browse and insert into oracle database using jsp or oracle??? sir.. i have number of excel sheets
Button How to use image for button in JSF
browse a file with java - Development process
browse a file with java I want to count the number of white line and comment line in a file type with sql with java... more the one action button in the form using Java script.
please give
Struts File Upload and Save
Struts File Upload and Save
... regarding "Struts file
upload example". It does not contain any... directory of server.
In this tutorial you will learn how to use Struts
How to show next question from database on the click of next button..(Struts & Hibernate)
How to show next question from database on the click of next button..(Struts....
Problem.: When m clicking my next button it is not showing another question...;l.com
How to show next question from database on the click of next button..(Struts & Hibernate)
How to show next question from database on the click of next button..(Struts....
Problem.: When m clicking my next button it is not showing another question.../struts/struts/struts2.2.1/paginationinstruts.html
Java file browse
Java file browse
In this section, you will learn how to browse a file and allows the user to
choose a file.
Description of code
GUI provide File choosers for navigating the file system, and then provide
the utility to choose either
if there is an invalid entry in html:file control then form is not submitting. - Struts
fine in all the cases expect one usecase.
1) click on browse button and select... friend,
Code to fileupload :
Struts File Upload Example... details with source code and visit to :
java - Struts
java when i hit submit button for login page ,,it displays a blank page....
plse slove it... Hi friend,
This is login form code
Insert into database
Reply - Struts
Reply
Thanks For Nice responce Technologies::--JSP
please write the code and send me....when click "add new button" then get the null value...its urgent... Hi
can u explain in details about your project
multiboxes - Struts
are checked but when i click on uncheck it does nothing(The uncheck radio button... in javascript code or in struts bean. Hi friend,
Code to solve
Reply - Struts
then get the value in form click the add new button....while this is not correct
send the mail with attachment - Struts
in struts. when i added the attachemt logic in struts,i am not able to send the mail .
Mail Problem is file path: how to get the file path from the browse("we
Struts 2 File Upload
Struts 2 File Upload
In this section you will learn how to write program in
Struts 2 to upload the file... in any directory on the server machine.
The Struts 2 FileUpload component can
struts imagelink - Ajax
struts imagelink i need one dropdown menu in that i have to select image
AND i need one button when i clicks on that image will be open
Struts 2.0.0
sheet.
Easy cancel button handling
Now struts 2 cancel button...
Struts 2.0.0
The Struts 2.0.0 is the first version of Struts. Struts
2.0 is based on Web works and now its part
How to Use Struts 2 token tag - Struts
How to Use Struts 2 token tag Hi ,
I want to stop re-submiiting the page by pressing F5, or click 'back n press submit' button again, i want to use... page, or do i need to map anything on my struts.xml file ?
I am using struts 2 pass input from radio button to jsp page
how to pass input from radio button to jsp page hi..
the code below... are matched from database. I want to pass the selected value in
Struts Action FormBean
and then retrive data to perform operation in execute() method in
Struts Action
|
http://roseindia.net/tutorialhelp/comment/53940
|
CC-MAIN-2014-42
|
refinedweb
| 970
| 71.14
|
New
Martin Mares , Chris Kasso and I have been working on the Admin Command Framework.
These are some new enhancements that were added to Glassfish 4.0.
o Support for Progress status using Server Sent Events
o Job Management support
Support for Progress status in commands using Server Sent Events.
This section will cover the newly introduced @Progress annotation. We will walk through the basic usages of Progress API.
Next we will see how ServerSentEvents fits in with the Progress API.
Progress API in Glassfish 4.0
Consider some long running commands say start-cluster. It would be useful to be notified about the progress of the command as it is executing.
To facilitate support for Progress status in AdminCommands a new annotation @Progress is added.
Any command which wants to use the Progress status API can be annotated with @Progress
The ProgressStatus object can be obtained from the AdminCommandContext.
The Progress API can be used to specify the total steps for execution. Once the total steps are known the percentage can be computed.
Additionally the ProgressStatus API takes a message that can be added as the command progresses like Installing, Parsing... etc.
As the command is executing, the progress can be updated by specifying the steps and the message to be sent to the client.
@Progress
public class SomeCommand implements AdminCommand {
public void execute(AdminCommandContext context) {
ProgressStatus ps = context.getProgressStatus();
ps.setTotalStepCount(3);
...
..
ps.progress(1, "Parsing files..");
The above snippet shows the @Progress annotation on the command. It also demonstrates how to get the ProgressStatus object from the AdminCommandContext.
It shows how to use the ProgressStatus.progress() method to specify the number of steps taken and a message to be emitted.
Here is the Progress Status API which command developers can read for detailed information....
Using ServerSentEvents to emit progress
Server-Sent Events (SSE) is a technology for providing push notifications from servers to clients once an initial client connection has been established.
For our case of long running commands which emits progress as it executes, the server can continuously sending the progress using Server Sent Events API.
Definition of a ManagedJob
Any command which has progress information in it ie annotated with @Progress or which is run with --detach (See section below) option is known as a ManagedJob. Each job has a job id associated with it.
You can query the status of a ManagedJob using list-jobs command.
How it fits together
1. When a managed job is executed in GlassFish the REST client will open an SSE connection with header Accept: text/event-stream.
2. The command gets executed on a dedicated thread pool which is provided by the JobManager.
3. Once the channel of communication is established all the progress feedback is sent as Server Sent Events and the channel is kept open to keep sending progress as it occurs.
4. The Response is closed when the command finishes execution.
The above figure shows the interaction between the Server and the command which is annotated with @Progress executed by the client.
The progress is sent via SSE and finally the ActionReport is sent once the command finishes execution.
Job Management commands
These are newer commands which are introduced
- detach option to commands
- attach command
- list-jobs command
- configure-managed-jobs
detach option to commands
Any command can be run with --detach option. This will give a job id associated with the command and the job is run in the background.
You can then lookup the job using the list-jobs command. (Similar to the jobs command in Unix)
You can later attach to the job using the attach command with the job id too and see the progress.
attach command
The following image shows a sample command started by the client which emits progress status information.
1. Client 1 starts the sample command which has some progress information
2. The server executes the command and sends the progress to the client using ServerSentEvents.
You can open another terminal for Client 2 and
attach to the same job and see the same progress updates on both the clients.
Fig 1. Multiple clients attaching to get progress via Server Sent Events.
Bboth the terminals Client1 and Client2 are both getting the same set of progress related Server Sent Events at the same time. Even if one client kills using Ctrl C the other will still see the updates.
list-jobs
The list-jobs command can provide information regarding the jobs.
It lists the job id, the name, the time the job was started, the state and the Exitcode.
Here is a sample output of list-jobs command
asadmin list-jobs
NAME JOB ID TIME STATE EXIT CODE USER
sample-command1 1 2013-02-05 14:11:24 COMPLETED SUCCESS admin
You can even run list-jobs with a single job id
asadmin list-jobs 1
NAME JOB ID TIME STATE EXIT CODE USER
sample-command1 1 2013-02-05 14:11:24 COMPLETED SUCCESS admin
Using curl to get the data of the list-jobs
This will get the information of all jobs
curl -vSs -H 'X-Requested-By foo' -X GET
This will get the information of job whose id is 1
curl -vSs -H 'X-Requested-By foo' -X GET
configure-manage-jobs command
The configure-managed-jobs command is used to clean up these ManagedJobs. By default the job retention period is 24 hours. But using this command you can specify how long you want to keep the jobs.
How you can contribute
Download GlassFish 4.0 from and try the newer features.
Java EE 7 tutorial is here
You can file bugs using this link
Provide feedback at users@glassfish.dev.java.net.
- Login or register to post comments
- Printer-friendly version
- bhaktimehta's blog
- 2363 reads
|
https://weblogs.java.net/blog/bhaktimehta/archive/2013/06/13/new-enhancements-admin-command-framework-glassfish-40
|
CC-MAIN-2014-10
|
refinedweb
| 965
| 62.78
|
.
Install Markdown and Pygments
Using latest Mac OS X (Snow Leopard) with Python 2.6.1, I installed Python-Markdown and Pygments:
easy_install ElementTree easy_install Markdown easy_install Pygments
Prepare your blog entry
Asuming you have blog entry written with Markdown syntax which includes some code examples. Make sure the source code snippets are indented with 4 spaces and you specified code language using one of the options. I use the following style to identify language:
:::python
When the language is deduced from shebang like this:
#!/usr/bin/env python
it seems to add line numbering to code which is not what I want (see how to add line numbers below).
Generate blog entry in html
Run the text, in Markdown format, through Python-Markdown to generate
html segment:
import markdown html = markdown.markdown(text,['codehilite'])
If you want the line numbers in code snippet use this line instead:
html = markdown.markdown(text,['codehilite(force_linenos=True)']
This does not generate full html page only a segment that can be pasted to Blogger as html formatted entry.
The option
codehilite turns on CodeHilite extension which uses Pygments to take care of code syntax highlighting.
For convenience it can be wraped into a scrip that reads a
markdown formatted file and generates file with
.html extension, let's call this script
markdown-pygments.py:
# markdown-pygments.py #!/usr/bin/env python import sys import os import markdown def main(args=None): if (args is None or len(args) < 2): print "Error, input file missing, usage:" print " markdown-pygments.py <markdown formatted file>" return markdownInFile = os.path.abspath(args[1]) (dir, file) = os.path.split(markdownInFile) (file, ext) = os.path.splitext(file) markdownOutFile = os.path.join(dir, ".".join([file,'html'])) print "in: ", markdownInFile print "out: ", markdownOutFile with open(markdownInFile, 'r') as f: text = f.read() html = markdown.markdown(text, ['codehilite']) with open(markdownOutFile, 'w') as f: f.write(html) if __name__ == '__main__': main(sys.argv)
You would then generate the html like this:
./markdown-pygments.py post-16-01-2010.txt
It will generate
post-16-01-2010.html in the current directory.
Update Blogger CSS to show syntax highlight
You can link to your external CSS which contains the syntax highlight but I prefer to just update Blogger CSS. If you look at the generated html you will see that the highlighted source code is inside:
<div class="codehilite"> ... source code is here ... </div>
We can dump the CSS to use highlight syntax into a file from Pygments. Tell Pygments that our source code is inside
div.codehilite tag:
pygmentize -S default -f html -a html -a "div.codehilite" > syntax.css
Now
syntax.css contains CSS that can be used with our generated html to add colors to syntax highlight.
To update Blogger CSS, log into Blogger and copy CSS styles into template.
Under
Customize tab select
Edit HTML, find
<b:skin><![CDATA[ element and paste CSS within it, I put it at the end just before
]]></b:skin>:
<b:skin><![CDATA[ ... your CSS goes here ... ]]></b:skin>
Publish Blog Entry
Publish your blog entry by copying the generated html from file into Blogger. The source code within your post should have syntax highlighted in color.
I take a different approach:
But there's a reason why I am landing at this article on your blog. I am still searching for the easiest, most optimal way to blog where embedding and highlighting code is more often than not.
|
http://mybyteofcode.blogspot.com/2010/01/use-markdown-and-pygments-with-blogger.html
|
CC-MAIN-2014-41
|
refinedweb
| 575
| 66.84
|
ecolombres Wrote:Found the addon here but when I'm installing I get "dependencies not meet" error...
I'm running latest nightly on an Atv2. Any idea which other dependencies I need to meet?
Quote:23:28:27 T:147828736 ERROR: Error Type:
23:28:27 T:147828736 ERROR: Error Contents: No module named webviewer
23:28:27 T:147828736 ERROR: Traceback (most recent call last):
File "/var/mobile/Library/Preferences/XBMC/addons/script.forum.browser/default.py", line 5, in
from webviewer import webviewer #@UnresolvedImport
ImportError: No module named webviewer
23:28:27 T:147828736 INFO: -->End of Python script error report<--
ecolombres Wrote:Webviewer installed.
The skin is not working for me, i cant see The background of the forumbrowser, its just not solid.
I tried disabling fanart slideshow, but nothing.
Jeroen Wrote:Nice! You've been keeping busy lately
I'll be sure to check it out
ecolombres Wrote:Jeroen, any news about this update?
Sranshaft Wrote:Jeroen has nothing to do with this mod. If I have time this weekend I'll try to update the skin.
|
http://forum.kodi.tv/showthread.php?pid=1008507%23pid1008507
|
CC-MAIN-2015-22
|
refinedweb
| 181
| 56.45
|
Continue Statement in C++ Example | C++ Continue Statement Program is today’s topic. Continue works in parallel with the break statement. The only difference is that the break statement completely terminates the loop while the continue statement only skips the current iteration and goes to the next iteration. The main aim of the continue statement is to skip the execution of statements inside the loop’s body for the current iteration.
Continue Statement in C++
Content Overview
As the name suggests, the continue statement forces a loop to continue or execute the next iteration.
When the continue statement is executed in a loop, the code inside a loop following the continue statement will be skipped, and the next iteration of the loop will begin.
For example, suppose we want to print numbers from 1 to 50, and we do not want to print 45 so when the loop iteration reaches use 45 we can use a continue statement that will skip the execution of that iteration and will go to the beginning of the next iteration.
Syntax of Continue Statement
continue;
See the following code snippet.
for (int i = 1; i <= 50; i++) { cout << i << endl; if (i == 45) { continue; } }
It will print all the numbers from 1 to 50 except 45.
Flow chart of Continue Statement
Examples of continue statement
Continue statement inside for loop
See the following code in which we are using continue statement with for loop.
#include <iostream> using namespace std; int main() { for (int i = 0; i <= 10; i++) { if (i == 5) { continue; } cout << "i=" << i << endl; } cout << "Missed it?\n Check 5.\n Not there?\n We used continue over there to skip it" << endl; }
See the output.
Q2- Write the program to print the table of 10 but skip the value when it becomes 90 and print the rest of the table.
#include <iostream> using namespace std; int main() { int k; for (int i = 0; i <= 10; i++) { if (k == 80) { k = 0; continue; } k = 0; k = i * 10; cout << "10 x " << i << "=" << k << endl; } cout << "I have skipped 10 x 9 = 90" << endl; }
See the output.
Use of continue statement in While loop
See the following program of continue statement with the while loop.
#include <iostream> using namespace std; int main() { int e = 5; while (e >= 0) { if (e == 4) { e--; continue; } cout << "Value of e: " << e << endl; e--; } return 0; }
See the following output.
Value of e: 5 Value of e: 3 Value of e: 2 Value of e: 1 Value of e: 0
Use of continue in do-While loop
See the following program of continue statement with the do-while loop.
#include <iostream> using namespace std; int main() { int j = 4; do { if (j == 7) { j++; continue; } cout << "j is: " << j << endl; j++; } while (j < 10); return 0; }
See the following output.
j is: 4 j is: 5 j is: 6 j is: 8 j is: 9
C++ Continue Statement with Inner Loop
C++ Continue Statement continues the inner loop only if you use continue statement inside the inner loop. See the following code.
#include <iostream> using namespace std; int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i == 2 && j == 2) { continue; } cout << i << " " << j << "\n"; } } }
See the output.
1 1 1 2 1 3 2 1 2 3 3 1 3 2 3 3
Finally, Continue Statement Tutorial With Example is over.
Recommended Posts
If-else Statements in C++ Example Tutorial
Recursion Program In C++ Tutorial
Exception Handling In C++
|
https://appdividend.com/2019/09/21/continue-statement-in-cpp-example-cpp-continue-statement-program/
|
CC-MAIN-2019-47
|
refinedweb
| 591
| 64.75
|
Hello,
I was wondering about loss function defined with a simple python definition, say for example
def loss(arg): return arg.abs().mean()
What is the right way to make it run on multi gpu ?
My current way would be to wrap it inside a
Module, that can then be wrapped inside a
DataParallel
class module_wrapper(nn.Module): def __init__(self): return def forward(self, arg): return loss(arg) my_parallel_loss = nn.DataParallel(module_wrapper())
I don’t find this piece of code very compact nor readable. Would a
DataParallel for functions like this one (which can be much longer) be a good idea ? At first I thought a decorator could be a good idea, but that would require the creation of a new wrapper module for each call which is probably not what we want.
Thanks !
|
https://discuss.pytorch.org/t/multi-gpu-for-user-defined-functions/28151
|
CC-MAIN-2022-33
|
refinedweb
| 135
| 61.97
|
- 04 Jan 2008 12:24:14 UTC
- Distribution: Text-CSV_XS
- Module version: 0.34
- Source (raw)
- Browse (raw)
- Changes
- How to Contribute
- Issues (2)
- Testers (96 / 0 / 0)
- KwaliteeBus factor: 1
- License: perl_5
- Activity24 month
- Tools
- Download (42.22KB)
- MetaCPAN Explorer
- Permissions
- Permalinks
- This version
- Latest version++ed by:46 non-PAUSE usersand 1 contributors
H.Merijn Brand
- Dependencies
- Config
- DynaLoader
- IO::Handle
- Test::Harness
- Test::More
- and possibly others
- Reverse dependencies
- CPAN Testers List
- Dependency graph
- NAME
- SYNOPSIS
- DESCRIPTION
- SPECIFICATION
- FUNCTIONS
- INTERNALS
- EXAMPLES
- TODO
- Release plan
- DIAGNOSTICS
- SEE ALSO
- AUTHORS and MAINTAINERS
NAME
Text::CSV_XS - comma-separated values manipulation routines
SYNOPSIS
use Text::CSV_XS; $csv = Text::CSV_XS->new (); # create a new object $csv = Text::CSV_XS->new (\%attr); # $eof = $csv->eof (); # Indicate if last parse or # getline () hit End Of File $csv->types (\@t_array); # Set column types
DESCRIPTION
Text::CSV_XS provides facilities for the composition and decomposition of comma-separated values. An instance of the Text::CSV_XS.
Embedded newlines
Important Note: The default behavior is to only accept ascii characters. This means that fields can not contain newlines. If your data contains newlines embedded in fields, or characters above 0x7e (tilde), or binary data, you *must* set
binary => 1_XS->new ({ binary => 1, eol => $/ }); while (<>) { # WRONG! $csv->parse ($_); my @fields = $csv->fields ();
will break, as the while might read broken lines, as that doesn't care about the quoting. If you need to support embedded newlines, the way to go is either
use IO::Handle;)
The basic rules are as follows:
CSV is a delimited data format that has fields/columns separated by the comma character and records/rows separated by newlines. Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes. However,.
Each record is one line terminated by a line feed (ASCII/LF=0x0A) or a carriage return and line feed pair (ASCII/CRLF=0x0D 0x0A), however, line-breaks can U+060c (ARABIC COMMA), U+FF0C (FULLWIDTH COMMA), U+241B (SYMBOL FOR ESCAPE), U+2424 (SYMBOL FOR NEWLINE), U+FF02 (FULLWIDTH QUOTATION MARK), and U+201C (LEFT DOUBLE QUOTATION MARK) (to give some examples of what might look promising) are therefor not allowed. (\%attr)
(Class method) Returns a new instance of Text::CSV_XS. The objects attributes are described by the (optional) hash ref
\%attr. Currently the following attributes are available:
- eol
An end-of-line string to add to rows, usually
undef(nothing, default),
".
- sep_char.
- allow_whitespace
When this option is set to true, whitespace (TAB's and SPACE's) surrounding the separation character is removed when parsing. So lines like:
1 , "foo" , bar , 3 , zapp
are now correctly parsed, even though it violates the CSV specs. Note that all whitespace is stripped from start and end of each field. That would make is more a feature than a way to be able to parse bad CSV lines, as
1, 2.0, 3, ape , monkey
will now be parsed as
("1", "2.0", "3", "ape", "monkey")
even if the original line was perfectly sane CSV.
- quote_char.
- allow_loose_quotes
By default, parsing fields that have
quote_charcharacters inside an unquoted field, like
1,foo "bar" baz,42
would result in a parse error. Though it is still bad practice to allow this format, we cannot help there are some vendors that make their applications spit out lines styled like this.
- escape_char
The character used for escaping.
- binary
If this attribute is TRUE, you may use binary characters in quoted fields, including line feeds, carriage returns and NULL bytes. (The latter must be escaped as
"0.) By default this feature is off.
-. :-)
- keep_meta_info.
- verbatim_XS'.
To sum it up,
$csv = Text::CSV_XS->new ();
is equivalent to
$csv = Text::CSV_XS->new ({ quote_char => '"', escape_char => '"', sep_char => ',', eol => '', always_quote => 0, binary => 0, keep_meta_info => 0, allow_loose_quotes => 0, allow_loose_escapes => 0, allow_whitespace => 0, verbat.
- combine
.
$status = $csv->print ($io, $colref);, $colref);
The glob
\*FILE.
- string
$line = $csv->string ();
This object function returns the input to
parse ()or the resultant CSV string of
combine (), whichever was called more recently.
- parse
.
- getline
.
The $csv->string (), $csv->fields () and $csv->status () methods are meaningless, again.
-.
-, object function returns the input to
combine ()or the resultant decomposed fields of
parse (), whichever was called more recently.
- meta_info
:
$csv->error_diag (); $error_code = 0 + $csv->error_diag (); $error_str = "" . $csv->error_diag (); ($cde, $str) = called in scalar context, it will return the diagnostics in a single scalar, a-la $!. It will contain the error code in numeric context, and the diagnostics message in string context.
INTERNALS
The arguments to these two internal functions are deliberately not described or documented to enable the module author(s) to change it when they feel the need for it and using them is highly discouraged as the API may change in future releases.
EXAMPLES
An example for creating CSV files:
use Text::CSV_XS; my $csv = Text::CSV_XS->new; open my $csv_fh, ">", "hello.csv" or die "hello.csv: $!"; my @sample_input_fields = ( 'You said, "Hello!"', 5.67, '"Surely"', '', '3.14159'); if ($csv->combine (@sample_input_fields)) { my $string = $csv->string; print $csv_fh "$string\n"; } else { my $err = $csv->error_input; print "combine () failed on argument: ", $err, "\n"; } close $csv_fh;], $quo; } } else { my $err = $csv->error_input; print STDERR "parse () failed on argument: ", $err, "\n"; $csv->error_diag (); }
TODO
- More Errors & Warnings
At current, it is hard to tell where or why an error occured (if at all)..
If ->new () fails, there should be a way to obtain the reason why. Currently it is almost impossible to make new () fail, but in the future there should be a (default) option to have it fail when unsupported options are passed.
- eol
Discuss an option to make the eol honor the $/ setting. Maybe
my $csv = Text::CSV_XS->new ({ eol => $/ });
is already enough, and new options only make things less opaque.
- returning undefined fields
Adding an option that enables the parser to distinguish between empty fields and undefined fields, like
$csv->always_quote (1); $csv->allow_undef (1); $csv->parse (qq{,"",1,"2",,""}); my @fld = $csv->fields ();
Then would return (undef, "", "1", "2", undef, "") in @fld, instead of the current ("", "", "1", "2", "", "").
- combined methods
Requests for adding means (methods) that combine
combine ()and
string ()in a single call will not be honored. Likewise for
parse ()and
fields (). Given the trouble with embedded newlines, using
getline ()and
print ()instead is the prefered way to go.
- Unicode
Make
parse ()and
combine ()do the right thing for Unicode (UTF-8) if requested. See t/50_utf8.t. More complicated, but evenly important, also for
getline ()and
print ().
Probably the best way to do this is to make a subclass Text::CSV_XS::Encoded that can be passed the required encoding and then behaves transparently (but slower).
- Double double quotes
There seem to be applications around that write their dates like
1,4,""12/11/2004"",4,1
If we would support that, probably through allow_double_quoted Definitely belongs in t/65_allow.t
- Parse the whole file at once
Implement a new methods that enables the parsing of a complete file at once, returning a lis of hashes. Possible extension to this could be to enable a column selection on the call:
my @AoH = $csv->parse_file ($filename, { cols => [ 1, 4..8, 12 ]});
Returning something like
[ { fields => [ 1, 2, "foo", 4.5, undef, "", 8 ], flags => [ ... ], errors => [ ... ], }, { fields => [ ... ], . . }, ]
- EBCDIC
The hard-coding of characters and character ranges makes this module unusable on EBCDIC system. Using some #ifdef structure could enable these again without loosing speed. Testing would be the hard part.
Release plan
No guarantees, but this is what I have in mind right now:
- 0.33
- croak / carp - error cause for failing new () - return undef - DIAGNOSTICS setction in pod to *describe* the errors (see below)
- 0.34
- allow_double_quoted - Text::CSV_XS::Encoded (maybe)
- 0.35
- csv2csv - a script to regenerate a CSV file to follow standards - EBCDIC support
DIAGNOSTICS
Still under construction ....
Currently these errors are available:
- 1001 "sep_char is equal to quote_char or escape_char"
-
- 2010 "ECR - QUO char inside quotes followed by CR not part of EOL"
-
- 2011 "ECR - Characters after end of quoted field"
-
- 2012 "EOF - End of data in parsing input stream"
-
- 2021 "EIQ - NL char inside quotes, binary off"
-
- 2022 "EIQ - CR char inside quotes, binary off"
-
- 2023 "EIQ - QUO ..."
-
- 2024 "EIQ - EOF cannot be escaped, not even inside quotes"
-
- 2025 "EIQ - Loose unescaped escape"
-
- 2026 "EIQ - Binary character inside quoted field, binary off"
-
- 2027 "EIQ - Quoted field not terminated"
-
- 2030 "EIF - NL char inside unquoted verbatim, binary off"
-
- 2031 "EIF - CR char is first char of field, not part of EOL"
-
- 2032 "EIF - CR char inside unquoted, not part of EOL"
-
- 2033 "EIF - QUO, QUO != ESC, binary off"
-
-"
-
SEE ALSO
perl(1), IO::File(3), L{IO::Handle(3)>, IO::Wrap(3), Text::CSV(3), Text::CSV_PP(3). and Spreadsheet::Read(3).
AUTHORS and MAINTAINERS
Alan Citterman <alan@mfgrtl.com> wrote the original Perl module. Please don't send mail concerning Text::CSV_XS to Alan, as he's not involved in the C part which is now the main part of the module.
Jochen Wiedmann <joe@xs4all.nl> cleaned up the code, added the field flags methods, wrote the major part of the test suite, completed the documentation, fixed some RT bugs. See ChangeLog releases 0.25 and on.
Copyright (C) 2007-2008..
|
https://metacpan.org/release/HMBRAND/Text-CSV_XS-0.34/view/CSV_XS.pm
|
CC-MAIN-2022-27
|
refinedweb
| 1,526
| 61.06
|
Description
A DSL for building chainable, composable HTTP requests. API structure taken from
the lovely elm-http-builder.
Currently comes with adapters for HTTPoison, HTTPotion, Hackney and IBrowse.
Documentation can be found at.
It's early days still. Feedback welcome!
HttpBuilder alternatives and similar packages
Based on the "HTTP Client" category.
Alternatively, view HttpBuilder alternatives based on common mentions on social networks and blogs.
httpoison9.9 2.8 HttpBuilder VS httpoisonYet Another HTTP client for Elixir powered by hackney
hackney9.8 5.8 HttpBuilder VS hackneysimple HTTP client in Erlang
tesla9.8 6.9 HttpBuilder VS teslaThe flexible HTTP client library for Elixir, with support for middleware and multiple adapters.
httpotion9.3 0.0 HttpBuilder VS httpotion(soft-deprecated) HTTP client for Elixir (use Tesla please)
Maxwell7.0 0.7 HttpBuilder VS MaxwellMaxwell is an HTTP client which support for middleware and multiple adapters.
Scout APM: A developer's best friend. Try free for 14-days
Do you think we are missing an alternative of HttpBuilder or a related project?
README
HttpBuilder
A DSL for building chainable, composable HTTP requests. API structure taken from the lovely elm-http-builder.
Currently comes with adapters for
HTTPoison,
HTTPotion,
Hackney and
IBrowse. JSON parsers are configurable, but defaults to
Poison if present.
Documentation can be found at.
It's early days still. Feedback welcome!
Example Usage
defmodule MyApp.APIClient do import HttpBuilder @adapter Application.get_env(:my_app, :http_adapter) def client() do # Alternatively - use HttpBuilder.cast/1 with a map of options. HttpBuilder.new() |> with_host("") |> with_adapter(@adapter) |> with_headers(%{ "Authorization" => "Bearer #{MyApp.getToken()}", "Content-Type" => "application/json" }) end def submit_widget(body) do client() |> post("/v1/path/to/submit") |> with_body(body) |> send() end def get_widget do client() |> get("/v1/path/to/fetch") |> with_query_params(%{"offset" => 10, "limit" => 5}) |> with_request_timeout(10 * 1000) |> with_receive_timeout(5 * 1000) |> send() end end
Installation
def deps do [ {:http_builder, "~> 0.4.0"} ] end
Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at.
|
https://elixir.libhunt.com/elixir-httpbuilder-alternatives
|
CC-MAIN-2021-43
|
refinedweb
| 326
| 52.87
|
Learning Java is simple. It is preferred to know C-lang earlier. Knowledge of C++ is not essential as same OOPS concepts we learn with Java syntax. This Simple Java Application gives you step-wise writing source code, compilation and execution.
Note: Before coming to know this tutorial, you are expected to know Java features, Java keywords and Java naming conventions.
Following is your first Simple Java Application that prints Hello World
Let us see each step from writing source code to getting output.
A. Writing source code
I take it granted you loaded JDK software and set the path in Environment Variables. Now open command-prompt and open notepad and write the following command. Say example,
C:\snr> notepad Demo.java
Demo.java is the file name. The extension of of a Java file should be .java like for a C-prog it is .c. The above statement opens a notepad and write the above source code as it is.
B. Compilation
After writing source code, let us compile.
C:\snr> javac Demo.java
javac stands for Java compiler. It is an instruction to compiler to compile Java file Demo.java. When compiled successfully, the compiler generates an executable file Demo.class.
C. Execution
After compilation, let us execute.
C:\snr> java Demo
The above command executes Demo.class and gets output as it the above screenshot.
Let us discuss briefly each line of code.
import java.lang.*;
import keyword is equivalent to include of C-lang. java.lang is a package equivalent to header file of C-lang, but with a difference. A header file contains a set of related predefined functions where as package contains related predefined classes and interfaces. With the above statement, all the classes and interfaces of java.lang package are imported for our Java program. Such classes are String and System used in the above program.
public class Demo
The whole code you write should be included within the class declaration; between open and close braces of the class. For this reason, main() method is also enclosed within the class. public is an access specifier that means the Demo.java code can be used by any other class without any restrictions. class is another keyword of Java which gives the name to the code as Demo.
public static void main(String args[])
static is known as access modifier that means the main() method can be called without the help of an object by JVM. JVM stands for Java Virtual Machine, the component of JDK responsible for execution of Java code. void keyword means, the main() method does not return a value. The main() method takes a string array by name args as parameter that can be used later to access command-line arguments.
System.out.println(“Hello World”);
System.out.println(“Best Wishes”);
System.out.println(“I want to prove Java is Simple”);
System.out.println() is the same as printf() of C-lang which prints at command-prompt. In Java, for each line \n is inbuilt. In println(), ln stands for new line character \n.
Following links give simple Java applications to start with learning Java in the same order. It is advised to talk to your Java friends whenever there is a bottleneck in understanding or write to me by filling the text box “Leave a Reply” given at each lesson end.
1. Java Example Compilation Execution
2. Using Local and Instance Variables
3. Data Binding Data Hiding Encapsulation
4. Using Variables from Methods
5. Unassigned Local and Instance Variables
6. static Keyword
|
http://way2java.com/java-general/simple-java-applications/
|
CC-MAIN-2017-17
|
refinedweb
| 592
| 60.11
|
Yesterday I tweeted about me being able to access my Docker for Windows Kubernetes Cluster from Debian WSL without exposing the Docker Daemon with TLS and I got quite some responses.
W00t! I'm able to access my #Docker for Windows #Kubernetes Cluster from #Debian WSL without exposing the #Docker Daemon with TLS. Anyone interested to know how I did this? pic.twitter.com/Dgu3a6aWrO
— Stefan Stranger (@sstranger) April 1, 2018
It seems that there are quite some people interested in me sharing how I was able to do this.
Background information
Let me start with some background information about why I wanted to manage my Docker for Windows Client Kubernetes cluster from (Debian) WSL. Last week I visited the Dutch Azure Meetup in Amsterdam where Erik St. Martin talked about Azure Containers.
One of the tools he talked about was Helm. Helm is a package manager for Kubernetes.
Helm
Helm helps you manage Kubernetes applications — Helm Charts helps you define, install, and upgrade even the most complex Kubernetes application.
Charts are easy to create, version, share, and publish — so start using Helm and stop the copy-and-paste madness.
I wanted to play around with Helm on my Docker for Windows Kubernetes Cluster. Please read my earlier blog post called "Running Kubernetes Cluster in Docker for Windows" to learn more on how to get this running on your Windows 10 machine.
There are different version of Helm:
I tried to install the Windows version of Helm but was not able to get this working. Then I thought I would try to manage my Docker for Windows Kubernetes cluster from (Debian) WSL.
We just released the Debian GNU/Linux for WSL. More information can be found at the following "Debian GNU/Linux for WSL now available in the Windows Store" blog post.
While investigating how I could connect from Debian WSL to my Docker for Windows Kubernetes cluster I stumbled on the following blog post "[Cross Post] WSL Interoperability with Docker" from Craig Wilhite.
By default the Docker Client for Windows offers a configuration to expose the Docker Daemon.
If you enable this configuration you do expose your system to potential attack vectors for malicious code.
And that's where the tool npiperelay can help. This is a tool built by John Starks.
WSL Interoperability with Docker
Please following the steps to install npiperelay, socat, docker client on the blog post from Craig Wilhite.
High-Level I run the following steps:
- Install npiperelay in Debian WSL
- Install Aptitude on Debian WSLAptitude is an Ncurses based FrontEnd to Apt, the debian package manager.
sudo apt-get install aptitude
- Install Go#Make sure we have the latest package lists
sudo apt-get update
#Download Go. You should change the version if there's a newer one. Check at:
sudo wget
#unzip Go
sudo tar -C /usr/local -xzf go1.10.1.linux-amd64.tar.gz
#Put it in the path
export PATH=$PATH:/usr/local/go/bin
- Build the relay (see the blog post from Craigh Wilhite)
- Install socatsudo aptitiude install socat
- Install Docker CE for Debian ()sudo aptitude install docker-ce
- Stitch everything together.See blog post Craigh Wilhite.
- Install kubectl ()
- Configure kubectl configuration.Copy Docker for Windows Kubernetes kube config files to Debian WSL kube configuration folder
cp -R /mnt/c/Users/[username]/.kube/ ~/
This will copy the kubernetes cluster configuration created by the Docker for Windows client to the Debian WSL user.
- Install Helm on Debian WSL
curl | bash
You should now be able to access your Docker for Windows Kubernetes cluster from Debian WSL.
#start relay sudo ~/docker-relay & #test docker client docker version #test access to the Kubernetes cluster kubectl version kubectl cluster-info kubectl get nodes --all-namespaces kubectl get pods --all-namespaces #test Helm helm version helm list
Have fun!
References:
|
https://blogs.technet.microsoft.com/stefan_stranger/2018/04/02/access-my-docker-for-windows-kubernetes-cluster-from-debian-wsl/
|
CC-MAIN-2019-04
|
refinedweb
| 636
| 53.61
|
16 August 2012 07:33 [Source: ICIS news]
By Felicia Loo
?xml:namespace>
SINGAPORE
European cracker operators have the incentive to switch to naphtha because of a weakening price spread between propane and naphtha, they said.
With the North Sea refineries going into maintenance,
“The arbitrage window is closed,” said one trader.
Prices will also draw support from the increased use of naphtha in the gasoline blending pool to plug a supply shortfall in the
At midday, Asia’s open-spec naphtha prices for the first-half October contract rose by $15-17/tonne (€12-14/tonne) from Wednesday to $963-$966/tonne CFR Japan – the highest since 4 May when prices were $965.50/tonne CFR Japan, according to ICIS data. Prices have tracked the overall robust gains in Brent crude futures.
Brent crude on ICE Futures rallied on Wednesday after weekly
However, Asian petrochemical demand appeared to be weak, capping any significant price gains in naphtha, traders said.
Asian styrene monomer (SM) prices remain on a downtrend this week with market activity slowing down. Prices declined to around $1,430/tonne CFR China this week after surging past $1,460/tonne CFR China last week.
According to ICIS data, SM spot prices staged a dramatic rebound off a low this year of $1,240/tonne CFR China in the first half of June, with the eurozone crisis abating temporarily. Short covering activities in July gave prices another boost from $1,325/tonne CFR China in late June to $1,400/tonne CFR China in late July.
However, with most of the shorts being covered over the past few weeks, buying impetus has weakened with players staying on the sidelines. Weak performance in the downstream styrenic resins sector also exerted downward pressure on SM prices. Poor economic conditions in the
For naphtha,
The continuous absence of key buyer –
FPCC took its 1.03m tonne/year No 2 cracker in Mailiao off line on Wednesday morning as planned. The 30-day shutdown prompted FPCC to skip spot naphtha buying for September and October deliveries.
The naphtha backwardation narrowed by half to $4/tonne on Wednesday, compared with a backwardation of $8/tonne on Monday, ICIS data showed.
“The naphtha intermonth spread is not as strong,” one trader said.
($1 = €0.81)
|
http://www.icis.com/Articles/2012/08/16/9587431/asia-naphtha-may-extend-gains-on-limited-oct-deep-sea-inflows.html
|
CC-MAIN-2014-42
|
refinedweb
| 381
| 60.04
|
I made a graphic in Illustrator CS5, and imported it into Flash CS5 as a graphic symbol.
I then changed its properties from a graphic into a button. I select Code Snippets and choose the Action to go to a web page.
1. Why is it making a movie clip to make this work?
2. I edit the properties of the button and add keyfrrames to the other states and on the over state, I scale it so it looks large. However, after testing it, the link I applied works, though the rollover effect does not. How can I make it work?
Thanks!!!!
start over by deleting everything but the graphic you imported. then click insert/new symbol/button/ok. on the button "timeline" add the graphic you want to the variouse button frames. drag the button from the library to your stage, assign an instance name and apply your button listener(s) to that button.
I want to add a new symbol of the same exact image being used for the button, only in a different color, and it too was designed in Illustrator. Should I just copy-and-paste all of these symbols from Illustrator onto the main stage, then delete them from the stage after they are imported into my library?
OR is there another way to do this?
Thanks.
import your new graphics into your library. duplicate your other button. go to the timeline of the other button and remove the old graphics and replace with your new graphics.
|
https://forums.adobe.com/thread/748850
|
CC-MAIN-2018-39
|
refinedweb
| 253
| 73.68
|
for f in *.pdf; \ do pdftotext -q -f 1 -l 2 $f $f.txt; \ err=$?; \ if [ $err -ne 0 ]; then mv $f _failed_$f; \ elif [ $err -eq 3 ]; then mv $f _locked_$f; \ else rm $f.txt; fi; done
Transfer files from remote server
When connected to a remote machine over ssh, it can be cumbersome to transfer files.
SCP, secure copy, makes it easy:
scp username@host:remote_file local_file scp username@host:~/foo/bar/*.csv ~/foo/bar/*.csv
Note: It seems easiest to initiate the transfer from a local console session.
Kick off multiple instances of script
I had the need to launch about 100 instances of a script all at once to scrape some web data. This was the loop I used:
for f in *.txt; do python inStock.py $f & done
Note:
- Semicolon launches consecutively, waiting for previous script to finish:
- for f in *.txt; do foobar.py $f; done
- Ampersand launches in the background rather than waiting for the consecutive script before it to finish:
- for f in *.txt; do foobar.py $f & done
Set Environmental Variables
When working with login credentials, server addresses, etc you can hide them from git and other viewers by saving them as local environmental variables.
Steps:
- create a .bash_profile if it does not exist yet.
- edit the .bash_profile to add or change the variables
- activate the .bash_profile
In a terminal/console:
touch ~/.bash_profile vim ~/.bash_profile source ~/.bash_profile
To set a new variable in the .bash_profile:
#aws export AWS_KEY=$"foobarkey123" export AWS_SECRET=$"foobarsecret123"
To use environmental variables in Python:
import os awsKey = os.environ['AWS_KEY'] awsSecret = os.environ['AWS_SECRET']
Remove duplicate files by MD5
I recently had the need to delete an unknown number of duplicate files out of a batch of ~10,000 images. The filenames were all different, but the md5 hash was known and all of the duplicates had the same.
md5 -r *.jpg | grep "37d1b8f9d6f02f31cmb192a28b96cade" | awk '{ print $2 }' | xargs rm
Split a text file in half
I often have the need to split long text files into smaller chunks, and my need requires they are split by line.
Here's my one liner solution:
f=$"filename"; s=$(wc -l $f | awk '{print $1}'); \ h=$(echo "scale=0;" $(($s/2+1)) | bc -q); \ split -l $h $f "output_"; for file in output_*; \ do mv "$file" "$file.txt"; done
Notes:
BC can handle floating point numbers, so scale=0 limits any decimal output.
Bash math requires double parentheses.
|
http://www.stevearnett.com/code?offset=1464274800883
|
CC-MAIN-2019-22
|
refinedweb
| 409
| 74.19
|
How to turn off validationsjess singh May 27, 2009 6:59 PM
I need to turn validations off on a form - If i try
immediate =true I can bypass validations but I don't see any values in the model bean (e.g Customer bean contained in CustomerAction ).
How can I get all the values the user entered ? Thanks in Advance.
1. Re: How to turn off validationsArbi Sookazian May 27, 2009 10:40 PM (in response to jess singh)
Are you using the <s:decorate>, <s:validate>, or <s:validateAll> tags or custom validation?
Why and how long do you need to turn off validation in a particular xhtml?
Refer to
Immediate Componentssection in Core JSF:
Immediate input components perform conversion and validation, and subsequently deliver value change events at the beginning of the JSF life cycle - after the Apply Request Values - instead of after Process Validations.
The example cited for bypassing validation is on pg. 238:
<h:commandButton
Validation does not need to occur when you cancel a form.
If a command has the immediate attribute set, then the command is executed during the Apply Request Values phase.
Or are you asking for a way to turn off validation for all xhtml pages??
2. Re: How to turn off validationsjess singh May 27, 2009 11:16 PM (in response to jess singh)
Hi Arbi - thanks for the help, I am using s:validateAll - I need validaton turned off for a particular page - the use case is when user wants to save a record as template (to create new records based on this template later )
I am aware of
<h:commandButton
but the problem is it does not put any values in the bean - and as you said if it happens after 'apply request values' phase then user entered values should be there but they are not.
3. Re: How to turn off validationsArbi Sookazian May 28, 2009 12:10 AM (in response to jess singh)
jess singh wrote on May 27, 2009 23:16:
I need validaton turned off for a particular page - the use case is when user wants to save a record as template (to create new records based on this template later )
So is this always turned off or sometimes turned off depending on what the user is doing on that page?
There is a big difference. I imagine the latter.
I have not encountered a scenario where I must conditionally turn on/off <s:validateAll>.
There are no attributes for that component according to 2.1 ref doc.
What kind of validations? Are they custom business validations (i.e. @Validator)? Or Hibernate Validator like @NotNull, @Range, @Length, etc.
Here is an example of business validator:
@Name("seamValidatorCodes") @Scope(ScopeType.CONVERSATION) @org.jboss.seam.annotations.faces.Validator public class SeamValidatorCodes implements javax.faces.validator.Validator, java.io.Serializable{...}
4. Re: How to turn off validationsjess singh May 28, 2009 11:42 PM (in response to jess singh)
Arbi - they are both types - business (custom hibernate validators as well as regular like @NotNull , @Length etc ) - yes s:validateAll can't be turned off through attributes - so what would be my best bet ?
5. Re: How to turn off validationsArbi Sookazian May 29, 2009 12:22 AM (in response to jess singh)
The only alternative I can think of is to modify the validateAll tag library and add support method(s) and an attribute to the tag (perhaps enabled?) to add the enable/disable functionality.
ex:
<s:validateAll
That would be the more elegant solution. The other workaround is to duplicate the xhtml (one with and one without the s:validateAll tags) and route the requests accordingly depending on enabled or disabled as per the use case requirement. This is not an optimal solution of course but it may satisfy your requirement(s).
|
https://developer.jboss.org/thread/188002
|
CC-MAIN-2018-17
|
refinedweb
| 636
| 59.03
|
Net::XMPP - XMPP Perl Library
Net::XMPP provides a Perl user with access to the Extensible Messaging and Presence Protocol (XMPP).
For more information about XMPP visit:.
use Net::XMPP; my $client = Net::XMPP::Client->new();:
Returns the XML string that represents the data contained in the object.
$xml = $obj->GetXML();");
Return the root tag name of the packet.
Return the XML::Stream::Node object that contains the data. See XML::Stream::Node for methods you can call on this object.()
Removes the raw XML from the packet.
RemoveChild() RemoveChild(namespace)
Removes all of the namespaces child elements from the object. If a namespace is provided, then only the children with that namespace are removed.");
For more information on each of these packages, please see the man page for each one..
A collection of high-level functions that Client uses to make their lives easier. These methods are inherited by the Client.
The XMPP XMPP recognizes..
Originally authored by Ryan Eatmon.
Previously maintained by Eric Hacker.
Currently maintained by Darian Anthony Patrick..
|
http://search.cpan.org/~dapatrick/Net-XMPP-1.02_04/lib/Net/XMPP.pm
|
CC-MAIN-2016-07
|
refinedweb
| 172
| 61.43
|
15 October 2012 03:45 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
Lower production volume and sales because of a planned turnaround at a plant, which is owned by affiliate Al Waha during the quarter, also affected Sahara Petrochemicals’ earnings, it said in a filing to the Saudi Stock Exchange or Tadawul on Sunday.
The company’s gross profit fell by 79% year on year to SR9.7m in the third quarter of this year.
Sahara Petrochemicals incurred an operating loss of SR7.2m in the third quarter of this year, reversing a profit of SR27.9m in the same period 2011, the company said in a statement.
In the first nine months of this year, the company’s net profit fell by 66% year on year to SR139.9m.
The company swung to an operational loss of SR78.2m in the January-September period from a profit of SR158.8m in the same period in 2011.
(
|
http://www.icis.com/Articles/2012/10/15/9603754/saudis-sahara-petrochemicals-q3-net-profit-falls-55.html
|
CC-MAIN-2015-06
|
refinedweb
| 157
| 66.54
|
Welcome to the Factory Design Pattern in Java tutorial. Factory Pattern is one of the Creational Design pattern and it’s widely used in JDK as well as frameworks like Spring and Struts.
Table of Contents
Factory Design Pattern
The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.
Let’s first learn how to implement a factory design pattern in java and then we will look into factory pattern advantages. We will see some of the factory design pattern usage in JDK. Note that this pattern is also known as Factory Method Design Pattern.
Factory Design Pattern Super Class
Super class in factory design pattern can be an interface, abstract class or a normal java class. For our factory design pattern example, we have abstract super class with overridden
toString() method for testing purpose.
package com.journaldev.design.model; public abstract class Computer { public abstract String getRAM(); public abstract String getHDD(); public abstract String getCPU(); @Override public String toString(){ return "RAM= "+this.getRAM()+", HDD="+this.getHDD()+", CPU="+this.getCPU(); } }
Factory Design Pattern Sub Classes
Let’s say we have two sub-classes PC and Server with below implementation.
package; } }
Notice that both the classes are extending
Computer super class.
package
Now that we have super classes and sub-classes ready, we can write our factory class. Here is the basic implementation.
package com.journaldev.design.factory; import com.journaldev.design.model.Computer; import com.journaldev.design.model.PC; import com.journaldev.design.model.Server; public class ComputerFactory { public static Computer getComputer(String type, String ram, String hdd, String cpu){ if("PC".equalsIgnoreCase(type)) return new PC(ram, hdd, cpu); else if("Server".equalsIgnoreCase(type)) return new Server(ram, hdd, cpu); return null; } }
Some important points about Factory Design Pattern method are;
- We can keep Factory class Singleton or we can keep the method that returns the subclass as static.
- Notice that based on the input parameter, different subclass is created and returned.
getComputeris the factory method.
Here is a simple test client program that uses above factory design pattern implementation.
package com.journaldev.design.test; import com.journaldev.design.factory.ComputerFactory; import com.journaldev.design.model.Computer; public class TestFactory { public static void main(String[] args) { Computer pc = ComputerFactory.getComputer("pc","2 GB","500 GB","2.4 GHz"); Computer server = ComputerFactory.getComputer("server","16 GB","1 TB","2.9 GHz"); System.out.println("Factory PC Config::"+pc); System.out.println("Factory Server Config::"+server); } }
Output of above program is:
Factory PC Config::RAM= 2 GB, HDD=500 GB, CPU=2.4 GHz Factory Server Config::RAM= 16 GB, HDD=1 TB, CPU=2.9 GHz
Factory Design Pattern Advantages
-.
Factory Design Pattern Examples in JDK
- java.util.Calendar, ResourceBundle and NumberFormat
getInstance()methods uses Factory pattern.
valueOf()method in wrapper classes like Boolean, Integer etc.
Factory Design Pattern YouTube Video Tutorial
I recently uploaded a video on YouTube for Factory Design pattern, please check it out. Please like and share the video and subscribe to my YouTube channel.
I think the explanation in ‘Factory Design Pattern Advantages’ section is quite verbose. I can tell the advantage of this pattern is simply “reducing repeated codes to choose and instantiate an implementation with arguments you’re having, using the fact there is only one possible implementation of the interface for a combination of arguments or/and for the environment of the machine.”
“provides approach to code for interface rather than implementation” and “provides abstraction between implementation and client classes through inheritance” are true, but I think they are just derived results from the reason why you apply this pattern I said above.
So I think the first advantage in the section should be what I said above at least.
Pankaj, You have a wide reach and your article make a huge impact on developers. I appreciate your work and dedication that you put to bring this in front of us all. Having said that I want to invite you to partner me in clearing the space and providing the correct Design patterns as they are and not as they occur to you, me or any other author. Lets stick to the original GOF definition. It defines Abstract factory pattern and Factory pattern. I want to point out that the example you have put is neither of that. In the factory pattern , the factory class has an abstract method to create the product and lets the sub classes to create the concrete product. What you have is a static method. also the examples you mentioned as being present in JDK as example of factory method is also not pure factory pattern. They are simply Static Factory methods. Those are not the part of GOF Creational pattern. I want you to edit your post so as Correct information reaches the readers.
Thanks a lot for the nice content for me!
Thank you Pankaj for enlightening us with your clear and succinct answer.
> valueOf() method in wrapper classes like Boolean, Integer etc.
Could you explain more about this?
You said, if we don’t use factory design pattern, Client will be aware of all the instances of the Computer(such as PC, Server), there is no abstraction. Even with factory design pattern, client should be aware of all the instances of the Computer right, else how will the client pass that string(“pc”,”server”) depending on his requirement ?
i think only the pc types will be known to the client and its implementation is hidden from them.
It was explained good. Thank you
Very well descriptive article. Big Thanks !
thank’s sir Nice article
Thanks for sharing.
how do i implement a factory to store my data and call it inside my unit tests?
Thanks for sharing
Very helpful artical. Thank you.
Very weel explained! Thank you!
very nice tutorial, easy to understand!
I understand that there’s always a benefit to get the instance of a class using the provided factory implementation.
How can I force users to compulsorily use the factory implementation to get the instance, instead of getting away creating an instance directly using new operator of the actual class?
i.e. How can I force people to use ServerFactory.getInstance() instead of new Server()?
You can make Server Class as an abstract class.
But in that case Your Factory wont be able to create the instance itself.
If you can make the constructor private as per singleton, then i assume that you cannot create the instance using new Server(); and only enforces the user to access the object only through getInstance(). Also as an additional rule getInstance() method can be enforced as a rule to be implemented in the sub-classes extending computer. i.e. an abstract method of getInstance(), be present in Computer class which is already an abstract class. Hope m right, others correct me if m wrong
But i think even in that case you can get an instance of the singleton instance be it PC or Server without using the factory right? If i am wrong can you pleaser paste some code in the reply section?
It’s Nice Explanation Learnt new things more it’s best practice and understanding
Quick and easy tutorial, thanks.
Learned some new stuff with very detailed information.
Where below are implemented
import com.journaldev.design.abstractfactory.PCFactory;
import com.journaldev.design.abstractfactory.ServerFactory;
Sorry, that came out while copying the code from my Eclipse editor by mistake. Those imports are useless, I have removed them from above code.
It’s a very good tutorial. But I have a doubt,
You mentioned Calendar#getInstance() as factory pattern implementation. But in this there is a small difference right?
There is no separate factory class. The super class Calendar itself is acting as the factory class.
Does an implementation like this have any advantage or disadvantage?
Hi, is there a place in which I can download all the source code for the several design pattern examples.
These are great examples, but I have to copy-paste each single text box into Intellij, and it is very cumbersome.
Thank you very much, and congratulations for such good material.
Yes. Its very nice article about simple factory covers basic concepts.
I am relatively new to design patterns but I need to ask this question. What if we need to add another subclass of computer say Laptop to the application.? Does this mean we will have to modify the computer factory class? This looks like violating the OO principle which says classes should be closed to modification but open to extension.
It seems to me that you’re showing what is called a simple factory with ComputerFactory; It is not the Factory Method Pattern.
The client TestFactory delegates the creation to another class which it is composed with.
If you want to implement the Factory Method Pattern,:
1. ComputerFactory should define an asbtract method getComputer(String ram, String hdd, String cpu)
2. ComputerFactory should have two subclasses PCFactory and ServerFactory.which implements the superclass abstract method to return either a PC or a server
3. The client should be given one of the two concrete factories and call the factory method to get PC or servers, depending which one was instanciated
yes , i agree. the article is about simple factory not factory .
But still a nice article.
Could you please reply back with actual factory pattern example
in your own explanatroy words…
yes absolutely you are right. It is not factory method pattern.
This is a factory (factory method ) pattern, if you make factory abstract then it becomes abstract factory pattern
Nice article !!!!!!!!
Now i found the perfect article for Design pattern.
Thanks Pankaj
Thanks for the clear explanation.
I have one doubt here in Factory pattern. We have two concrete classes implementing the interface/Abstract class whose instances are created inside Factory class.But, instead of below line
Computer pc = ComputerFactory.getComputer(“pc”,”2 GB”,”500 GB”,”2.4 GHz”);
we can also use
Computer pc=new PC(“pc”,”2 GB”,”500 GB”,”2.4 GHz”); to get new instance of PC. Then what is the advantage of using ComputerFactory.getComputer() method on the client side directly.?
See here
That’s why it’s called an creation all design pattern cause then we don’t have to dirty our code keeping the instance creation all logic here and there cause we have implanted a factory out there which is just doing it for us you just name it..name the object and it’s ready for you….
Thats because u will be bound to the object, ie if you create Computer pc=new PC(“pc”,”2 GB”,”500 GB”,”2.4 GHz”) u will always get the instance of PC and it would be hardcoding, So if you use factory you wil not worry of the implementation u will always get the object of reference Computer.
Some body asked me that Why do we have to implement singleton pattern when we have static.
And here in your post you say that either we can use static method or implement it as Singleton. Can you please detail on this?
May be its a late reply, but worth share thought here.
Factory classes(In general design patterns) are meant for maintainability and re-usability. Factory pattern states that, the objective of this pattern is to decouple the object instantiation from the client program. And this can be achieved either by static method or singleton factory class.
Why we use singleton pattern when we have static?
we use “static” when a piece of code/data same across all instances of a class OR important piece of code that needs to be executed even when class is not instantiated OR instantiation is not required.
Question here is, how to make outer class itself static? the answer is “Singleton Pattern”.
The “singleton pattern” is a mechanism, which gives the flexibility to reuse the same instance of a class(avoid multiple instantiation of a class when it is not required OR execute mandatory functionality only once) OR have the single instance to achieve the expected functionality.
This can be achieved by using static + additional checks on the pre-existence of the instance(of self).
Ex: Thread pool.
Good answer!!!
Very good answer… Thank You
|
https://www.journaldev.com/1392/factory-design-pattern-in-java
|
CC-MAIN-2021-10
|
refinedweb
| 2,081
| 57.57
|
Can I add/increment individual elements to a Counter?
I am getting each element one by one from an xml parse stream, so my Counter use here is always going to be based on 1-by-1.
OK, I know I can do this:
from collections import Counter
counter = Counter("abaa")
print ("counter:", counter) #('counter:', Counter({'a': 3, 'b': 1}))
#and I can do this as well...
def track_data(counter, data):
counter.update(Counter(data))
#let's say I am in a function that receives data one by one.
one_element_of_incoming_data = "a"
track_data(counter, one_element_of_incoming_data)
print ("counter:", counter) #('counter:', Counter({'a': 4, 'b': 1}))
counter.increment(one_element_of_incoming_data)
Sure:
from collections import Counter counter = Counter() for s in 'abcdefga': counter[s] += 1
In this way,
Counter works like a
defaultdict(int). However, it also has some handy methods since it is made to work with counts of things (e.g. you can add two
Counters together, it has a more convenient constructor, etc.).
|
https://codedump.io/share/X1YDgNBCUkoU/1/collectionscounter---can-i-addincrement-individual-elements-to-a-counter
|
CC-MAIN-2017-04
|
refinedweb
| 161
| 55.24
|
50 Common Java Errors and How to Avoid Them (Part 1)
This big book of compiler errors starts off a two-part series on common Java errors and exceptions, how they're formed, and how to fix them.
Join the DZone community and get the full member experience.Join For Free
There are many types of errors that could be encountered while developing Java software, but most are avoidable. We’ve rounded up 50 of the most common Java software errors, complete with code examples and tutorials to help you work around common coding problems.
For more tips and tricks for coding better Java programs, download our Comprehensive Java Developer’s Guide, which is jam-packed with everything you need to up your Java game – from tools to the best websites and blogs, YouTube channels, Twitter influencers, LinkedIn groups, podcasts, must-attend events, and more.
If you’re working with .NET, you should also check out our guide to the 50 most common .NET software errors and how to avoid them. But if your current challenges are Java-related, read on to learn about the most common issues and their workarounds.
Compiler Errors
Compiler error messages are created when the Java software code is run through the compiler. It is important to remember that a compiler may throw many error messages for one error. So fix the first error and recompile. That could solve many problems.
1. “… Expected”
This error occurs when something is missing from the code. Often this is created by a missing semicolon or closing parenthesis.
private static double volume(String solidom, double alturam, double areaBasem, double raiom) { double vol; if (solidom.equalsIgnoreCase("esfera"){ vol=(4.0/3)*Math.pi*Math.pow(raiom,3); } else { if (solidom.equalsIgnoreCase("cilindro") { vol=Math.pi*Math.pow(raiom,2)*alturam; } else { vol=(1.0/3)*Math.pi*Math.pow(raiom,2)*alturam; } } return vol; }
Often this error message does not pinpoint the exact location of the issue. To find it:
- Make sure all opening parenthesis have a corresponding closing parenthesis.
- Look in the line previous to the Java code line indicated. This Java software error doesn’t get noticed by the compiler until further in the code.
- Sometimes a character such as an opening parenthesis shouldn’t be in the Java code in the first place. So the developer didn’t place a closing parenthesis to balance the parentheses.
Check out an example of how a missed parenthesis can create an error (@StackOverflow).
2. “Unclosed String Literal”
The “unclosed string literal” error message is created when the string literal ends without quotation marks, and the message will appear on the same line as the error. (@DreamInCode) A literal is a source code of a value.
public abstract class NFLPlayersReference { private static Runningback[] nflplayersreference; private static Quarterback[] players; private static WideReceiver[] nflplayers; public static void main(String args[]){ Runningback r = new Runningback("Thomlinsion"); Quarterback q = new Quarterback("Tom Brady"); WideReceiver w = new WideReceiver("Steve Smith"); NFLPlayersReference[] NFLPlayersReference; Run();// { NFLPlayersReference = new NFLPlayersReference [3]; nflplayersreference[0] = r; players[1] = q; nflplayers[2] = w; for ( int i = 0; i < nflplayersreference.length; i++ ) { System.out.println("My name is " + " nflplayersreference[i].getName()); nflplayersreference[i].run(); nflplayersreference[i].run(); nflplayersreference[i].run(); System.out.println("NFL offensive threats have great running abilities!"); } } private static void Run() { System.out.println("Not yet implemented"); } }
Commonly, this happens when:
- The string literal does not end with quote marks. This is easy to correct by closing the string literal with the needed quote mark.
- The string literal extends beyond a line. Long string literals can be broken into multiple literals and concatenated with a plus sign (“+”).
- Quote marks that are part of the string literal are not escaped with a backslash (“\”).
Read a discussion of the unclosed string literal Java software error message. (@Quora)
3. “Illegal Start of an Expression”
There are numerous reasons why an “illegal start of an expression” error occurs. It ends up being one of the less-helpful error messages. Some developers say it’s caused by bad code.
Usually, expressions are created to produce a new value or assign a value to a variable. The compiler expects to find an expression and cannot find it because the syntax does not match expectations. (@StackOverflow) It is in these statements that the error can be found.
} // ADD IT HERE public void newShape(String shape) { switch (shape) { case "Line": Shape line = new Line(startX, startY, endX, endY); shapes.add(line); break; case "Oval": Shape oval = new Oval(startX, startY, endX, endY); shapes.add(oval); break; case "Rectangle": Shape rectangle = new Rectangle(startX, startY, endX, endY); shapes.add(rectangle); break; default: System.out.println("ERROR. Check logic."); } } } // REMOVE IT FROM HERE }
Browse discussions of how to troubleshoot the “illegal start of an expression” error. (@StackOverflow)
4. “Cannot Find Symbol”
This is a very common issue because all identifiers in Java need to be declared before they are used. When the code is being compiled, the compiler does not understand what the identifier means.
There are many reasons you might receive the “cannot find symbol” message:
- The spelling of the identifier when declared may not be the same as when it is used in the code.
- The variable was never declared.
- The variable is not being used in the same scope it was declared.
- The class was not imported.
Read a thorough discussion of the “cannot find symbol” error and examples of code that create this issue. (@StackOverflow)
5. “Public Class XXX Should Be in File”
The “public class XXX should be in file” message occurs when the class XXX and the Java program filename do not match. The code will only be compiled when the class and Java file are the same. (@coderanch):
package javaapplication3; public class Robot { int xlocation; int ylocation; String name; static int ccount = 0; public Robot(int xxlocation, int yylocation, String nname) { xlocation = xxlocation; ylocation = yylocation; name = nname; ccount++; } } public class JavaApplication1 { public static void main(String[] args) { robot firstRobot = new Robot(34,51,"yossi"); System.out.println("numebr of robots is now " + Robot.ccount); } }
To fix this issue:
- Name the class and file the same.
- Make sure the case of both names is consistent.
See an example of the “Public class XXX should be in file” error. (@StackOverflow)
6. “Incompatible Types”
“Incompatible types” is an error in logic that occurs when an assignment statement tries to pair a variable with an expression of types. It often comes when the code tries to place a text string into an integer — or vice versa. This is not a Java syntax error. (@StackOverflow)
test.java:78: error: incompatible types return stringBuilder.toString(); ^ required: int found: String 1 error
There really isn’t an easy fix when the compiler gives an “incompatible types” message:
- There are functions that can convert types.
- The developer may need change what the code is expected to do.
Check out an example of how trying to assign a string to an integer created the “incompatible types.” (@StackOverflow)
7. “Invalid Method Declaration; Return Type Required”
This Java software error message means the return type of a method was not explicitly stated in the method signature.
public class Circle { private double radius; public CircleR(double r) { radius = r; } public diameter() { double d = radius * 2; return d; } }
There are a few ways to trigger the “invalid method declaration; return type required” error:
- Forgetting to state the type
- If the method does not return a value then “void” needs to be stated as the type in the method signature.
- Constructor names do not need to state type. But if there is an error in the constructor name, then the compiler will treat the constructor as a method without a stated type.
Follow an example of how constructor naming triggered the “invalid method declaration; return type required” issue. (@StackOverflow)
8. “Method <X> in Class <Y> Cannot Be Applied to Given Types”
This Java software error message is one of the more helpful error messages. It explains how the method signature is calling the wrong parameters.
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types; generateNumbers(); required: int[] found:generateNumbers(); reason: actual and formal argument lists differ in length
The method called is expecting certain arguments defined in the method’s declaration. Check the method declaration and call carefully to make sure they are compatible.
This discussion illustrates how a Java software error message identifies the incompatibility created by arguments in the method declaration and method call. (@StackOverflow)
9. “Missing Return Statement”
The “missing return statement” message occurs when a method does not have a return statement. Each method that returns a value (a non-void type) must have a statement that literally returns that value so it can be called outside the method.
public String[] OpenFile() throws IOException { Map<String, Double> map = new HashMap(); FileReader fr = new FileReader("money.txt"); BufferedReader br = new BufferedReader(fr); try{ while (br.ready()){ String str = br.readLine(); String[] list = str.split(" "); System.out.println(list); } } catch (IOException e){ System.err.println("Error - IOException!"); } }
There are a couple reasons why a compiler throws the “missing return statement” message:
- A return statement was simply omitted by mistake.
- The method did not return any value but type void was not declared in the method signature.
Check out an example of how to fix the “missing return statement” Java software error. (@StackOverflow)
10. “Possible Loss of Precision”
“Possible loss of precision” occurs when more information is assigned to a variable than it can hold. If this happens, pieces will be thrown out. If this is fine, then the code needs to explicitly declare the variable as a new type.
A “possible loss of precision” error commonly occurs when:
- Trying to assign a real number to a variable with an integer data type.
- Trying to assign a double to a variable with an integer data type.
This explanation of Primitive Data Types in Java shows how the data is characterized. (@Oracle)
11. “Reached End of File While Parsing”
This error message usually occurs in Java when the program is missing the closing curly brace (“}”). Sometimes it can be quickly fixed by placing it at the end of the code.
public class mod_MyMod extends BaseMod public String Version() { return "1.2_02"; } public void AddRecipes(CraftingManager recipes) { recipes.addRecipe(new ItemStack(Item.diamond), new Object[] { "#", Character.valueOf('#'), Block.dirt }); }
The above code results in the following error:
java:11: reached end of file while parsing }
Coding utilities and proper code indenting can make it easier to find these unbalanced braces.
This example shows how missing braces can create the “reached end of file while parsing” error message. (@StackOverflow)
12. “Unreachable Statement”
“Unreachable statement” occurs when a statement is written in a place that prevents it from being executed. Usually, this is after a break or return statement.
for(;;){ break; ... // unreachable statement } int i=1; if(i==1) ... else ... // dead code
Often simply moving the return statement will fix the error. Read the discussion of how to fix unreachable statement Java software error. (@StackOverflow)
13. “Variable <X> Might Not Have Been Initialized”
This occurs when a local variable declared within a method has not been initialized. It can occur when a variable without an initial value is part of an if statement.
int x; if (condition) { x = 5; } System.out.println(x); // x may not have been initialized
Read this discussion of how to avoid triggering the “variable <X> might not have been initialized” error. (@reddit)
14. “Operator ... Cannot be Applied to <X>”
This issue occurs when operators are used for types not in their definition.
operator < cannot be applied to java.lang.Object,java.lang.Object
This often happens when the Java code tries to use a type string in a calculation. To fix it, the string needs to be converted to an integer or float.
Read this example of how non-numeric types were causing a Java software error warning that an operator cannot be applied to a type. (@StackOverflow)
15. “Inconvertible Types”
The “inconvertible types” error occurs when the Java code tries to perform an illegal conversion.
TypeInvocationConversionTest.java:12: inconvertible types found : java.util.ArrayList<java.lang.Class<? extends TypeInvocationConversionTest.Interface1>> required: java.util.ArrayList<java.lang.Class<?>> lessRestrictiveClassList = (ArrayList<Class<?>>) classList; ^
For example, booleans cannot be converted to an integer.
Read this discussion about finding ways to convert inconvertible types in Java software. (@StackOverflow)
16. “Missing Return Value”
You’ll get the “missing return value” message when the return statement includes an incorrect type. For example, the following code:
public class SavingsAcc2 { private double balance; private double interest; public SavingsAcc2() { balance = 0.0; interest = 6.17; } public SavingsAcc2(double initBalance, double interested) { balance = initBalance; interest = interested; } public SavingsAcc2 deposit(double amount) { balance = balance + amount; return; } public SavingsAcc2 withdraw(double amount) { balance = balance - amount; return; } public SavingsAcc2 addInterest(double interest) { balance = balance * (interest / 100) + balance; return; } public double getBalance() { return balance; } }
Returns the following error:
SavingsAcc2.java:29: missing return value return; ^ SavingsAcc2.java:35: missing return value return; ^ SavingsAcc2.java:41: missing return value return; ^ 3 errors
Usually, there is a return statement that doesn’t return anything.
Read this discussion about how to avoid the “missing return value” Java software error message. (@coderanch)
17. “Cannot Return a Value From Method Whose Result Type Is Void”
This Java error occurs when a void method tries to return any value, such as in the following example:
public static void move() { System.out.println("What do you want to do?"); Scanner scan = new Scanner(System.in); int userMove = scan.nextInt(); return userMove; } public static void usersMove(String playerName, int gesture) { int userMove = move(); if (userMove == -1) { break; }
Often this is fixed by changing to method signature to match the type in the return statement. In this case, instances of void can be changed to int:
public static int move() { System.out.println("What do you want to do?"); Scanner scan = new Scanner(System.in); int userMove = scan.nextInt(); return userMove; }
Read this discussion about how to fix the “cannot return a value from method whose result type is void” error. (@StackOverflow)
18. “Non-Static Variable ... Cannot Be Referenced From a Static Context”
This error occurs when the compiler tries to access non-static variables from a static method (@javinpaul):
public class StaticTest { private int count=0; public static void main(String args[]) throws IOException { count++; //compiler error: non-static variable count cannot be referenced from a static context } }
To fix the “non-static variable ... cannot be referenced from a static context” error, two things can be done:
- The variable can be declared static in the signature.
- The code can create an instance of a non-static object in the static method.
Read this tutorial that explains what is the difference between static and non-static variables. (@sitesbay)
19. “Non-Static Method ... Cannot Be Referenced From a Static Context”
This issue occurs when the Java code tries to call a non-static method in a non-static class. For example, the following code:
class Sample { private int age; public void setAge(int a) { age=a; } public int getAge() { return age; } public static void main(String args[]) { System.out.println("Age is:"+ getAge()); } }
Would return this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method getAge() from the type Sample
To call a non-static method from a static method is to declare an instance of the class calling the non-static method.
Read this explanation of what is the difference between non-static methods and static methods.
20. “(array) <X> Not Initialized”
You’ll get the “(array) <X> not initialized” message when an array has been declared but not initialized. Arrays are fixed in length so each array needs to be initialized with the desired length.
The following code is acceptable:
AClass[] array = {object1, object2}
As is:
AClass[] array = new AClass[2]; ... array[0] = object1; array[1] = object2;
But not:
AClass[] array; ... array = {object1, object2};
Read this discussion of how to initialize arrays in Java software. (@StackOverflow)
Next Time
Now that we've covered compiler errors, next time we'll dive into the variety of runtime exceptions that might crop up to ruin your day. Just like this segment, they will include code blocks, explanations, and pertinent links to help fix your code as fast as possible.
Published at DZone with permission of Angela Stringfellow, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
|
https://dzone.com/articles/50-common-java-errors-and-how-to-avoid-them-part-1
|
CC-MAIN-2021-17
|
refinedweb
| 2,750
| 55.24
|
.
--trigger-happy
--trigger-happy
We value your feedback.
Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!
--trigger-happy
look into somewhere near the middle of the page, you'll find this:
FRNDINT Rounds ST to an integer
I'm not sure of the details, but i suggest reading some more about it.
--trigger-happy
Very important: select NO optimization otherwise the compiler is likely to optimize all or most of the computation.
#include <math.h>
float op1, op2; int Answer;
void compute() { op1 = 2.000; op2 = 1.618; Answer = round( op1 * op2 ) ; printf("Answer is: %d\n", Answer ); }
Now depending on the compiler, it may generate a call to round() external function or do the round() in-line.
If it calls a function, that doesnt help you , so you'll have to write your own round:
int round( float x ) { int Ans; if( x > 0.0 ) Ans = x + 0.5; else Ans = x - 0.5; return Ans; }
123: register double d =1.618;
00402333 mov dword ptr [ebp-14h],0F7CED917h
0040233A mov dword ptr [ebp-10h],3FF9E353h
124: int ix = (int)(d + d + 0.5);
00402341 fld qword ptr [ebp-14h]
00402344 fadd qword ptr [ebp-14h]
00402347 fadd qword ptr [__real@8@3ffe800000000000
0040234D call __ftol (004281ec)
00402352 mov dword ptr [ebp-18h],eax
The C++ code of that is
register double d =1.618;
int ix = (int)(d + d + 0.5);
To include assembler to C++ code you may use __asm keyword, e. g.
int power2(int num, int power)
{
__asm
{
mov eax, num ; Get first argument
mov ecx, power ; Get second argument
shl eax, cl ; EAX = EAX * ( 2 to the power of CL )
}
/* Return with result in EAX */
}
Regards, Alex
> shl eax, cl ; EAX = EAX * ( 2 to the power of CL )
(1) Works correctly only for "num"s and "powers"s greater or equal to zero.
(2) And gives no indication of overflow.
(3) And may give mysterious results if the optimizer is holding something in any part of ecx.
|
https://www.experts-exchange.com/questions/21338719/Multiplication-with-integers-and-decimals-and-rounding-numbers-in-assembly-masm.html
|
CC-MAIN-2018-05
|
refinedweb
| 347
| 70.84
|
Following up on Anders suggestion I found that you can use a control adapter on controlType EPiServer.UI.Hosting.VirtualPathControl
I'd originally had a page adapter on ~/secure/CMS/admin/FileManagement.aspx but that doesn't work when you want to catch the save from both the Admin and Edit modes.
To do this we made a control adapter for the EPiServer.UI.Hosting.VirtualPathControl control. And then spun the collection of controls to find the save event, and added our own function to that save events click handler.
I've uploaded both the AdapterMapping and the Control adapter to :
Just change SaveClicked to call whatever function you require. There is code to give you the current filename so you know which file is being edited.
There may be a more granular control to choose, but this worked fine for our needs. If you run into any issues let me know.
namespace Blend.PageAdapters { /// <summary> /// This PageAdapter is being made to piggyback the EPiServer FileManagement page. /// This specific adapter is looking for the Save button on the EditFileSummary /// portion of the page. /// </summary> public class EditFileSummary : ControlAdapter { /// <summary> /// Overloads the OnLoad event of the page this PageAdapter is piggybacking. /// This allows us to add methods to the eventhandlers on the actual page. /// </summary> /// <param name="e">Event Args.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); var saveButton = FindControl<ToolButton>(Page, null); if (saveButton == null) { return; // Error checking to make sure you bind to a TemplateButton } // Ensure we've bound to the save button if (saveButton.Text == "Save" && saveButton.ToolTip == "Save") { saveButton.Click += this.SaveClicked; // Attach our method to the save button's Click event handler } } /// <summary> /// A simple generic way to find controls on the page. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="control">The parent control.</param> /// <param name="id">The id of the control being looked for.</param> /// <returns></returns> private static T FindControl<T>(Control control, string id) where T : Control { T controlTest = control as T; if (controlTest != null && (id == null || controlTest.ID.Equals(id))) { return controlTest; } foreach (Control c in control.Controls) { controlTest = FindControl<T>(c, id); if (controlTest != null) { return controlTest; } } return null; } /// <summary> /// Displays every control on the page and its ID. Added for troubleshooting purposes in situations /// where you are trying to find a control on the page and the source is not readily available. Call this function and /// browse through the IDs then feed that ID into FindControl() to attempt to bind to it in this pageadapter. /// </summary> /// <param name="parent">Parent is the control whole children will be recursed.</param> /// <param name="depth">Tracks how deep the function is for display purposes.</param> private static void WriteControlValues(Control parent, int depth) { foreach (Control child in parent.Controls) { HttpContext.Current.Response.Write(new string('-', depth) + '>' + child + " - <b>" + child.ID + "</b><br />"); WriteControlValues(child, depth++); } } /// <summary> /// This function is the method we tie to the button click event on the save button. /// </summary> /// <param name="sender">The object which created the event.</param> /// <param name="e">The arguements passed in the event.</param> private void SaveClicked(object sender, EventArgs e) { var fileName = FindControl<HiddenField>(Page, "curFile"); var decoded = HttpContext.Current.Server.UrlDecode(fileName.Value); if (String.IsNullOrEmpty(decoded)) { return; } MetaIndexer.IndexFile(decoded); } } }
Does anyone know of an event that can be hooked when the user edits a File Summary?
I know you can hook the addition or the change of a file. But if someone right-clicks on a file and selects "Edit File Summary," they are not affecting the underlying file, so no event applies.
I suspect there is no such event or way of hooking this moment, but before I go do anything drastic, I thought I'd check if anyone else knows of some way to gracefully handle this.
|
https://world.optimizely.com/forum/developer-forum/Developer-to-developer/Thread-Container/2010/6/Is-there-an-event-that-fires-when-a-File-Summary-is-edited/
|
CC-MAIN-2021-39
|
refinedweb
| 633
| 58.08
|
Dan Short
It seems these days that every cool new technology
has an X in the name somewhere. And for some
reason this X inspires fear and dread when
combined with the Internet: XML, XSL, XPATH, XFORM
and, yes, even XHTML. But Extensible
HyperText Markup Language shouldn't cause you
to lose any sleep at night, especially when you've
got the XHTML capabilities of Dreamweaver MX on your
side. With these new features the only thing you'll
need to worry about when coding to this new standard
is what attributes you can and can't use.
I'm going to cover several topics in this article, including
how XHTML differs from standard HTML, how Dreamweaver MX
handles XHTML coding, the difference between Strict and
Transitional Document Type Definitions (DTDs) and finally
validating your code inside Dreamweaver.
Bear with me, it's worth it. I promise.
Standards: The truth is out there
To what extent are standards gospel? On one side you
have the "Code to Standards" group touting that
you should never use a tag or attribute not specified by
the W3C—and to hell with Netscape 4.x. On the other
side you have those individuals who don't care what the
standards are so long as the page appears correctly. I sit
somewhere in between.
I believe you should follow coding standards as closely
as possible for several reasons. First, it's easier to track
down your mistakes. Second, you'll make life easier for
you and other developers in the long run. But I also believe
some standards aren't ready for prime time and should be
avoided until browsers and the customers who use them (and
who talk with their credit cards) catch up.
Coding to standards makes it easier for you to find your
mistakes and quicker to fix them. If you run your code through
an online validator from the W3C or through Dreamweaver's
built-in validator, you'll have better luck tracking down
simple syntax issues. Maybe your tables or layers are set
up incorrectly from a display perspective, but at least
you can eliminate syntactical errors.
Because you're coding to a defined standard, emerging technologies
that follow those standards will be able to make better
use of your code with fewer hassles. Coding to standards,
in essence, "future-proofs" your pages to some degree. Coding
to standards also sends a message to browser vendors that
the standards are important to developers. We make the Internet
what it is, after all, so we can make our voices heard by
making it necessary for future browsers to follow published
standards.
How to spell XHTML
XHTML is HTML written as an XML application. This means
that XHTML documents must meet several requirements:
1.
Documents must be well-formed
2.
Tags and attributes must be in all lowercase
3.
For non-empty tags (<a>, <td> and <p>,
for example), end tags are required
4.
Attribute values must always be quoted
5.
Attribute minimization is not supported
6.
Empty elements (<hr> and <br>, for example)
must be properly closed
7.
The id attribute must be used instead of
the name attribute
8.
All images must have alt attributes
Allow me to explain these rules.
Documents must be well formed
Your XHTML documents must contain several standard tags
on the page. They must contain an <?xml?> version,
an XHTML DOCTYPE and an XML namespace in the <html>
tag. (I show an example of this later.)
All start tags must also have end tags and all tags must
be properly nested.
Correct (all tags nested):
<em>Some <strong>bold</strong>
and italic text.</em>
Incorrect (tags improperly nested):
<em> Some <strong>bold
and italic text.</em></strong>
Tags and attributes must be in all lowercase
In XHTML, <TABLE> is not the same as <table>
because XML is case-sensitive. For this reason all tags
and their attributes must be all lowercase.
Correct (tags all lowercase):
<a href="mylink.htm"
onclick="javascript:action();">My Link</a>
Incorrect (tags mixed lowercase and uppercase):
>
For non-empty tags, end tags are required
A non-empty tag is any tag with content between the start
and end, such as <a> or <p>. In XHTML these
must all contain proper end tags.
Correct (tags properly closed):
<p>My first paragraph</p>
<p>My second paragraph</p>
Incorrect (tags not closed):
<p>My first paragraph
<p>My second paragraph
Attribute values must always be quoted
All attributes in XHTML documents must be properly quoted.
Leaving the quotes out will invalidate the document.
Correct (attributes properly quoted):
<img src="myimage.gif"
id="myimage" alt="My Image" />
Incorrect (attributes missing some quotes):
<img src=myimage.gi" id=myimage
<img src=myimage.gi" id=myimage
Attribute minimization is not supported
Attribute minimization happens when only the value of the
attribute is added to the tag, without the attribute's name.
Correct (attribute value given):
<input type="checkbox"
checked="checked" />
Incorrect (attribute value missing):
<input type='checkbox" checked
/>
Empty elements must be properly closed
Empty elements are those tags that don't contain any content.
Examples include <br>, <hr> and <img>.
In order to properly close these tags, just add a space
followed by a "/" directly before the closing ">." This
ensures that older browsers that don't support XHTML (such
as Netscape 4.x) can still display the tags correctly. They'll
just ignore the extra space.
Correct (element closed properly):
<br />
Incorrect (element closed improperly):
<br>
<br/>
The id attribute must be used instead of the
name attribute
The name attribute for referencing elements on
your page is officially deprecated and may be removed in
future XHTML specifications. To plan for this, use the id
attribute in its place.
Correct (id attribute used):
Incorrect (deprecated name attribute used):
<img src="myimage.gif"
name="myimage" alt="My Image" />
<img src="myimage.gif"
name="myimage" alt="My Image" />
Jump in head first, but check the water
Once you get the basics down, you'll find that coding
to the new XHTML standard is quick and easy. Before you
jump into the XHTML ocean, however, take a minute to decide
which specification you want to code to. XHTML includes
both a Transitional DTD and a Strict DTD. (A DTD defines
the structure and legal elements of an XML document.) The
main difference between the two is which attributes are
allowable. They both follow the same syntactical rules I
specified in the previous section, but the Strict DTD is
missing several attributes we all got used to in HTML.
For example, the following attributes are no longer allowed
in the XHTML Strict DTD:
onResize
Type attributes on lists
Target attributes on <a> tags
Width attributes on tables
Border on <img> tags
That's just a partial list of some of the attributes removed.
The reasoning for this is that these types of attributes
should be defined in style sheets. There's a list-type declaration
in Cascading Style Sheets (CSS) that you should use in place
of the type attribute in <ul> tags. The border
attribute and width declaration in tables were
removed because there are associated CSS attributes for
those purposes as well.
If you decide you can't live without those attributes,
or your audience's browsers don't t support the necessary
CSS styles, you may want to code to the Transitional DTD
until the browsers catch up. If you'd rather go all the
way and live with the few problems that Netscape 4.x and
some Microsoft IE browsers exhibit with the advanced styles,
then the Strict DTD may be more to your liking.
To give you an example of the differences between the
two DTDs, I'll show you how to build two very simple pages.
The first page will be coded to the Transitional DTD; then
you'll convert that document to the Strict DTD.
Movin' on up...to the XHTML side
The XHTML Transitional DTD's purpose is exactly what
the name implies. It's designed for sites in the process
of moving to the full XHTML Strict DTD. The Transitional
DTD includes many of the original HTML attributes that are
no longer in the XHTML Strict DTD (such as the target
attribute for <a> tags). This allows you to continue
working (almost) as you always have been without stressing
over missing attributes in your document.
The page I show you is extremely simple, just so you can
see how Dreamweaver MX manages all those new requirements
you have to follow. The result looks something like this
(mouseover the button to see the effect):
Do you really know...
That's all there is to it. This simple example shows you
how Dreamweaver MX supports the new XHTML requirements.
Before you get started, save the following two images to
your desktop by right-clicking each image (or Control+Click
on a Macintosh) and saving the image to your desktop:
The first thing you need to do is start a blank document.
Use File > New instead of the Site panel, because creating
a new document in the Site panel doesn't give you the option
to make the document XHTML-compliant:
1
Select File > New.
2
Choose Basic in the Category box on the left and
HTML in the Basic Page box on the right.
3
In the lower-right corner, be sure the "Make
Document XHTML Compliant" option is checked.
4
Click the Create button.
After you've clicked Create, you'll see a fully XHTML Transitional–compliant
document. Switch to Code view (Ctrl+`) to see what you've
got:
<>
Allow me to explain this code:
<?xml version="1.0"
encoding="iso-8859-1"?>
This tells XML-compliant browsers (IE5 and later and
Netscape 6) which version of XML to use when processing
this page.
<?xml version="1.0"
encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "">
This is the default DOCTYPE used by Dreamweaver MX.
It's the XHTML Transitional DTD and should only be
changed if you want to move to the Strict DTD. I'll
tell you how to change this default later on in the
"Make that page behave" section.
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "">
<html xmlns="">
This is your standard <html> tag with the xmlns
(XML NameSpace) attribute added. Namespaces give you
a quick way to qualify the names used in XML documents.
This is great for a quick reference, allowing you
to quickly view the XHTML
specification that the document was coded against.
<html xmlns="">
Now that you have your document ready, you can start designing
your page as normal. Switch to Code and Design view so you
can see what Dreamweaver is doing to the code. Type this:
Do you really know...
and press Shift+Enter to insert a line break. Notice that
when you press Shift+Enter, instead of getting the standard
<br> tag, you get the XHTML equivalent: <br />.
Because your document has an XHTML DTD, Dreamweaver MX knows
how to close the empty tags.
To add your image, press Ctrl+Alt+I or click the Image
icon in the Common category of the Insert panel. Find the
daddy.gif image you saved to your system earlier and click
OK. Looking in the Code view of your page, you should now
see this:
<img src="mmdesdev/daddy.gif"
width="150" height="40" />
Click on the image to bring up the image properties in
the Property inspector and give your image the name "yourdaddy":
Check the Code view again and you'll see that Dreamweaver
MX now adds both the name attribute and the id
attribute to the image. The name attribute ensures
backwards compatibility to browsers that may not recognize
the id attribute yet. When you use the Transitional
DTD, the name attribute will still validate, but
you'll need the id attribute to complement it.
Your code should now look like this:
<img src="mmdesdev/daddy.gif"
name="yourdaddy" width="150" height="40"
id="yourdaddy" />
Next add your Swap Image behavior. Select the image and
open your Behaviors panel (Shift+F3). Click the Add button
and choose Swap Image. Set the source to xhtml.gif and make
sure Preload Images and Restore Images onMouseOut are checked.
Click OK and you'll end up with the following code:
<body onload="MM_preloadImages('mmdesdev/xhtml.gif')">
Do you really know...<br />
<a href="javascript:;" onmouseover="MM_swapImage('yourdaddy','','mmdesdev/xhtml.gif',1)"
onmouseout="MM_swapImgRestore()" target="_blank">
<img src="mmdesdev/daddy.gif"
name="yourdaddy" width="150" height="40"
border="0" id="yourdaddy" alt="Who's
your daddy?" /></a>
</body>
Change the target to "_blank" to force a new window for
your link and be sure to add a descriptive alt
tag. Note that the onload, onmouseover
and onmouseout attributes are now all lowercase.
Adding a behavior to a standard HTML 4.0 page will write
the attributes as onLoad, onMouseOver and onMouseOut. Just
one more thing you don't have to think about.
That's it! You've just created your first fully valid XHTML
document using Dreamweaver MX. Next you'll convert the document
to the Strict DTD.
Make that page behave
If you feel it's time to get tough with your pages and
make sure they hold to the XHTML Strict DTD, there are just
a few things you need to change in your current page.
Dreamweaver MX isn't going to do all the work for you on
this one. Even if you're using the Strict DTD, Dreamweaver
MX will allow—and continue to add—attributes
not allowable in the Strict DTD. To convert your document,
change your DOCTYPE declaration and remove a few unsupported
attributes. Replace those now-missing attributes with some
simple CSS styling.
Here's how you change your DOCTYPE statement. Replace the
Transitional DTD with the new Strict DTD:
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
One difference to note between the stock DTD that Dreamweaver
MX inserts and your new Strict DTD is the lack of a specific
URL for the DTD. This prevents some rendering
bugs in IE6 that happen when DTDs contain URLs.
Next remove all attributes that are illegal in the Strict
DTD, such as target attributes on links and borders on images.
Remember that once you add a link to an image you'll need
to follow up and remove the "border='0'" part. You'll also
need to remove the language attribute from the <script>
tag. Your content will also need to be wrapped in a container
of some sort (such as a <p> tag or <div>). You
can determine what you've missed by using the built-in validator
that I'll cover a bit later. Your new code for your entire
page is going to look like this:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html xmlns="">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<script type="text/javascript">
...
</script>
</head>
<body onload="MM_preloadImages('mmdesdev/xhtml.gif')">
<p>Do you really know...<br />
<a href="javascript:;" onmouseover="MM_swapImage('yourdaddy','','mmdesdev/xhtml.gif',1)"
onmouseout="MM_swapImgRestore()"><img src="mmdesdev/daddy.gif"
width="150" height="40" id="yourdaddy"
alt="Who's your daddy?" /></a>
</p>
</body>
</html>
Now that you have your page validated with the Strict DTD,
you have a nasty border around your image:
To remove this border, add a style to your page that says
"set the border of any image inside an <a> tag
to 0." Open the CSS panel (Shift+F11) and click the
Add Style button. In the New CSS Style dialog box, click
Use CSS Selector, click This Document Only, and enter a
img in the Selector box. Click OK.
In the CSS Style Definition dialog box that appears, click
the Border category in the left pane and set the Top border
to 0. Leave the Same for All checkboxes checked and click
OK.
You're all done. You won't see the border disappear in the
Dreamweaver MX window, but uploading the page will get rid
of the border in IE5 and later and in Netscape 6. Nestcape
4.x continues to show the border surrounding the image,
but this is the tradeoff you'll have to make.
Validating your code
Now that you've got everything put together, determine
whether you've caught all those border attributes and given
every image an alt attribute (even if it's an empty
one). To do this, use the new Results panel in Dreamweaver
MX. To show the Validation tab, choose Window > Results
> Validation or press Ctrl+Shift+F7 (or Command+Shift+F7
on a Macintosh). The Results panel looks like this:
In order to validate your document, click the Play button
(the green triangle) and choose Settings from the drop-down
menu. This opens the Validation category of the Dreamweaver
Preferences. Make sure you're actually checking the document
against the XHTML DOCTYPE. In the Settings dialog box choose
which XHTML DOCTYPE you want to check against.
Once you're sure you have your preferences right, click
OK, click the Play button again and choose Validate Current
Document from the drop-down menu. The Results panel will
give you a wealth of information regarding each error, including
the file the error is in, the line number, and what the
error is. Double-click each line to go directly to that
line in Code view so you can make your corrections.
Converting old sites
Dreamweaver MX gives you an easy way to bring your old
websites into the next century with its Convert to XHTML
command. This little wonder adds the necessary DTDs to convert
all your behaviors to the proper case and attempt to add
alt attributes to any images missing them. If there
are any problems with the conversion, Dreamweaver MX provides
a prompt with the details so you know what it didn't cover.
XHTML is the first step to a more rigid and valid coding
style. When the next fancy browser comes out, you're less
likely to end up going back through old sites to fix outdated
code. Dreamweaver MX makes coding to the Transitional DTD
a breeze, and with just a little extra work, you can make
sure it will validate to the Strict DTD as well. Whichever
standard you decide to code for is entirely dependent on
your client, site and attitude. But once you've made the
choice, staying on course is simple.
About the author
Daniel Short, Chief Designer of Web
Shorts Site Design, designs and develops websites in
Portland, Oregon, and the rest of the world. A Team Macromedia
member devoted to teaching developers how to use best practices,
Daniel also runs Short Order Software, a venture that sells
pre-made apps and modifications as well as gives away free
extensions.
Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy (updated 07-08-2008).
Search powered by Google™
|
http://www.adobe.com/devnet/dreamweaver/articles/code_standards.html
|
crawl-002
|
refinedweb
| 3,192
| 63.8
|
Mark,
Thanks for the feedback. Is is better form to back-out these changes and
apply a new patch, or to simply make these changes to trunk and commit them?
Thanks,
-chris
On 12/5/2010 12:31 PM, Mark Thomas wrote:
> On 03/12/2010 16:07, schultz@apache.org wrote:
>> Author: schultz
>> Date: Fri Dec 3 16:07:50 2010
>> New Revision: 1041892
>>
>> URL:
>> Log:
>> Fixed bug 48692: Provide option to parse application/x-www-form-urlencoded PUT requests
>
> Some minor comments in-line.
>
>> + protected HashSet parseBodyMethodsSet;
> This needs to use generics (same for subsequent use later on in the class).
>
>> + public String getParseBodyMethods()
>> + {
>> + return (this.parseBodyMethods);
>> + }
> The Tomcat code style is to have brackets at the end of the previous line.
>
>> + if(methodSet.contains("TRACE"))
>> + throw new IllegalArgumentException("TRACE method MUST NOT include an
entity (see RFC 2616 Section 9.6)");
> This should use the StringManager for i18n support.
>
>> + public boolean isParseBodyMethod(String method)
> This method could (should?) be protected rather then public.
>
>> - if (!getMethod().equalsIgnoreCase("POST"))
>> + if(!getConnector().isParseBodyMethod(getMethod()))
> The Tomcat code style is to have a space after the if.
>
>> <changelog>
>> + <update>
>> + <bug>48692</bug>: Provide option to parse
>> + <code>application/x-www-form-urlencoded</code> PUT requests.
(schultz)
>> + </update>
>> <fix>
>> <bug>8705</bug>: <code>org.apache.catalina.SessionListener</code>
now
>> extends <code>java.util.EventListener</code>. (markt)
> Bugs get added to the changelog in ascending numerical order within the
> appropriate section.
>
>> + <attribute name="parseBodyMethods" required="false">
>> + <p>A comma-separated list of HTTP methods for which request
>> + bodies will be parsed for request parameters identically
>> + to POST. This is useful in RESTful applications that want to
>> + support POST-style semantics for PUT requests.
>> + Note that any setting other than <code>POST</code> causes Tomcat
>> + to behave in a way that violates the servlet specification.
>> + The HTTP method TRACE is specifically forbidden here in accordance
>> + with the HTTP specification.
>> + The default is <code>POST</code></p>
>> + </attribute>
> "violates" is probably too strong a term here. There is some wiggle
> room in the language. I would suggest "goes against the intent" is
> probably closer.
>
> Mark
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
> For additional commands, e-mail: dev-help@tomcat.apache.org
>
|
http://mail-archives.apache.org/mod_mbox/tomcat-dev/201012.mbox/%3C4CFBE40B.70301@christopherschultz.net%3E
|
CC-MAIN-2014-23
|
refinedweb
| 369
| 50.73
|
How to collect EC2 metrics
When it comes to collecting EC2 metrics and events, you will likely make use of Amazon’s CloudWatch service. But even from that one source, there are a few ways to get data. Each of these methods will enable you to collect the same metrics. You can access CloudWatch metrics through:
- the CloudWatch web console,
- the AWS command line tool, or
- a program or third-party monitoring service that connects to the CloudWatch API.
You can supplement the available CloudWatch metrics by running a monitoring agent that pulls system-level information that CloudWatch may not collect directly from your EC2 instances. We will go over all of these approaches in this post.
But first: Are you you? EC2 APIs. See the AWS documentation for information.
Regional differences
As mentioned in part one of this series, you can launch EC2 instances in different geographical regions, each of which contains multiple availability zones. Regions and the resources hosted in each are isolated from one another. One consequence of this is that you can only view one region’s metrics at a time through CloudWatch unless you create dashboards that pull metrics in from multiple regions. Otherwise, you must specify which region’s instances you want to view. How to do this is described below.
Watching the clouds
CloudWatch collects metrics through the hypervisor from any AWS services you may use in your infrastructure. Namespaces allow you to specify which service (e.g. EC2) you want to view metrics for. As mentioned in part one of this series, by default CloudWatch publishes metrics at five-minute intervals. If detailed monitoring is turned on, this granularity increases to every minute, but certain metrics are only available with basic monitoring, and others can only be aggregated at a five-minute frequency even with detailed monitoring enabled. Custom metrics, which will be covered later, can be forwarded at a much higher frequency, though that can incur additional charges.
To help you drill down into specific parts of your EC2 infrastructure, CloudWatch provides a few means of filtering and aggregating data: dimensions, periods, and statistics.
Dimensions
Dimensions are preset groupings of instances. Selecting a dimension will filter your metrics to isolate that particular group. The EC2 namespace provides the following dimensions:
InstanceId: Isolates data from a specific instance.
AutoScalingGroupName: Filters instances by their Auto Scaling group, if they are assigned to one.
ImageId: Filters instances by their Amazon Machine Image (AMI). This dimension is only available for instances with detailed monitoring enabled.
InstanceType: Filters instances by instance type. This dimension is only available for instances with detailed monitoring enabled.
Periods
The period sets the timespan, in seconds, over which CloudWatch will aggregate a metric into data points. The larger the period, the less granular your metric data will be. Note, however, that aggregation periods shorter than five minutes are only available with detailed monitoring, and periods shorter than one minute are only possible with custom metrics.
Statistics
Statistics are calculations used to aggregate data over the collection period. The following options are available:
Minimum,
Maximum,
Sum,
Average,
SampleCount (the number of data points used for the aggregation), and
pNN.NN. The
pNN.NN aggregation returns any user-specified percentile, for example
p95.00, which provides useful data for monitoring median values, outliers, and worst-case metrics.
Methods for collecting EC2 metrics
As mentioned above, there are several ways to use CloudWatch to view your EC2 metrics: via the AWS web console, via the AWS CLI, and via a third-party tool that integrates with the CloudWatch API.
Metrics via AWS console
The main CloudWatch page provides a few options for monitoring your AWS infrastructure. You can:
- browse available metrics for a quick overview of your instances,
- create dashboards to track multiple metrics, and
- set alarms to notify you if metrics pass fixed thresholds.
Browse metrics
In the CloudWatch console, you can use the region selector to specify which region you want to view metrics for. Then, select any AWS namespace to see metrics from that service or source. Within the EC2 namespace, you can drill down to a dimension or single instance and choose which of the available metrics you want to graph. could view CPU usage for different instance types at the same time, or compare network throughput between Auto Scaling groups.
Dashboards
For a more comprehensive picture of your EC2 instances, EC2 metrics. Alarms can be set against any upper or lower threshold and will trigger whenever the selected metric, aggregated across the specified dimension, exceeds (or falls below) that threshold for a set amount of time. In the following example, we are creating an alarm that will notify us whenever the average CPU utilization across all m3.medium instances equals or exceeds 90 percent over a five-minute window (one monitoring interval, under CloudWatch basic monitoring).
You can also set alarm actions such as stopping or rebooting instances when the alarm triggers. For example, you can create an alarm that stops any instance that has CPU utilization of less than 5 percent for an hour in order to avoid paying for unused resources.
Status checks
Instance status checks are reported from EC2 directly instead of through CloudWatch. So, you have to view them via the EC2 dashboard. The instance list view includes a quick summary of how many status checks each instance has passed. After selecting an instance, you can then click on the
Status Checks tab in order to see specifically if both the system and instance checks have passed.
Metrics via CLI
Once you install the AWS CLI tool, you can query the full AWS API from the command line. The metrics and status checks described in the first part of this series fall under two different AWS namespaces, CloudWatch and EC2, so you’ll need two different CLI commands to request them. In both cases, you can specify which region you want to query in two ways. First, you can set the default region environmental variable,
AWS_DEFAULT_REGION (this is also set when you initially configure the AWS CLI tool). Or second, you can include the
--region parameter with the command.
EC2 metrics
Most EC2 metrics come from the CloudWatch namespace via the
get-metric-statistics command. CloudWatch pulls metrics from other AWS services, so you must point the
get-metric-statistics to the EC2 namespace so it knows which metrics you are requesting. In addition to namespace, the command requires four other parameters:
metric-name
start-time(ISO 8601 UTC format)
end-time(ISO 8601 UTC format)
period(in seconds)
You also must include either a
statistics parameter, or the
extended-statistics parameter if you want to specify a percentile. For example:
aws cloudwatch get-metric-statistics --metric-name CPUUtilization --start-time 2017-12-01T12:30:00 --end-time 2017-12-01T13:30:00 --period 900 --statistics Average --namespace AWS/EC2
This requests average CPU usage across all instances within the default region (as no dimensions were included that would filter the search) for the specified hour with a granularity of 15 minutes. This will yield:
{ "Datapoints": [ { "Timestamp": "2017-12-01T12:30:00Z", "Average": 23.545234408687673, "Unit": "Percent" }, { "Timestamp": "2017-12-01T13:15:00Z", "Average": 23.607252374630786, "Unit": "Percent" }, { "Timestamp": "2017-12-01T12:45:00Z", "Average": 23.575792401181392, "Unit": "Percent" }, { "Timestamp": "2017-12-01T13:00:00Z", "Average": 23.639131672378156, "Unit": "Percent" } ], "Label": "CPUUtilization" }
Note that CloudWatch’s JSON response is not necessarily ordered chronologically when it returns more than one datapoint.
EC2 status checks
Instance status checks do not come from the CloudWatch namespace but instead are reported from the EC2 namespace using the
describe-instance-status command. Without any parameters, this command will return the status and any associated events for all running instances (within the default region). You can include a list of one or more instance IDs, or you can provide a list of filters to return. For example, you can request only instances from a specific availability zone, or only instances that have an impaired instance status. The following command requests statuses for two specific instances via their instance IDs:
aws ec2 describe-instance-status --instance-ids i-07e36h4237d2as5hd i-0fw72f1c9e53d62r9
This returns:
{ "InstanceStatuses": [ { "InstanceId": "i-0fw72f1c9e53d62r9", "InstanceState": { "Code": 16, "Name": "running" }, "AvailabilityZone": "us-east-1e", "SystemStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] }, "InstanceStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] } }, { "InstanceId": "i-07e36h4237d2as5hd", "InstanceState": { "Code": 16, "Name": "running" }, "AvailabilityZone": "us-east-1e", "SystemStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] }, "InstanceStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] } } ] }
If there are any scheduled events associated with the instance you are checking, those will also appear in the response to
describe-instance-status.
Metrics via API
Amazon provides SDKs for major programming languages and mobile platforms to create applications and libraries that can communicate with AWS via specific APIs. A number of third-party monitoring products and tools take advantage of these APIs to pull and aggregate metrics automatically.
If you want to access the API directly, refer to the individual SDK documentation for information on how to make requests to the CloudWatch and EC2 namespaces for metrics and status checks. Amazon also supports a basic REST API that accepts HTTP and HTTPS requests.
Getting a fuller picture
CloudWatch provides a convenient way to collect EC2 metrics and get a general overview of the health of your instances, and it is fully integrated into the AWS ecosystem. But because it gathers metrics via a hypervisor instead of reporting from your instances themselves, it doesn’t collect all the resource metrics that you might want to keep an eye on, notably memory usage statistics.
One way to fill this gap is through the use of custom metrics, which you can forward to CloudWatch and monitor using the same methods outlined above. Additionally, custom metrics may be collected with much finer granularity—defaulting to one-minute resolution but with the ability to go as high as one second. (Note that fees will apply.) Amazon also provides sample scripts that use this custom metric mechanism to report memory, swap, and disk space statistics for Linux-based instances, although those scripts are not officially supported by AWS.
To gain deeper visibility into your instances, as well as your EC2-based applications and all the infrastructure components that support them, you can use a comprehensive monitoring service that integrates with EC2 and the rest of your stack. This provides a complete view into your infrastructure and applications, with the potential added benefit of increased resolution, because metric collection is not restricted by CloudWatch’s hypervisor.
In the third and final post of this series, you will learn how to use Datadog to set up comprehensive, high-resolution monitoring for your EC2 instances and the rest of your stack.
|
https://www.datadoghq.com/blog/collecting-ec2-metrics/
|
CC-MAIN-2018-17
|
refinedweb
| 1,792
| 50.87
|
I'm having a problem with a warning message and would be greatfull if someone could help me get it removed. The program runs but it has a warning message that I can't seem to get rid of. I am using the latest version of Dev-C++. The code is:
#include <iostream>
#include <stdlib.h>
int main()
{
using std::cout;
/* this is a comment
and it extends until the closing
star-slash comment mark */
cout << "Hello World!\n";
// this comment ends at the end of the line
cout << "That comment ended!\n";
// double slash comments can be alone on a line
/* as can slash_star comments */
system("pause");
return 0;
}
And Here is my compile log:
Compiler: Default compiler
Executing g++.exe...
g++.exe "C:\Dev-Cpp\C++ In 21 Days Demostrations\Listing 2.5.cpp" -o "C:\Dev-Cpp\C++ In 21 Days Demostrations\Listing 2.5.exe" -I"C:\DEV-CPP\include\c++\3.3.1" -I"C:\DEV-CPP\include\c++\3.3.1\mingw32" -I"C:\DEV-CPP\include\c++\3.3.1\backward" -I"C:\DEV-CPP\lib\gcc-lib\mingw32\3.3.1\include" -I"C:\DEV-CPP\include" -L"C:\DEV-CPP\lib"
C:/Dev-Cpp/C++ In 21 Days Demostrations/Listing 2.5.cpp:19:2: warning: no newline at end of file
Execution terminated
Compilation successful
Thanks Bondojoe
Have you tried adding in a newline at the end of the file? I know it sounds stupid, but it's worth a try. Apart from that, there isn't any syntactical problem with your code...nothing that would give you a compiler warning.
Did you copy and paste the code, or download it from somewhere? That could be the problem (although I really can't see why it would be :P) Hope that helps you.
ac
Thanks alot that was the problem. I needed a new line at the end. No warning messages now.
Forum Rules
|
http://www.antionline.com/showthread.php?261826-warning-no-newline&p=807755
|
CC-MAIN-2015-22
|
refinedweb
| 324
| 66.94
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
How do I get the user avatar in the kanban view of a custom module?
Hey guys, I'm trying to create a custom module and every thing works fine so far. My only problem is, that I'm not able to show the user avatar in the kanban view. I only get a randow image (maybe my function is wrong?) I trying to get the user avatar from res.partners.
Here the pythonscript:
def _get_user_image(self, cr, uid, ids, field, arg, context=None): res = {} ctx = {} records = self.browse(cr, uid, ids, context=context) for record in records: res[record.id] = record.user_id.pool.get('res.partner')._get_default_image(cr, uid, False, ctx, colorize=True) return res
#...
_columns = { 'image' : fields.function(_get_user_image, type="binary", method=True, string='Image', readonly=True), }
The view.xml
<record model="ir.ui.view" id="view_gcon_access_kanban"> <field name="name">gcon.access.kanban</field> <field name="model">gcon.access</field> <field name="arch" type="xml"> <kanban> <field name="user_id"/> <field name="name"/> <field name="count_contact"/> <field name="count_devices"/> <field name="image"/> <templates> <t t- <div class="oe_kanban_vignette oe_semantic_html_override"> <a type="open"> <img t- </a> <div class="oe_kanban_details"> <h4> <a type="open"> <field name="user_id"/> (<field name="name"/>) </a> </h4> <group> Contacts: <field name="count_contact"/><br /> Devices: <field name="count_devices"/> </group> </div> </div> </t> </templates> </kanban> </field> </record>
What of these codes is wrong? In the xml I tried several tag, but nothing worked or rather displayed the wrong image. We are using the openERP v7. Best regards
Dy
|
https://www.odoo.com/forum/help-1/question/how-do-i-get-the-user-avatar-in-the-kanban-view-of-a-custom-module-32703
|
CC-MAIN-2017-09
|
refinedweb
| 279
| 59.7
|
Feature #15352
Mandatory block parameters
Description
There are too many block parameter assertions (it's kind of idioms:
raise NoBlockGiven unless glock_given?).
It's very useful if there's a syntax to declare mandatory block parameters, such as:
def foo(&!block) block.call end foo() # raises ArgumentError "in `foo`: no block given"
Updated by shevegen (Robert A. Heiler) over 1 year ago
This is an interesting suggestion in the sense that block parameters,
or rather, blocks as a whole, are a bit like additional arguments to
every method in ruby, at all times, optional; but they are also quite
special entities in ruby. For example, to use .call on a proc; is a
bit similar to yield, and unbinding/rebinding a method and passing
this as a block to another method.
Typically if we have a method such as foo(), in ruby we can call it
via:
foo() foo foo { :something }
All three ways are more or less the same, except for the last which
pushes more information onto the method foo; but that information
may not be evaluated within the method body (of foo).
I think this is where matz should come in since he designed ruby
and added blocks, so he knows best how blocks are seen (from within
ruby itself). I could see it go either way with statements, where
ruby users may say that block parameters should behave like regular
parameters of methods; or that blocks are special and so block
parameters should also be special. I myself have no real preference
either way. I think backwards compatibility and backwards behaviour
may be a reason in retaining the present behaviour, though; but again,
I am neutral on the feature suggestion in itself. We can also reason
that this would allow for more functionality, since he would gain the
ability to cause blocks to raise an error, in this case an
ArgumentError.
There is, however had, one part I slightly dislike, and that is the
syntax. I don't have an alternative suggestion, which is bad, but
I don't like the close associoated of &! there. Perhaps my opinion
is partially affected by other unrelated suggestions, e. g. to add
arguments to &: invocation styles, such as &.: or variants that
use even more characters. But anyway, I guess the syntax is partially
separate from the suggested functionality, so I think it may be
best to ask matz about the principle situation first, that is whether
block arguments should/could behave like regular methods too (specifically
whether they should be able to raise ArgumentError, if a ruby user wants
to have it that way).
One last point; not sure if they are worth mentioning but I will mention
it, if only for symmetry:
In regular parameters signature we have something like:
def foo(bar = '')
def foo(bar)
In the second case we must supply an argument; in the first, the default
will be to an empty String ''. I understand that this can not be the same
for blocks, at the least not without changing how they behave, but I wanted
to point this out because to me this is quite different in behaviour and
syntax, from the proposed &! or any similar proposal - I guess it all has
to be different to the two method definitions above.
Anyway, I wanted to write a bit more, but I tend to write too much so I will
stop here.
Updated by sawa (Tsuyoshi Sawada) over 1 year ago
I don't find this feature useful. If you wanted to raise an error when no block is given, all you have to do is call
yield within the method body, which will not be an extra code if you are going to use the block somewhere in the method body.
def foo ... yield ... end foo # >> `foo': no block given (yield) (LocalJumpError)
And in case you want to return an error with a different message, then that is when you want to implement your custom validation clause in your code like the ones found in the examples that you have searched.
Also available in: Atom PDF
|
https://bugs.ruby-lang.org/issues/15352
|
CC-MAIN-2020-16
|
refinedweb
| 682
| 62.21
|
Might be a silly question but I'm a bit confused here.
I have a parent entity which contains a list of children.
public class Parent { public int Id { get; set; } public List<Child> Children { get; set; } } public class Child { public int Id { get; set; } }
EFcore will create a
ParentId as a foreign key in the table
Child.
Now, let's say I want to retrieve all the children that have a specific Parent, how should I do it ? The
ParentId is not available in the
Child object.
Therefore, I cannot do something like:
var result = model.Child.Where(child => child.ParentId == 3);
I could add the
ParentId property to the child in the entity, but I really don't want this property to be assigned manually. And if I set it as readonly by specifying the getter only, the migration doesn't work anymore.
EF Core allows you to access the associated shadow property in LINQ to Entities query using the EF.Property method:
Addresses a given property on an entity instance. This is useful when you want to reference a shadow state property in a LINQ query. Currently this method can only be used in LINQ queries and can not be used to access the value assigned to a property in other scenarios.
All you need to know is the name and the type - in your case they are "ParentId" and
int? (optional):
var result = model.Child.Where(child => EF.Property<int?>(child, "ParentId") == 3);
I would recommend you have both the references (child-parent and parent-children) in the respective classes as provided in @ScotG answer.
However,since you dont want that, in EF using lazy loading you can do something like
model.Parents.Find(3).Children since from the Parent class you have the references of its children.
|
https://entityframeworkcore.com/knowledge-base/56367475/entity-framework-core---access-parent-from-child
|
CC-MAIN-2022-21
|
refinedweb
| 302
| 63.29
|
Originally posted by Dirk Schreckmann: Moving this to the Threads and Synchronization forum...
abhay bansal wrote:
Wont this be called one by one by the multiple threads? This method being static, wont it have only a single copy accessed by all the threads.
Wont the threads wait if a large load is put onto the function?
Pho Tek wrote:Jim,
Are you saying then that if I have a class
skeleton of this sort:
public class Foo{
static int i;
public static void doSomething(){
// do something with i
}
}
Then i is actually not thread safe. One way
to make this thread safe would be to changed
the i member variable into an instance variable.
Right ?
Thanks
Pho
abhay bansal wrote:I have seen a performance degradation using static methods(Class level) as compared to the non-static methods(Object level) for the same number of threads.
Steve Luke wrote:Over about 30 or so runs each, static code ran 30 ms slower than non-static code (on average). If you took any 4 trials and grouped them together then averaged those runs you would see the same 30 ms difference between static and non-static runs.
My guess would have been there was no difference so I am thoroughly surprised to see that there is an measurable (if small) difference between them. Still, I think this comes under the micro-optimization category. , I would let the class design and usage dictate my choice between static / non-static rather than possible speed gains. I don't understand where that speed gain is coming from but it is minor and it is may be runtime specific.
|
http://www.coderanch.com/t/231982/threads/java/Static-Methods-local-variables-Thread
|
CC-MAIN-2015-27
|
refinedweb
| 274
| 67.89
|
Sometimes you want to set some data in one of the early handler phases and make it available in the latter handlers. For example, say you set some data in a TransHandler and you want the PerlHandler to be able to access it as well. maintained for the life of the current request and are deleted when the transaction is finished. The notes( ) method is used to manipulate the notes table, and a note set in one Apache module (e.g., mod_perl) can later be accessed in another Apache module (e.g., mod_php).
The notes( ) method accepts only non-reference scalars as its values, which makes this method unfit for storing non-scalar variables. To solve this limitation mod_perl provides a special method, called pnotes( ), that can accept any kind of data structure reference content handler:
package Book::Auth; ... sub handler { my $r = shift; ... $r->notes('answer',42); ... } running in the mod_perl domain, however, you can always keep the notes in the parent request notes table and access them via the main( ) method:
$r->main->notes('answer');
Similarly to the notes, you may want or need to use the Apache environment variables.
<!--#if expr="$hour > 6 && $hour < 12" --> Good morning! <!--#elif expr="$hour >= 12 && $hour <= 18" --> Good afternoon! <!--#elif expr="$hour > 18 && $hour < 22" --> Good evening! <!--#else --> Good night! <!--#endif -->.
|
http://etutorials.org/Programming/Practical+mod_perl/Part+III+Databases+and+mod_perl/Chapter+18.+mod_perl+Data-Sharing+Techniques/18.2+Sharing+Data+Between+Various+Handlers/
|
CC-MAIN-2017-04
|
refinedweb
| 220
| 72.36
|
A GraphQL endpoint and authentication backend to signup or login a valid user access token from Facebook
Project description
Django Facebook Login
django-facebook-login provides an authentication backend and a GraphQL mutation
that takes a Facebook user-access-token and the user's email and then does one
of the following:
- Connect existing Django user with their Facebook account
- Login existing, already connected Django user
In all cases, the user will be authenticated afterwards. This means, unlike most other custom authentication backends, this backend will create a new user if the given credentials (Facebook email + Facebook user access token) are not known, yet.
Make sure you read the
Noteworthy Things below before you decide to use this
library.
Quick start
Add "facebook-login" to your INSTALLED_APPS setting like this:
INSTALLED_APPS = [ ... 'facebook-login', ]
Add the
FacebookAuthBackendto your
AUTHENTICATION_BACKENDSsetting:
AUTHENTICATION_BACKENDS = ( ..., "facebook_login.auth_backends.FacebookAuthBackend", )
Hook up the mutation in your GraphQL schema:
# in your main `schema.py`: import graphene from facebook_login import schema as fb_login class Mutation( ... fb_login.Mutation, graphene.ObjectType, ): pass class Queries(...): pass schema = graphene.Schema(query=Queries, mutation=Mutation)
Run
python manage.py migrateto create the
FacebookAccounttable.
Configure the app in your
local_settings.py:
# Get these values from FB_LOGIN_APP_ID = 'YOUR APP ID' FB_LOGIN_APP_SECRET = 'YOUR APP SECRET'
Noteworthy things
This library does not include frontend code
You still need extra code on your frontend that retrieves the user access token from Facebook. Usually you would hook up the official Facebook login button that triggers the official Facebook login popup and then write some code that sends the token that was returned by Facebook to our mutation.
This library forces the user to grant access to their Facebook email
During the official Facebook login popup, the user can decide to revoke access to the email address. Other libraries, like django-allauth will have some extra views where the user is then asked to enter an email anyways, after the Facebook login. We do not care about this. Instead, we will ask the user to press the login button again and this time please grant access to the email address.
This library does not return a JWT token or anything like it
Please note that we don't use JWT in our projects. We use Django's default session based authentication. Therefore, our mutation does not return anything.
Our mutation does call Django's
login() function, which will save the new
login-state into the user's session. When the mutation returns, it will instruct
the browser to save the new session key in the cookie. Our frontend will then
trigger a
window.location = /new/url/, since this is a new request (including
the new session key), the server-rendered response will realize that this is a
now logged-in user.
If you would like to disable this behavior, you may provide a custom function
for the
FB_LOGIN_SUCCESS_HANDLER setting (see below).
Configuration
This app uses the following settings:
FB_LOGIN_APP_ID (mandatory)
This should be your Facebook app-id.
FB_LOGIN_APP_SECRET (mandatory)
This should be your Facebook app secret.
FB_LOGIN_GRAPH_VERSION (optional)
Default:
'v5.0'
You can set this to a higher version in order to stay compliant with the Facebook guidelines. Of course, just bumping the version number does not guarantee that this app will still work, but the APIs that we use here have been pretty stable for years, so it might just work.
FB_LOGIN_SUCCESS_HANDLER (optional)
Default:
facebook_login.utils.success_handler_default
Set this to your own function in case you need to do additional things
when a user logs in. You can find our original implementation in
utils.success_handler_default().
Your custom function may return a string and that string would be passed on
to the frontend by the mutation as the
extra key. You will most likely want
to return something like this:
json.dumps({'token': 'ABC123...'}).
If you do return something (i.e. a JWT token), then the mutation will return
it to the frontend as the
extra key.
FB_LOGIN_ERROR_HANDLER (optional)
Default:
facebook_login.utils.error_handler_default
Set this to your own function, for example if you would like to log certain exceptions to Sentry or alert you in other ways when Facebook login attempts are crashing. By default, only the user will see error messages on the frontend but you will likely not notice that something is wrong.
Your implementation should look something like this:
from facebook_login import exceptions def error_handler_custom(facebook_auth_mutation, request, exception): message = '' if isinstance(exception, exceptions.UserEmailException): message = str(exception) else: message = ('Failed to login with Facebook. Our engineers have been' ' notified. Please try again, later.') # log exception to Sentry return facebook_auth_mutation( status=400, form_errors=json.dumps({ 'facebook': [message] }), extra=None, )
As you can see, this way you can customize the error messages that are shown to the user and you can use any logging service that you like.
FB_LOGIN_API_BASE_URL (optional)
Default:
''
Allows to override the base API URL, just in case. Of course, we are not sure, if a future API would be backwards compatible, so just changing this to a higher API version number might cause issues with this library.
Troubleshooting
KeyError: 'password'
If this happens, chances are that you are using
django-allauth. Their
authentication backend crashes when Django's
authenticate() function is
called without a
username and
password keyword-argument. As a workaround,
you can just make sure that
facebook_login.auth_backends.FacebookAuthBackend
appears before other authentication backends.
Contributing
- Clone this repo
mkvirtualenv --python=python3.6 django-facebook-login
pip install -r requirements.txt
pip install -r test_requirements.txt
fab test
open htmlcov/index.html
./manage.py migrate# This creates a sqlite3 DB
./manage.py createsuperuser
./manage.py runserver
Unfortunately, running the local devserver only gives you access to the Django admin. There is no demo-frontend code that would actually call this library's backend code, yet.
Acknowledgements
This library was built with love at The Artling
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/django-facebook-login/
|
CC-MAIN-2021-39
|
refinedweb
| 998
| 56.25
|
Like it or not, LINQ is here to stay. Personally I think this is a good thing. After some initial hesitation, I have sipped the Kool Aid and it’s not that bad.. Fortunately, this turned out to be a deficiency in the samples and documentation, not LINQ itself. There are actually lots of options available.
In this article, we will review various approaches for building dynamic LINQ queries, starting with some fairly straightforward options and moving on to building the query from scratch with Expression Trees. None of this will require the System.LINQ.Dynamic namespace.
Hopefully you’ll enjoy the ride.
A Little Background.
For purposes of this discussion, we will use the latter syntax and call it Method chaining. We are chaining together method calls and it’s a fluent interface. So I give props to both names. This is personal preference, but I believe that IntelliSense kicks in quicker with Method chaining. I also think this syntax makes a couple of implications more obvious. Also, I should point out that Visual Studio and C#/ VB.Net don’t really care which format you use. You can use either one, or you could use both. For the sake of your team and transitioning from section to section or project to project, I recommend that you pick an approach and then stick with it. I prefer Method chaining.
Let’s see what a simple query will look like in Query syntax and Method chaining syntax. Here we want to query a list of files to retrieve the ones that imported in the last week.
With Query syntax, it may look like this:
With Method chaining it may look like this:
These two queries look very similar and they will do exactly the same thing.
If you wanted to add additional criteria, you could simply add them to the “Where” section.
So far everything seems comfortable and if you look at most of the examples on the Internet or MSDN this is what you would see. As the query gets more complex, the “Where” section gets more complex. As we will soon see, this is not the only option.
From here on out, we will include the sample code using Method chaining syntax. Rest assured, in most cases, you can still do the same thing with either format. In fact, Resharper even has helper links to automate switching back and forth.
Simple Dynamic Query With Multiple Where Statements
In a traditional SQL statement, we are limited to a single WHERE statement and all of the criteria goes in that one WHERE statement. When you are first learning LINQ, it looks as if you have the same limitation and, in fact, you will search high and low on the Internet before finding examples that don’t reinforce this perception. Facing such restrictions, dynamic queries are tough. Fortunately, we don’t face such restrictions, we know we can have any number of WHERE methods in a LINQ query. Consider this:
Our last example could be written like this:
The two queries are identical in meaning, but note the subtle difference here:
This looks very similar to the previous query but will have dramatically different results. In this last query, the initial filter requiring that the Import date had to be in the last seven days is ignored. This is because the Queryable is immutable. The first call to the Where method on the files object does nothing to the original files object. Instead, it creates a brand new object and returns it. This is why when we call the Where method on the files object the second time we have lost what happened to the first call. This is a subtle but very important difference.
When we chain methods, we are automatically operating on the returned value from the previous call.
So the correct way to write the last example would be something like this:
Now to make the query dynamic, we change things up slightly:
Now, depending on the value of the pastOnly parameter, the second filtering criteria may or may not be included in the query.
Type Safe Dynamic Sorting
It is common to display a grid of data to a user and allow the user to sort it any way that they want. We can easily accommodate this dynamically by adding the appropriate OrderBy method call to our query.
If we know that there are only a handful of options that the user could specify, we could do something like this:
This is very intuitive and it makes it very obvious what you are doing. It can be very tedious as well. If we need to add a new property that could be sorted by, we would have to change this code. It also has the name of the property hard coded in the logic. We will also have to duplicate this logic everywhere that we want to allow dynamic sorting on the FileImport object.
One way to improve this will be to encapsulate the OrderBy logic into its own method.
We start by noting the signature of the OrderBy method. The method signature that we are interested in looks like this:
We are passing in a Lambda expression that is a function expecting TSource and returning TKey. We can encapsulate the sorting logic by defining a method that will take a string for the property name and return such a function.
By pulling the conditional logic out of the query, we limit the number of places that will need to change as new sort options become available.
Armed with such a function, our dynamic query can be rewritten like this:
Now our dynamic query looks good. There are no magic strings, and it does not have to be changed when we add new sorting options.
But we can do even more for the EvaluateOrderBy method.
Improving the EvaluateOrderBy Method
The EvaluateOrderBy method has a couple of problems:
- It will only work with the FileImport object.
- It will only sort by the options hard coded in.
- It still has to be updated when we add new options.
Ideally we would like to have a method without the magic strings. We would like to have a method that will work with any TSource. Well that’s a pretty tall order, but I think we are up for it.
This is where express trees come into play. Expression Trees allow us to build up the logic for the method (lambda expression) that we need to return. Expression Trees may seem a little intimidating at first, but don’t worry, the expression that we need to build up is very simple, we need to build a property reference expression. The expression that is created will look like this:
We are going to ignore the more complex cases of:
It is possible that the property references could go on indefinitely. This is possible, but rare in actual practice. If you do find yourself having to manage such a complex object hierarchy, you can use reflection to map out the relationship and then adopt recursion to build up the property references.
For such a simple case, the GenericEvaluateOrderBybecomes this:
There is a lot going on for such a short method.
We start by determining the type for the generic argument. This will also be the type for our lambda expression.
Next we define the parameter by specifying the name and type.
Next we specify the only thing that we are going to do in this function, reference a property. We specify that it is a property of the parameter and we specify the name. If you wanted additional protection, you could use reflection to ensure that the specified property is a property of the type that you found earlier. This is also where you would need to build up a complex structure to support nested property references.
Now that we have all of the “logic” in place, we simply need to convert it to a lambda expression and compile it.
Alternately, we could make this an extension method to the Queryable itself:
With this approach, we pass in the IQueryable and return an IQueryable. The big difference is that now we will explicitly call “OrderBy” passing in the lambda expression that we created earlier.
From a usage perspective, we now have:
This will now allow us to sort any IQueryable by any property regardless of the object being referenced or who the LINQ provider is.
Using Expression Trees to Build a Query from Scratch
For this bit of magic, we are not going to be able generically add any filter criteria in place, but we can add some nice reusable logic.
When we define filter criteria, it will generally take one of just a handful of forms:
The Expression class in the Expressions namespace provides static methods to cover all of our bases.
Here we will focus our attention on three static methods:
- Equal(Expression, Expression)
- LessThanOrEqual(Expression, Expression)
- GreaterThanOrEqual(Expression, Expression)
The other methods available will follow the same pattern of taking two expressions, a Left Expression, a Right Expression, and the method itself defining the binary operator.
In most cases, the two expressions passed into our comparison expression will be a property reference expression and a constant expression.
To create a simple comparison method, we might use something like this:
This will do a simple equality comparison. Simply change the Expression.Equal to any of the other comparison functions to get the different types of comparisons. Everything else stays the same.
The resulting function that is returned is suitable for passing directly into a Where method on our IQueryable.
In terms of usability, this is a giant step backwards. The original syntax is much easier to write and read. Not to mention that we now have a magic string in our query, but we are just getting started.
Now that we know how to programmatically create a function that can be included in the where clause, we are ready to explore some exciting options. Consider how we could write a method to require that all dates have passed.
We start by getting the type for the Generic Argument. Then we build up a list of the dates that are in this type. We then initialize our parameter expression as we have done in the past. Next we setup a constant expression that we will compare each date property against.
Now things get a bit more interesting. We have a couple of different possibilities in the final comparison depending on how many dates are in the object. Ultimately, we will return a lambda based on filterExpression
- If there is only one date, filterExpression will use the property reference and thedateCap as left and right.
- If there are two dates, filterExpression will be a “logical and” expression with one comparison being the “left” and the other comparison being the “right”
- If there are more than two dates, filterExpression will be a “logical and” expression with one comparison being the “left” and the “right” being a new “logical and” expression. This pattern can go on indefinitely regardless of how many dates there are.
So this one method can handle everything from there being a single property to dozens of date properties. Regardless of how many date properties there are, we can call it like this:
This simple pattern can easily be extended to create methods such as:
- AllDatesAreBlank
- AllBooleansAreTrue
- AllBooleansAreFalse
- AllStringFieldsHaveValues
- AllIntegersArePositive
Conclusion
We live in a brave new world. For years programmers have dreamed of being able to unify data access logic regardless of source. With LINQ we are closer to realizing that goal, and Expression Trees give us complete access to all the magic.
|
https://www.simple-talk.com/dotnet/.net-framework/dynamic-linq-queries-with-expression-trees/
|
CC-MAIN-2017-04
|
refinedweb
| 1,952
| 61.77
|
Unanswered: Display issue on TabPanel with GXT3
Hi,
I have a strange problem with an application of tabPanel:
This is my code (for example) :
public class Zone3ViewImpl implements Zone3View {
private TabPanel tabPanel;
public Zone3ViewImpl() {
tabPanel = new TabPanel();
tabPanel.setBodyBorder(false);
tabPanel.setTabScroll(true);
tabPanel.add(new Label("Tab 1 Content"), new TabItemConfig("Tab 1", true));
tabPanel.add(new Label("Tab 2 Content"), new TabItemConfig("Tab 2", true));
}
@Override
public Widget asWidget() {
return tabPanel;
}
}
And the display of Zone3ViewImpl in my application looks like this :
tabPanel.jpg
As you can see, the first Tab isn't display at the left of my window and all my tabs got an enlarge "header".
Impossible to see where the problem come from.
If someone can help me, I would really appreciate it.
thx
Hi,
Did you find a way to fix this?
I Have the exact same problem using tabs.
I tried the sample code in the explorer with gxt 3.0.0b and I have an extra 40px padding on the left and a height of 46px (21px on the explorer).
Can somoene explain us why we have this weird display.
Thanks
- Join Date
- Feb 2009
- Location
- Minnesota
- 2,737
- Vote Rating
- 93
- Answers
- 109
As mentioned also in, it appears that you are not loading the reset.css file correctly. Either it is missing in your html page, or is not loading when the application comes up correctly - the Chrome Inspector should show a 404 if it is not loading correctly.
Thank you very much for your quick answer.
I didn't get any 404 on reset.css on firebug.
I added it and it has fixed the rendering.
|
https://www.sencha.com/forum/showthread.php?215013-Display-issue-on-TabPanel-with-GXT3&p=848883
|
CC-MAIN-2016-18
|
refinedweb
| 277
| 65.42
|
On the previous pages, we looked at three examples of using playhead commands to control variously-structured movieclip timelines. In the first example, we used gotoAndStop commands to jump to a keyframe in a movieclip that defined its state (on or off). In the second example, we turned the two keyframes of example1 into two sequences, and used gotoAndPlay to play through each sequence (and stop at the end). The last example contained a movieclip with a continuous loop (bee tweened along a guided motion path) that was controlled by the playhead commands play and stop.
On this page, we'll look at doing the same thing with actionscript, which can provide a greater range of possibilities and control than building keyframes and sequences on a timeline. We'll start with our previous example 1 (on/off lightbulb) and look at how we can achieve the same control with actionscript.
Open lightbulb3.fla (available via link at right) and you'll see a layer with on & off controls and a lightbulb layer with a jpg in it. If you convert the jpg to a movieclip and name it lightbulb_mc, you can control its visibility with this code (in frame 1 of the main movie):
on_mc.onRelease = function() { lightbulb_mc._visible = true; }; off_mc.onRelease = function() { lightbulb_mc._visible = false; };
As we did previously, we're defining a function and assigning that function to the onRelease event property of on_mc, and another function to the onRelease event property of off_mc. Each function contains one statement, which assigns a value to the _visible property of lightbulb_mc. As you can see, _visible is a Boolean property, that is, it takes one of two values: true or false.
If you want a bit more refinement (lightbulb still showing but very faded), you'll need to use another property of movieclips, _alpha, which is a Number property and can take any value between 0 and 100. And to make the lit up part of the bulb disappear completely in the off state, you could add a layer above the lightbulb layer, using the paintbrush tool to draw a dark smudge over the center of the lightbulb, converting that to a movieclip named smudge_mc, and applying this code in frame 1 (instead of the code above):
on_mc.onRelease = function() { smudge_mc._visible = false; lightbulb_mc._alpha = 100; }; off_mc.onRelease = function() { smudge_mc._visible = true; lightbulb_mc._alpha = 40; };
Notice that neither of those statements affects the state of the lightbulb when the movie starts up; they only define what should be done when one of the controls is clicked. To show the lightbulb in its off state when the movie starts, you could add this line above the others (or below; it doesn't matter which):
lightbulb_mc._alpha = 40;
Question: What statement would you put instead of the one above to show the lightbulb in its fully on state when the movie starts? (no, it's not just lightbulb_mc._alpha = 100, since the _alpha of lightbulb_mc is already at alpha=100 by default).
The intro to classes page has more information about properties of movieclips in particular, and about properties and methods of classes in general.
In all the examples we've looked at so far, we've created anonymous functions and assigned them to event properties. A better coding method is to define the function first and give it a name by which it can later be accessed. Doing that to the code above would produce the following:
lightbulb_mc._alpha = 40; function turnOn() { smudge_mc._visible = false; lightbulb_mc._alpha = 100; } function turnOff() { smudge_mc._visible = true; lightbulb_mc._alpha = 40; } on_mc.onRelease = turnOn; off_mc.onRelease = turnOff;
Giving the function a name allows it to be assigned to multiple objects, and also gives us more control over the state of the controls, allowing us to disable one (should we ever want to) with this statement
on_mc.onRelease = null;and later re-enable it with
on_mc.onRelease = turnOn;
We've seen how to produce a transition by creating a tweened sequence on the timeline. Another way to achieve the same thing with actionscript is by using the Tween class, which allows you to program a change to any property of a movieclip, from a specific beginning value to a specific ending value, over a specific duration. You could make the lightbulb fade up when it's turned on, for example, with this code in frame 1 of the movie:
import mx.transitions.Tween; import mx.transitions.easing.*; // FUNCTIONS // define what should be done when the on button is clicked function turnOn() { new Tween(smudge_mc, "_alpha", Regular.easeIn, 100, 0, 1, true); new Tween(lightbulb_mc, "_alpha", Regular.easeIn, 40, 100, 1, true); } // MOVIE SETUP // start movie with lightbulb off: lightbulb_mc._alpha = 40; // define what should happen when on_mc is clicked: on_mc.onRelease = turnOn;
Several things are different in that code than what we've used previously. First, there are two import statements at the beginning -- those are necessary to include on any frame where you'll refer to the Tween class (which is not, for some reason, built into MX 2004 or Flash 8, but is available in both by importing). Another change is the addition of comments to explain each section of code.
The other change is the use of the Tween class. In each of the two statements in our event handler function (a function assigned to an event property), we use the tween class to produce a transition which will be applied to a specific property of a specific movieclip. A generic form of the tween class, which you can cut/paste/modify when needed, is:
// to tween over a period of time: new Tween(movieclip, "property", easing-type, start-value, stop-value, #seconds, true); // to tween over a number of frames: new Tween(movieclip, "property", easing-type, start-value, stop-value, #frames, false);
So the tween that we applied to smudge_mc changes its alpha from 100 to 0 over 1 second, and the tween being applied to lightbulb_mc (at the same time) changes its alpha from 40 to 100 over 1 second. You can probably figure out how to copy the on_mc function code and change it to work in reverse for off_mc.
In the sample shown above, I also added an if statement to check and see if the lightbulb was turned on before it can be turned off. Because my lightbulb movieclip is only one frame, I can't check for the playhead being in a particular frame as I did before. Instead, I'll read the the _alpha property to see if it's turned off (and assume that any value of alpha below 50 means turned off):
function turnOn() { if (lightbulb_mc._alpha < 50) { new Tween(smudge_mc, "_alpha", Regular.easeIn, 100, 0, .7, true); new Tween(lightbulb_mc, "_alpha", Regular.easeIn, 40, 100, .7, true); } }
(I did the same check in turnOff, checking for alpha > 90 there).
A description of the various tween and easing types may be found here, as well as None.easeNone if no easing is desired. (The others are: Bounce, Back, Elastic, Regular, Strong, or None used in combination with either easeIn, easeOut, or easeInOut).
Note that while we used the Tween class to affect the _alpha property of movieclips on this page, it can also be used to affect the _xscale and _yscale properties (to grow or shrink an object) and the _x and _y properties (to move an object on the stage), along with _rotation, _width, and _height.
The Tween class is used to produce motion on all of the Easing Slider pages at the site, on the Tween Sequence page, and for the easing in the two-level menu example.
Exercise:
Set up a scene with several controllable objects that are one-frame movieclips and as many controls as you need to control those objects in various ways. Putting all of your code in frame 1, using comments and sections as in the last example (a function definition section and a movie setup section), make the controls control your objects with the use of movieclip properties and/or the Tween class.
last update: 2 Sep 2006
Discussed on this page:
control movieclips via properties, visible, alpha, tween class, named functions
Files:
lightbulb3.fla
(free download)
|
http://www.flash-creations.com/notes/actionscript_codedmotion.php
|
crawl-001
|
refinedweb
| 1,370
| 61.16
|
Type: Posts; User: Waqas_Badar
have u tried __soapCall function? I think it will resolve ur issue
Ok i resolve the problem. It is showing me one hour difference because on my system "Automatically adjust clock for day light saving" is on.
I have found following piece of code for client time zone:
alert((new Date().getTimezoneOffset()/60) * -1)
It works fine for positive time zone. But when set negative time zone on system. I...
is there any method in C# to which i pass ip address and subnetmask and it return true if given ip is in subnet mask?
For example, i give ip 192.168.0.149 and subnetmask 192.168.0.0 to the funtion...
How to use SSL in desktop application?
In fact, i am developing desktop application which download mails from gmail. But there POP3 require ssl. I want to know which class i should use for SSL? is...
i have posted the code. See, one thread above. On run following error is return:
"ERROR 1053: The service did not respond to the start or control request in timely fashion"
And on uninstall,...
I have written another simple window service. The code is as follows:
namespace WindowsService3
{
public partial class Service1 : ServiceBase
{
public Service1()
{
...
i have put try cath in start method but nothing is written in event log.
ANY OTHER CLUE TO RESOLVE THIS ISSUE?
I have written a window service in C#. On windows XP it runs fine. I checked it on my computer and some other computers in office. I am able to install it on production system. But when i try to run...
I am using socket class for udp connection. I have to receive data from server but i do not know the size of data. In receive method we have to send byte array. Is there any way i can know how much...
Have u try this:
document.getElementById("subtotal").value = total;
I think it can not be done because java script run on client side. And this will have some security issues.
I am putting background image on ListView control. But items on list view are coming in white background. I set item background color to transparent but it still has white background. Any idea how to...
Is there a way to use IPSEC through C#? I want to ban and allow some IP on server.
Is there any library in C# for RCON?
If u r seeing PHP code on firefox then u have not configured php.ini file. If u r putting ur code of php in <? ?> tags then try it to replace with <?php ?>
can u explain ur query like ID is primary key? and ON WHICH COLUMN YOU WANT AVERAGE?
My target is to allow only specific ips to connect my computer. I google it. Most of people are saying this work should be done in C not C#. I think we can import DLL in C# so it may be possible to......
it think you can use submit function of form. Consider following code:
<a href="javascript: document.forms['USERFAVOUR'].submit()">Submit</a>
i think onreadystatechange takes a function with no argument. If you have to send argument then use this line of code:
httpReq.onreadystatechange = function (){showAjaxData(httpReq, id)};
I think to get value from select element first you to get its selected index and then from options array get its value. For example
<select name="abc" id="abc" onchange="showSelectedValue()">
...
Do you receive this error on pressing button?
Have you try alert tinyMCE? if you alert it should show an object. If you do not see it then see configuration of tinyMCE on their site.
if you...
did u put file tiny_mce.js?
if so then correct its path in head tag. I have written the code after testing.
OK see below code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head>...
|
http://forums.codeguru.com/search.php?s=8caf6c66ace0682d0a59bbd0c819b95d&searchid=8139599
|
CC-MAIN-2015-48
|
refinedweb
| 654
| 78.65
|
Performance Roundup: Heap Stacks Boost Threads in 1.8.x, MacRuby AOT, ZenProfile and EventHooks
- |
-
-
-
-
-
-
Read later
My Reading List
Ruby 1.9 moved the Ruby world from 1.8.x's userspace thread system to native threads. While 1.9's native threads still suffer from the GVL (Global VM Lock), which allows only one Ruby thread to be executed at a time, the switch to native threads brought other benefits.
Joe Damato explores one problem in Ruby 1.8.x's thread implementation which went away with native threads in 1.9. In short: context switches in 1.8.x are quite expensive, since they cause a thread's complete stack contents to be copied; from the stack to the heap (for the suspended thread) and in the other direction for the scheduled thread. Applications with large stacks or with huge stack frames suffer from this implementation detail.
Native thread implementations avoid this inefficiency by maintaining multiple stacks and switching between them. Joe's post is a very detailed description of his "heap stacks", which bring this approach to Ruby 1.8.x.
The performance improvements are significant, ranging from 2x increases up to ~10x increases, which bring the benchmark results close to the results of 1.9.1.
Patched versions of the code are available on GitHub: for 1.8.6 and for 1.8.7.
The Heap Stacks solution is yet another attempt to eradicate the biggest inefficiencies of Ruby 1.8.x, along with the MBARI patches which fixed some long standing issues with continuations and the GC.
Another path to better Ruby performance is taken by the MacRuby project, which has recently started work on an LLVM based VM. Some of that work has now been used to create an Ahead Of Time (AOT) compiler for Ruby. AOT here is in contrast to Just In Time compilers, ie. instead of compiling at runtime, an AOT compiler run generates an executable out of the source code:
The expression is compiled into LLVM IR, then bitcode, then assembly, then machine code. True compilation :-)
There are many scenarios where this is useful:
It will be useful for 1) code obfuscation 2) use Ruby on environments where dynamic code generation is not allowed
Finally, profilers are a way to figure out bottlenecks in applications. Ryan Davis updated his zenprofile profiler, which uses event hooks in the Ruby runtime as efficient way to track method invocations. Zenprofile has been around for some time, but the updated version now relies on the event_hook gem, which factors out the native code necessary for setting up the hooks. By using event_hook, it's now possible to write pure Ruby event hooks instead of having to write native code to hook into the Ruby interpreter. Zenprofile makes use of that by offering a pure Ruby version of it's profiling logic, and a faster version which uses RubyInline and C for the native code.
A quick look at the zenprofile code shows that using event_hook is as easy as extending the
EventHook class, overriding a few methods such as
def self.process event, obj, method, klass to capture the events.
Zenprofile also offers the
spy_on feature, which can be used to focus on the performance of individual methods. The feature can be configured with Ruby code; eg. to focus on
Integer#downto, here an example from
misc/factorial.rb:
require 'spy_on' Integer.spy_on :downto
Rate this Article
- Editor Review
- Chief Editor Action
|
https://www.infoq.com/news/2009/05/heapstacks-macrubyaot-eventhooks
|
CC-MAIN-2016-44
|
refinedweb
| 579
| 63.19
|
Introduction
The SignalR automatically creates the JavaScript proxy script, which helps us to create the SignalR client in JavaScript, but sometimes we don't want to use the proxy script or we are not able to use the proxy script. Example
Hence, I am going to explain how you can create the JavaScript SignalR client on your own without using the generated proxy.
I am going to create a weather app. It will be the same as my previous implementation of weather app, but instead of using the generated proxy script, I will write my own.
If you have not checked my previous article about – Creating a weather app, using SignalR, check it out at the link, given below.
Let’s start. Create a new project
Create a new Web project with the name WeatherAppDemo with .NET framewrok version 4.5. I am using .NET 4.5, because this will let us use the latest SignalR 2.x version.
Please do not change the name because I am going to use this namespace throughout the article.
Adding signalr Library
I am doing this because I want to keep the code related to SignalR to a different folder.
Configuring signalr
Now, compile the code and append this “/SignalR/hubs” at the URL. You will have some JavaScript code.
If you are able to see JavaScript code, then you have successfully configured a SignalR Server. Creating Client
Hence, we need to create two clients, which are-
STEP TO CREATE A BASIC JAVASCRIPT CLIENT
CREATE CHANGEWEATHER CLIENT
Follow the steps to create a basic JavaScript client and in the last step paste the code, given below, in the script tag.
Notice, when you will open RecieveWeatherNotification.html for the first time, there is no temperature, which is not good – I mean there should be some initial temperature. Now, what do we need to do?
Adding Extra Feature(Making more real)
I have described above, what I am going to do, so just copy the code, given below and update the ChatHub class.
Hence, compile the code and check out everything. References
View All
Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.
|
https://www.c-sharpcorner.com/article/creating-manual-javascript-signalr-client/
|
CC-MAIN-2018-22
|
refinedweb
| 361
| 71.34
|
> Oh and the "normal" #ifdef style used in Emacs is: > > #if FOO > #else /* !FOO */ > #endif /* !FOO */ > or > #if FOO > #endif /* FOO */ I find this style of #ifdef blocks to be much too cryptic for my tastes. What does /* !FOO */ and /* FOO */ mean anyway. I find that it is much clearer if your comments for the #else and #endif portions state exactly what #ifdef line they go to rather than some cryptic reference to what they go to. This style causes much less confusion and is a great help when you are not really reading the code in detail but are just skimming through looking for the place where you need to make a change. This is one of the few places where my coding style differs from the GNU coding standards. I would like to thank you for testing this patch on Linux. I have not yet had a chance to do so myself. I still do not have my Linux machine up and running completely. I am now trying to get Samba to work on it properly.
|
http://lists.gnu.org/archive/html/emacs-devel/2002-10/msg00523.html
|
CC-MAIN-2015-06
|
refinedweb
| 178
| 87.25
|
import "internal/syscall/windows/sysdll"
Package sysdll is an internal leaf package that records and reports which Windows DLL names are used by Go itself. These DLLs are then only loaded from the System32 directory. See Issue 14959.
IsSystemDLL reports whether the named dll key (a base name, like "foo.dll") is a system DLL which should only be loaded from the Windows SYSTEM32 directory.
Filenames are case sensitive, but that doesn't matter because the case registered with Add is also the same case used with LoadDLL later.
It has no associated mutex and should only be mutated serially (currently: during init), and not concurrent with DLL loading.
Add notes that dll is a system32 DLL which should only be loaded from the Windows SYSTEM32 directory. It returns its argument back, for ease of use in generated code.
Package sysdll is imported by 2 packages. Updated 2020-06-01 with GOOS=windows. Refresh now. Tools for package owners.
|
https://godoc.org/internal/syscall/windows/sysdll
|
CC-MAIN-2020-29
|
refinedweb
| 159
| 58.69
|
On Thu, Sep 17, 2020 at 9:32 PM Wes Turner wes.turner@gmail.com wrote:
There are a number of refactoring tools for Python. From :
...
Another:
On Thu, Sep 17, 2020 at 8:27 PM Steven D'Aprano steve@pearwood.info wrote:
On Thu, Sep 17, 2020 at 11:47:03PM -0000, Joseph Perez wrote:
Thus `f"{:a + b}" == "a + b"`.
...
I don't know how well IDEs like VisualStudio and PyCharm do refactoring,
Using the same example from the Bowler issue:
- print(f'bar is {bar}, not {zar}') - print('bar is {bar}, not {zar}'.format(bar=bar, zar=zar))
..both rope and Pycharm are currently smart enough to refactor the part in the curly braces:
- f'bar is {bar}, not {zar}' → f'bar is {bar_new}, not {zar}' - .format(bar=bar, zar=zar) → .format(bar=bar_new, zar=zar)
As far as I know, none of these tools know how to do the renaming of the FIRST bar to bar_new:
- f'bar is {bar}, not {zar}' → f'*bar_new* is {bar_new}, not {zar}' - .format(bar=bar, zar=zar) → .format(*bar_new*=bar_new, zar=zar)
The effort for this just doesn't seem worth it. All IDEs have find and replace (pycharm's is very nice). And even python developers who eschew the IDE use SOMETHING to write their code... whether it's vim or notepad++ or vscode (people tell me it's not an IDE) or emacs or whatever, and that something invariably provides find and replace functionality (vim has the :substitute command. notepad++ has ctr+r. Microsoft Word has ctl+h ;) ).
But if you really want it or need it in a situation where find and replace isn't a great option, you can hack a utility function using the 3.8 syntax:
def nameof(x): return x.split("=", 1)[0]
...and use it in a nested fstring:
f"{nameof('{foo=}')}"
foo
Now refactoring can work like a charm for single variables:
- f'{nameof(f"{bar=}")} is {bar}, not {zar}' → f'{nameof(f"{bar_new=}")} is {bar_new}, not {zar}'
The OP example doesn't look fantastic, but it works:
f"{nameof(f'{a=}')} + {nameof(f'{b=}')}" == "a + b"
True
--- Ricky.
"I've never met a Kentucky man who wasn't either thinking about going home or actually going home." - Happy Chandler
|
https://mail.python.org/archives/list/python-ideas@python.org/message/HZO5N7HY6II3LWTN52UMM5AKN2S5YETM/
|
CC-MAIN-2022-33
|
refinedweb
| 379
| 69.52
|
I am trying to make a simple tournament simulator that calls for the user to input team names and ability of the team from 1-100 and then plays a round robin tournament between them where each team plays the other twice. The games are played by generating a random number from 0-sum of the two teams abilities and if it is below the first team that team is the winner.
Code java:
import java.util.Scanner; public class tourney { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Please enter the number of teams: "); int teamsCount = input.nextInt(); for (int i = 0; i < teamsCount; ++i) { System.out.print("Please enter the name of the team (without spaces): "); String name = input.next(); System.out.print("Please enter the strength of the team (1 - 100): "); int strength = input.nextInt(); } } } class Team { // The name of the team private String name; // The strength of the team private int strength; // Constructor, which takes name and strength of the team Team(String name, int strength) { this.name = name; this.strength = strength; } // The method to get the name of the team public String getName() { return name; } // Get the strength of the team public int getStrength() { return strength; } // Play a game between the current team (the one, for which this method is called) // In other words the first team is this team, the other team is provided as a parameter public boolean playGame(Team anotherTeam) { } }
I realize I will have to make a whole other class for tournament but right now I am struggling on just playing the games. I figure I will use a (int)(Math.random * (ability1stteam + ability2ndteam). From the class Team, I understand how to call the first values but will I need to create a whole other class to be able to call the team name and strength from the other team or how would I go about this?
Thanks for any help that can be provided.
|
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/27926-simple-tourney-simulator-question-printingthethread.html
|
CC-MAIN-2016-26
|
refinedweb
| 331
| 67.69
|
I am having trouble getting OpenCV to work with Python on my Mac.
I have tried installing it with MacPorts and with Cmake (which I installed from MacPorts) using the methods found at here:. I also had to download Xcode to make MacPorts work.
I ran
sudo port -v install opencv +python27 and it seemed to work fine. However when I tried to import OpenCV in Python using
import cv, the module could not be found.
If any of this information helps, I have OSX 10.6.8 Snow Leopard, python 2.7.3, and am trying to install OpenCV 2.4.3. I am not a very experienced programmer so my troubleshooting attempts are falling short of a solution.
Any help is appreciated. Thanks!
I haven't tried the MacPorts installation, but you might want to try this:
import cv2 from cv2.cv import *
I had the same problem, it seems that the OpenCV Python Bindings don't get installed without
numpy preinstalled; you can use these commands:
sudo port uninstall opencv sudo port install py27-numpy sudo port install opencv +python27
As in this question: How to install Python 2.7 bindings for OpenCV using MacPorts
|
http://m.dlxedu.com/m/askdetail/3/918f63f194efe91fd31087509a39e0aa.html
|
CC-MAIN-2018-30
|
refinedweb
| 198
| 82.24
|
$$\ $$\ $$\ $$\ $$$\ $$ | $$ | $$ | $$$$\ $$ | $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$$\ $$$$$$$\ $$$$$$\$$$$\ $$$$$$\ $$ $$\$$ |$$ __$$\ $$ __$$\ \____$$\\_$$ _| $$ _____|$$ __$$\ $$ _$$ _$$\ $$ __$$\ $$ \$$$$ |$$ / $$ |$$ / $$ | $$$$$$$ | $$ | $$ / $$ | $$ | $$ / $$ / $$ |$$$$$$$$ | $$ |\$$$ |$$ | $$ |$$ | $$ |$$ __$$ | $$ |$$\ $$ | $$ | $$ | $$ | $$ | $$ |$$ ____| $$ | \$$ |\$$$$$$ |$$$$$$$ |\$$$$$$$ | \$$$$ |\$$$$$$$\ $$ | $$ |$$\ $$ | $$ | $$ |\$$$$$$$\ \__| \__| \______/ $$ ____/ \_______| \____/ \_______|\__| \__|\__|\__| \__| \__| \_______| $$ | $$ | \__|
After almost a year without posting anything, here I come with the write-ups for the 32c3ctf. For this challenge we were provided with the following script:
#!/usr/bin/env python import sys import os import socket import pickle import base64 import marshal import types import inspect import encodings.string_escape class Flag(object): def __init__(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("172.17.0.1", 1234)) self.flag = s.recv(1024).strip() s.close() flag = Flag() from seccomp import * f = SyscallFilter(KILL) f.add_rule_exactly(ALLOW, "read") f.add_rule_exactly(ALLOW, "write", Arg(0, EQ, sys.stdout.fileno())) f.add_rule_exactly(ALLOW, "write", Arg(0, EQ, sys.stderr.fileno())) f.add_rule_exactly(ALLOW, "close") f.add_rule_exactly(ALLOW, "exit_group") f.add_rule_exactly(ALLOW, "open", Arg(1, EQ, 0)) f.add_rule_exactly(ALLOW, "stat") f.add_rule_exactly(ALLOW, "lstat") f.add_rule_exactly(ALLOW, "lseek") f.add_rule_exactly(ALLOW, "fstat") f.add_rule_exactly(ALLOW, "getcwd") f.add_rule_exactly(ALLOW, "readlink") f.add_rule_exactly(ALLOW, "mmap", Arg(3, MASKED_EQ, 2, 2)) f.add_rule_exactly(ALLOW, "munmap") f.load() data = os.read(0, 4096) try: res = pickle.loads(data) print 'res: %r\n' % res except Exception as e: print >>sys.stderr, "exception", repr(e) os._exit(0)
The script is something similar to what is running at the given target host, which can be accessed via HTTP. If we just send a GET / request, it replies with a “plz POST” message so we know that it would probably take the content of the POST and pass it to pickle.loads() call. In the script above we can observe that the unpickle is not done safely, so the challenge might be about exploiting it.
Just to refresh a little bit the exploitation of an insecure unpickle, remember that pickle is supposed to allow representing arbitrary objects, so we could provide a crafted pickle that represent an object that could be useful to us. The following snippet allow us to generate a pickle that represents a “os.getcwd()” object that, once it gets deserialized, it would be executed:
import pickle import os class RunSomething(object): def __reduce__(self): return (os.getcwd, (,)) print pickle.dumps(RunSomething())
With this refreshed information about pickle, we could now extend the script so it sends the POST request to the target host with the pickle payload in it. Before doing so, we just pay attention to the script we were provided so we can see that the flag seems to be held by a variable within the same scope than the picke.loads() call, called “flag”. In python exists the “sys.module” structure, which is a dictionary with information about all de loaded modules, including the one of the script. If we take into account all of this, we can just write the final exploit that would retrieve the flag for us:
class RunSomething(object): def __reduce__(self): return (eval, ("sys.modules['__main__'].flag.flag",)) target = "" d = pickle.dumps(RunSomething()) r = requests.post(target, data=d) print r.text
We run the script, it sends the POST request with the payload, and retrieve the flag:
32c3_rooDahPaeR3JaibahYeigoong
Greetings to my team 0xb33rs and nibble for his help!
|
http://nopatch.me/2015/12/29/32c3ctf-misc-gurke/
|
CC-MAIN-2018-47
|
refinedweb
| 542
| 60.31
|
I got a school assignment that is driving me nuts. I can find the answer im looking for while searching the web, so I really would appriciate some advice on this one.
The assignment is to create a basic JavaFX Application that says "Hello World" but i should contain of the helloMain.java and the class HelloWorld.java that extends BorderPane. I have solved the assignment just using the helloMain but when I have tried to move some of the code (the root node and all it contains) into the HelloWorld.java the Scene does not seem to load when I run the application (just an empty window). So obviously I have done something wrong, but I cant figure out what.
in helloJava I got the following code (and Im pretty sure this is correct)
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class helloWorldMain extends Application {
@Override
public void start(Stage primaryStage) {
HelloWorld helloWorld = new HelloWorld();
Scene scene = new Scene(helloWorld, 300, 300);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class HelloWorld extends BorderPane {
public HeloWorld() {
final Text text = new Text(0, 130, "Hello World");
Pane txtPane = new Pane();
Pane txtPane2 = new Pane();
VBox root = new VBox();
txtPane.getChildren().add(text);
txtPane2.getChildren().add(text);
root.getChildren().addAll(txtPane, txtPane2);
}
In
HelloWorld you add
Nodes to a
VBox that you don't add anywhere, so they are "hanging in the air".
Add this line to the end of constructor of HelloWorld ...
getChildren().add(root);
... and you are done.
|
https://codedump.io/share/s8hu4SSdlkF3/1/how-to-use-my-own-class-in-main
|
CC-MAIN-2017-43
|
refinedweb
| 265
| 57.47
|
cross_file 0.1.0
cross_file: ^0.1.0
cross_file: ^0.1.0
An abstraction to allow working with files across multiple platforms.
cross_file #
An abstraction to allow working with files across multiple platforms.
Usage #
Import
package:cross/cross_info.dart, instantiate a
CrossFile
using a path or byte array and use its methods and properties to
access the file and its metadata.
Example:
import 'package:cross_file/cross_file.dart'; final file = CrossFile('assets/hello.txt'); print('File information:'); print('- Path: ${file.path}'); print('- Name: ${file.name}'); print('- MIME type: ${file.mimeType}'); final fileContent = await file.readAsString(); print('Content of the file: ${fileContent}'); // e.g. "Moto G (4)"
You will find links to the API docs on the pub page.
Getting Started #
For help getting started with Flutter, view our online documentation.
For help on editing plugin code, view the documentation.
|
https://pub.dev/packages/cross_file
|
CC-MAIN-2020-50
|
refinedweb
| 138
| 55.61
|
Inspecting images
Inspect image metadata using the
sgr show
command:
$ sgr show namespace/repository:image_hash
Inspect tables in a given image using the
sgr table command:
$ sgr table namespace/repository:image_hash table_name
Inspect object metadata with the
sgr object command:
$ sgr object object_id
These commands require you to clone the repository (but not its actual data).
It's also possible to inspect the metadata on a remote repository without
cloning any images by passing the
-r or
--remote flag to these commands:
$ sgr show -r data.splitgraph.com splitgraph/geonames:latest Image splitgraph/geonames:0b77a102cbabe2de8597dcab71f1c333f16f9e1963c9c8982988e10e65989c62 Created at 2019-12-11T12:20:08.447974 Size: 539.95 MiB Parent: 0000000000000000000000000000000000000000000000000000000000000000 Tables: all_countries
Example
Let's further inspect the object that the first example image,
example/repo_1,
used.
$ sgr object o26c6d8345cba276f807d7bcf906531568f309c2609a3420d98c01a6c99b166 Object ID: o26c6d8345cba276f807d7bcf906531568f309c2609a3420d98c01a6c99b166 Namespace: example Format: FRAG Size: 963.00 B Created: 2020-04-06 10:17:15.650187 Rows inserted: 10 Insertion hash: 37be08d7c1aca256f5e64860afe7db21e6f7c47b00cdf23f65b84576bc209f41 Rows deleted: 0 Deletion hash: 0000000000000000000000000000000000000000000000000000000000000000 Column index: key: [0, 9] value: ['19581e27de7ced00ff1ce50b2047e7a567c76b1cbaebabe5ef03f7c3017bb5b7', 'ef2d127de37b942baad06145e54b0c619a1f22327b2ebbcfbec78f5564afe39d']
There are a few interesting things in this object's metadata. Firstly, it's
stored in the
FRAG format. A Splitgraph table consists of multiple fragments
that can partially overwrite each other.
Every fragment also has a column index: this is a metadata entry showing, for every column, the minimum and maximum values that this fragment affects (deletes or inserts). This is used when querying large remote Splitgraph tables to not download fragments that definitely don't match a given query. For qualifiers on sorted columns (like the primary key), this can mean only downloading one or two fragments to satisfy a query to a table composed of hundreds.
Finally, every fragment also has an insertion and a deletion hash: the insertion hash is the hash of all the rows that this fragment inserts and the deletion hash is the hash of all the rows that this fragment deletes. These hashes are homomorphic (every row is hashed individually and then the hashes are summed up) and are similar to Facebook's LtHash. They have a really important property: the sum of all hashes of individual fragments composing a table is equal to the content hash of a whole table. This is used in deduplicating data and optimizing storage.
sgr generates the deterministic object ID by combining the content hash
(
insertion - deletion hash) and the hash of the schema of a given object. This
means that Splitgraph fragments are content-addressable.
Now, let's look at the second object that the new version of the
demo table in
example/repo_2:new_data is linked to.
$ sgr object o4882c12cdc4cb5b4e89481ebdb71585998633f19a72652debbb80980ae0f0b Object ID: o4882c12cdc4cb5b4e89481ebdb71585998633f19a72652debbb80980ae0f0b Namespace: example Format: FRAG Size: 552.00 B Created: 2020-04-06 10:18:11.466667 Rows inserted: 4 Insertion hash: aa15011c4af8e7afb877b5de68ab782b69d63720ba5787bec54fbcd6838fb377 Rows deleted: 4 Deletion hash: 7463a64e15187558e6e1096368033dfab422b34503c20e94a83b7a3e4650df68 Column index: key: [0, 11] value: ['4a44dc15364204a80fe80e9039455cc1608281820fe2b24f1e5233ade6af1dd5', 'd4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35_UPDATED'] Location: created locally
As you can see, this new object is based on the object that was used by the very
first version of the data we generated
(
o4882c12cdc4cb5b4e89481ebdb71585998633f19a72652debbb80980ae0f0b). This is
because the demo data is static and so the first version of the
demo table in
example/repo_1 and
example/repo_2 is in fact the same.
Since this object updates and deletes some rows, their values are included in its deletion hash, which is now non-zero.
Finally, the column index now spans all the values of the
key column that were
replaced or added. Hence, when there's a query against this table that is inside
that range, both fragments will be fetched to check if they match that query.
We can also inspect the actual object: every object in the
sgr cache is stored
as a CStore columnar storage file.
$ sgr sql "SELECT * FROM splitgraph_meta.o4882c12cdc4cb5b4e89481ebdb71585998633f19a72652debbb80980ae0f0b" 2 d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35_UPDATED True 3 4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce_UPDATED True 10 4a44dc15364204a80fe80e9039455cc1608281820fe2b24f1e5233ade6af1dd5 True 11 4fc82b26aecb47d2868c4efbe3581732a3e7cbcc6c2efb32062c08170a05eeb8 True 0 None False 1 None False
sgr stores the object with the same schema as the original table, plus a
Boolean flag showing whether a row has been updated/inserted (upserted) or
deleted. For deleted rows,
sgr only records the primary key, and pads the rest
of the table with
NULLs.
sgr does not always store objects in the engine. When you push an image to an
external location, like Splitgraph,
sgr usually uploads them to an
S3-compatible storage location.
sgr only downloads the actual objects and
loads them into Postgres when you check out an image containing the objects.
|
https://www.splitgraph.com/docs/sgr-advanced/working-with-data/inspecting-images
|
CC-MAIN-2022-27
|
refinedweb
| 735
| 50.87
|
2018.2 is now available, Nintendo Switch,.
You now have the ability to add .java (as well as .cpp and .a) source files to Unity project plugin folders. These files will be recognized as Unity plugins and compiled into the APK without requiring the user to build libraries separately in Android Studio. The plugin code remains a part of the Unity project, eliminating the need to create a separate Android Studio..
C# Job System, Entity Component System and Burst Compiler
With our new high-performance multithreaded system introduced in 2018.1, we’re rebuilding the very core foundation of Unity. The new system will enable your games to take full advantage of the multicore processors currently available — without the programming headache. This is possible thanks to the new C# Job System, which gives you a safe and easy sandbox in which to write parallel code. We are also introducing a new model to write performant code by default with the Entity Component System , Android, and Nintendo Switch)..
Related posts
133 CommentsSubscribe to comments
ocean king cheat appSeptember 8, 2018 at 6:14 am
You will want to know where your visitors coming by way of.
The title is avert see your past top bar (title bar) of the browser.
In such cases, the organic listings also get into the slap of the
Google.
muskidoSeptember 3, 2018 at 12:26 pm
i love unity game
MINSEON OAugust 28, 2018 at 4:13 pm
Can’t I use shader graph in VR game? It doesnt work(solid black screen – HTC VIVE) when I use shader graph and LWRP.
MINSEON OAugust 28, 2018 at 4:11 pm
Can’t I use Shader graph to VR game? steam vr is not working(HTC VIVE HMD Screen is always black.) when I use LWRP and Shader Graph.
David SAugust 26, 2018 at 3:25 am
2018.2.4 environment VERY SLOW and graphics / dialogs not working on my Mac (posted in OSX forum).
Antonius NaumannAugust 17, 2018 at 4:05 pm
The SVG-Update is great. Is it possible to change the in-game).
Is it possible to achieve this?
Antonius NaumannAugust 17, 2018 at 4:04 pm
The SVG-Update is great. Is it possible to change ingame).
Is it possible to achieve this?
adamgamesAugust 15, 2018 at 9:31 pm
i have a error in the downlowading
Thomas Krogh-JacobsenAugust 16, 2018 at 9:40 am
Sorry to hear you are experiencing problems downloading. What error are you getting?
johnAugust 15, 2018 at 2:02 pm
hey i want to create unity game for this game
SpyCharAugust 15, 2018 at 4:45 am
There is one feature that would be helpful for high quality visualisations. Especially when it comes to human body. It is a support for rigs with more than four influences per vertex. HDRP would be an appropriate place to introduce it.
fiestera-2563@hotmail.comAugust 9, 2018 at 3:35 pm
Me encanta
BlavadidooAugust 8, 2018 at 6:00 pm.
Camila SilvaAugust 6, 2018 at 9:40 am.
AnthonyAugust 6, 2018 at 3:48 pm
Hey! Could you let me know the case numbers in question? I’d follow up with the status. Thanks so much for your interest in physics.
Jasur SadikovAugust 2, 2018 at 4:45 pm
Awesome! Nice work! Unity took right direction with their engine.
Waiting for UI system minor improvements and Editor UI update.
xAGAugust 1, 2018 at 7:39 pm
Absolutely love the direction that Unity is taking. I have been working with Unity for a long time now and it literally went from kinda clunky to very professional feeling!
JustACommentAugust 1, 2018 at 5:21 pm
Ah I thought the SVG importer works for the UI :(
GlennJuly 31, 2018 at 6:02 pm
SVG question…. Does Unity 2018.2 support SVGs with transparencies? I create all my art in Illustrator which I then convert to PNGs. I often adjust the opacity in many ways as the shapes overlap.
BipJuly 27, 2018 at 5:43 pm
Does Unity support right-to-left text yet? I’m using the InputField component and I had to develop a custom script that flips the input when appropriate, but it’s not reliable when mixing ltr languages with rlt ones.
AlexJuly 26, 2018 at 6:43 pm
Did anyone tested 2018.2.1 with default project no SDK imported its cant build send error multidex-1.0.2 cant be found. does QA actually work ?
illuminati-reptilianJuly 25, 2018 at 11:14 pm
.”
Is this only related to Universal Apps or every platform?
антонJuly 25, 2018 at 7:57 pm
updating the norms is very convenient and pleasant to work
LukeJuly 25, 2018 at 6:23 pm
When will the new Standard Character Assets be available ? i Have asked in the forums ( and on social media, i have been more successful getting information out of my dogs about which one is responsible for raiding the bin than i have from Unity.
Tom SouthworthJuly 23, 2018 at 3:58 pm :)
Benoit DupuisJuly 24, 2018 at 2:47 pm
Hello Tom, unfortunately SVG is not yet supported by the UI system. This is something that gets asked very often and we’re seriously considering it. Thanks for the feedback!
AdamJuly 22, 2018 at 2:06 pm
My Editor is too Slow
windows8.1
unity2018.2
4gb ram
any suggestion on how to make it fast
Lurking NinjaJuly 25, 2018 at 9:26 pm
– get Windows 10
– get more RAM (min. 16GB highly recommended, maybe more, it depends on what you’re doing)
– get an SSD as a working storage
ThadJuly 19, 2018 at 12:58 am
How do you get it? Note I only have personal.
Max KrasJuly 18, 2018 at 2:04 am
I absolutely love the idea of SRP. But, will it be possible to write a shader with a custom lighting model? For example, I would like to change the Fresnel approximation for a car game I’m developing.
JamesJuly 17, 2018 at 5:45 pm
Say you’ve got a 2D game, totally unlit. Zero lighting etc. Running IL2CPP. Would the LW SRP make a difference in performance?
sarveshJuly 17, 2018 at 4:49 pm
can i use python language to code my games in unity
LukeJuly 25, 2018 at 6:25 pm
Not the i’m aware of, the main scripting lang is C#, but that shouldn’t stop you, you can do it !!!
jkLimJuly 17, 2018 at 8:18 am
In the runner game, stutter problem can not be solved at all.
Is it the technical limit of Unity?
LCoderJuly 17, 2018 at 10:10 am
Stutter is chronic problem in 5.x and above.
Martin Tilo SchmitzJuly 30, 2018 at 4:29 pm.
xZZAugust 1, 2018 at 7:41 pm
Your PC is trash…. Sorry but there is no other way to say it. I experience no stutter whatsoever on multiple machines. You should try to meet the recommended requirements before saying it does not work as intended.
JohnJuly 16, 2018 at 5:40 pm
So were do we find the ,planar reflections, volumetric lighting?
Jordan AJuly 15, 2018 at 3:24 pm!
CaseyJuly 14, 2018 at 3:05 pm.
BeginnerJuly 17, 2018 at 5:22 am
Can you teach me English? I don’t have any foundation!
lookenwuJuly 14, 2018 at 11:02 am
When will Shader Graph Production Ready?
vishalJuly 28, 2018 at 6:26 pm
hiii
LeeJuly 14, 2018 at 4:50 am….
Amboy Manzano ArqueroJuly 14, 2018 at 12:24 am
hello
AlexeyJuly 13, 2018 at 12:31 am
Wow!!! SVG Import! This feature is AWESOME!!!! I’m wait this coolest feature many time…. together with API, it’s cool! However, still wait to updating .net runtime to the latest version :)
PS. Detailed translate to Russian language are available here
DiscoJuly 12, 2018 at 10:00 pm
How can i enable Specular AA?
Brian AckerJuly 12, 2018 at 3:56 am :(
steenJuly 13, 2018 at 11:03 am
Hi Brian,
There is not going to be an update of the preview build with Prefabs. All resources are currently focused on getting the new Prefab workflows ready for 2018.3.
Connor PayneJuly 12, 2018 at 2:34 am
Will we ever be able to create large terrains without the paintbrush scaling up?
ChungJuly 11, 2018 at 5:57 pm
Charles BeaucheminJuly 11, 2018 at 8:03 pm
You need to set Vulkan as the preferred rendering API for your current build target in the player settings, or launch the editor with -force-vulkan
ChungJuly 12, 2018 at 5:22 am
Last ngiht I tried with -force-vulkan but not working, Tonight, I will try change in player setting
Levi BardJuly 12, 2018 at 9:03 am
If it’s not working with
-force-vulkan, check your editor log to see whether vulkan support is being successfully loaded/enabled (and if not, why not).
ChungJuly 12, 2018 at 7:39 pm !
ChungJuly 12, 2018 at 8:03 pm
LivenJuly 11, 2018 at 5:34 pm
Any news on shadergraph / NET4.x incompatibility ?
WhitEnamelJuly 11, 2018 at 1:11 pm
What is “Unable to find name key matches ‘rıght'”? What is “rıght”? And this error doesn’t affect run the game. But spamming my console.
Charles BeaucheminJuly 11, 2018 at 3:00 pm
please open a bug using the Bug Reporter tool and we’ll follow up with you
YozaroJuly 11, 2018 at 11:02 am
Can’t find the Addressables package in Package Manager and there seems to be no links to the preview builds anymore. How am I supposed to get the package?
Charles BeaucheminJuly 11, 2018 at 2:58 pm
please have a look at our forum post here:
EddieJuly 11, 2018 at 11:00 am
Will Recorder 1.0 work with the HD Pipeline?
Ans BeaulieuJuly 26, 2018 at 9:45 pm
Yes as long as you output to game screen and not cameras (it’s an option in the Recorder). We are working on a fix for the cameras.
Michal PiatekJuly 11, 2018 at 9:07 am!
AtomicJoeJuly 11, 2018 at 7:55 am
THANK YOU FOR STREAMING MIPMAPS!!!!!!
I see it works with lightmaps too, but does it manage reflection probes too?
KyleJuly 11, 2018 at 4:26 am
How do I get the Addressable Asset package? I don’t see it in the Package Manager.
PeterJuly 11, 2018 at 7:30 am
Check this forum post:
The “Getting Started” document contains a link to a demo project that references the necessary packages.
DaveJuly 11, 2018 at 3:49 am
I’m a little confused, is ECS still in preview. Can we use ECS in our commercial releases/projects, or is it just to test out/learn and not recommended to use in final project releases.
lookenwuJuly 11, 2018 at 3:34 am
failed to download UWP IL2CPP component
Charles BeaucheminJuly 11, 2018 at 3:04 pm
possibly an intermittent server overload issue? did you try doing it again? otherwise, you can try this direct link:
VVEthanJuly 11, 2018 at 1:06 am
IL2CPP-Managed Debugger — this is huge/awesome/excellent, can’t wait to try it.
andreJuly 10, 2018 at 11:33 pm
I just installed unity2018.2 and found that the font in the editor is still too small to read on a 4k screen. Where can I set the font size for text in the editor?
Antoine LassauzayJuly 11, 2018 at 3:41 pm.
andreJuly 11, 2018 at 5:07 pm
Thank you for your explanation.
I reset my scaling setting in Windows 10 and put it back to 150% and now Unity Editor looks good and I can finally read the text there again.
RyanJuly 10, 2018 at 11:29 pm?
Anthony RosenbaumJuly 10, 2018 at 9:44 pm
Sweet only 3 more months until Nested Prefabs and Isometric Tilemaps!
Charles BeaucheminJuly 10, 2018 at 10:19 pm
you can use Nested Prefabs right away by downloading the preview build here:
KharilJuly 10, 2018 at 8:43 pm
“Proxy Screen Space Reflection & Refraction”
Is there a paper, blog post or any sources that explain the details of the working?
Charles BeaucheminJuly 10, 2018 at 9:40 pm
you can take a look at the documentation for HighDefinition and LightWeight packages here:
KharilJuly 10, 2018 at 9:50 pm.
KharilJuly 11, 2018 at 3:40 am
Goddamnit, it’s another name for box projection cubemap, you could have said that, My head was spinning for a while :(
Jesus OrillanJuly 12, 2018 at 12:54 pm
How could you make Proxy SSR work? I found no documentation about it.
archieJuly 10, 2018 at 8:10 pm
this is cool, but I wonder what about skinned mesh rendering component to be using in ECS and C# Job system?
guillermo01August 19, 2018 at 12:46 am
hola me llamo guillermo tnia cuatro mensajes en mi tablet
DeepakJuly 10, 2018 at 7:30 pm
Sir , actually I really happy and little bit disappointed with “no terrian” updates ! Please make new terrain feature like paint materials !
Arisa ScottJuly 10, 2018 at 8:41 pm
We have Terrain updates coming in 2018.3, check out our Unite Berlin roadmap presentation for an overview:
Chris H.July 10, 2018 at 7:20 pm
Any word on the state of the GPU lightmapper? I know it was mentioned as a 2018.2 feature, has it been pushed to 2018.3.x?
Charles BeaucheminJuly 10, 2018 at 7:27 pm
You can always keep an eye on our Unity Roadmap to know the features we are working on and the version in which we will be releasing them. For now, the GPU Lightmapper is in development but not scheduled yet.
NomadicJuly 10, 2018 at 6:42 pm
2D polygon collider does not updates if 2d texture changed
Michael HerzogJuly 10, 2018 at 6:22 pm
“In 2018.2, we added several improvements including Reactive system samples and arrays and strings.”
Where are these string helpers? I can’t find a “NativeString” in the Unity.Collections namespace. Am I missing smth?
Joachim AnteJuly 10, 2018 at 7:31 pm
The Entity Component System is focused on providing a new way of writing high performance code. It is up to you if you want to use it or not. We have no plan to deprecate MonoBehaviour / GameObject.
AlexanderJuly 11, 2018 at 11:40 am.
Charles BeaucheminJuly 10, 2018 at 7:55 pm
Hi Michael, thanks for your feedback. It seems these systems will be coming later. I will edit the blog post to rectify this information.
DenisJuly 10, 2018 at 6:03 pm
“Edit Sprite Mesh” in Anima 2D not work on 2018.2 – fix this please!
When are you planning a new prefab system? As far as I remember, it’s promised in 2018.2 version.
Charles BeaucheminJuly 10, 2018 at 6:14 pm
Can you use the bug reporter to file an issue for this please?
As for the Prefab System, you can already get a preview build here: but it is only scheduled for 2018.3.
DenisJuly 11, 2018 at 6:02 am
Done:
Holik KrisztiánJuly 10, 2018 at 5:53 pm
Congratulations!
Can i find any infromation about how to upgrade full old project to the new HDRP?
JcrombezJuly 10, 2018 at 5:47 pm
Can you give us some details on why some nodes can and some can’t be used as vertex position input ?
Matt DeanJuly 10, 2018 at 10:32 pm
This is simple because HLSL doesnt allow some functions in the vertex shader. More information and a list of incompatible nodes can be found here:
jcrombezJuly 11, 2018 at 9:07 am
Thank you Matt.
KurdJuly 10, 2018 at 5:38 pm
Widh you could add Java beside C#, I’m still waiting your reales Which support Java.
MostHatedJuly 10, 2018 at 8:29 pm.
KurdJuly 12, 2018 at 8:26 am
I’m asking them to make Java a main language. Still waiting.
Alkis TsapanidisJuly 13, 2018 at 4:12 pm
Simple request with an exceedingly easy answer:
No.
HaddicusJuly 14, 2018 at 8:47 pm
You’re going to be waiting a LOOOONG time. They just removed Javascript support, and have no intention to add Java support, like ever. Better for you to learn C#, or go somewhere else.
Sad Government WorkerJuly 10, 2018 at 5:12 pm
More unity updates that I will never see
Another Sad Government WorkerJuly 10, 2018 at 5:22 pm
Don’t worry, I think we will finally update to Unity 3.4.1
JeweinJuly 10, 2018 at 4:38 pm
All this looks magical, good to see you folks had loads of fun too :-)
DillanJuly 10, 2018 at 4:29 pm.
Karl JonesJuly 10, 2018 at 4:45 pm
Sorry to hear you are having problems. Have you filed any bug reports for these issues you are having? What are the bug numbers?
Charles BeaucheminJuly 10, 2018 at 5:04 pm
Since 2017.3, we put in place a Release QA team dedicated to ensure the versions we are shipping are of good quality, on top of the QA teams working on testing each feature.
MostHatedJuly 10, 2018 at 8:33 pm.
Harshit Pratap SinghJuly 10, 2018 at 4:27 pm
The new features are great specially shader graph, new asset store, unity hub and the package manger.
Jashan ChitteshJuly 10, 2018 at 4:07 pm ;-)
Brad WeiersJuly 10, 2018 at 5:01 pm
LWRP works in 2018.2 for mobile VR platforms but it’s missing MSAA which is coming in 2018.3. HDRP support for VR will be 2019 once we have all the kinks worked out.
Fahim FaysalJuly 10, 2018 at 3:45 pm
What about the bone based 2d animation system. Is it ready?
Charles BeaucheminJuly 10, 2018 at 3:53 pm
please check our 2D Preview forum for all the information about this package and other 2D packages:
Glauber TorresJuly 10, 2018 at 3:31 pm
This is very impressive! Any idea when facial mocap will be in public beta?
Simon TaylorJuly 10, 2018 at 3:27 pm?
BenJuly 10, 2018 at 4:51 pm.
JesperJuly 11, 2018 at 8:21 am
We are actively working on removing the limitations on Additive Loading, especially light probes.
Simon TaylorJuly 12, 2018 at 12:49 pm
Thank you for the reply. Its good to know that this area is receiving some attention.
Simon TaylorJuly 10, 2018 at 5:10 pm
Here’s the bug I refered to marked as Postponed.
Postponed till when exactly?
西哥July 10, 2018 at 3:08 pm
终于修复了2d palette 的 bug
immeasurabilityJuly 10, 2018 at 3:07 pm
when fix all bugs?
Charles BeaucheminJuly 10, 2018 at 3:32 pm
2018.2 will receive regular updates with bug fixes until 2018.3 is out
please check our blog post about LTS and TECH streams here:
AlexanderJuly 10, 2018 at 2:55 pm
Congratulations on a new release!
With all the focus on Entity Component System, should we worry that the current development approach using GameObjects and MonoBehaviours will become obsolete and will be deprecated at some point?
Charles BeaucheminJuly 10, 2018 at 7:39 pm
We are not planning any deprecation of these any time soon. We will maintain what’s there with GameObjects and MonoBehaviours.
IgnisJuly 10, 2018 at 2:36 pm
That’s a long list of features… o.o
AndyJuly 10, 2018 at 2:27 pm
Good stuff, though much still in preview!
Planar Reflections? Do you have a link to info on this? Much needed
RemyJuly 10, 2018 at 3:26 pm.
AndyJuly 10, 2018 at 6:00 pm
Ah I see, any chance of some reduced quality version for the LWRP in future?
We still want to show some mirror effect on mobile
Dino FejzagicJuly 10, 2018 at 2:05 pm
Awesome! Keep it coming guys!
|
https://blogs.unity3d.com/2018/07/10/2018-2-is-now-available/?_ga=2.253992392.1335979215.1531302626-767168276.1529670619
|
CC-MAIN-2019-39
|
refinedweb
| 3,331
| 73.47
|
#include <GU_Decompose.h>
Definition at line 33 of file GU_Decompose.h.
Definition at line 37 of file GU_Decompose.h.
Returns a pointer to an array of half-edges which form the boundary cycle of numbered idx among all boundary cycles.
Returns index of the primitive component to which the idx-th boundary cycle belongs.
Definition at line 170 of file GU_Decompose.h.
Returns a pointer to an array of half-edges which form the idx-th boundary cycle among all boundary chains for the patch comp. (first index is zero).
Definition at line 173 of file GU_Decompose.h.
Definition at line 167 of file GU_Decompose.h.
Returns the number of boundary components of a given component.
Definition at line 93 of file GU_Decompose.h.
Returns the total number of boundary chains (cycles) in all the components. Note that some components may have no boundary chains and other may have multiple. For a 2-manifold maximal patch, i.e. one made of primitives, each boundary chain is a closed cycle of edges. For a 1-manifold maximal patch, i.e. oen made of edges, the boundary chain (when non-empty) consists of the two endpoints.
Returns the number of maximal manifold components.
|
http://www.sidefx.com/docs/hdk/class_g_u___decompose.html
|
CC-MAIN-2018-26
|
refinedweb
| 201
| 61.02
|
i need help on to remove profile tag which is blocking my work.
this make it difficult to preview my work
thanks
i need help on to remove profile tag which is blocking my work.
this make it difficult to preview my work
thanks
what browser and operating system are you using?
please make sure your browser is fully updated
This seems like a consistently reappearing issue with older browsers (which we technically do not support).
I am fairly sure the issue due to a “not-standard-yet” CSS API. I will put this up on the issue tracker just in case. But we can’t make promises for older browsers, unfortunately.
@Maskottchen, please update your browser to get past this for now.
What system are you on, isn’t it Windows 10? Can you not just update your browsers?
Otherwise, one temporary option might be to install tampermonkey, create a new script, add the code shown below.
// ==UserScript== // @name fCC Icon fix // @namespace // @version 0.1 // @description Fix for unsupported CSS // @author lasjorg // @match* // @icon // @grant none // ==/UserScript== (function() { const styleElement = document.createElement('style'); styleElement.innerHTML = ` .navatar { display: flex !important; } ` document.head.appendChild(styleElement); })();
It should work but I haven’t tested it all that thoroughly.
|
https://forum.freecodecamp.org/t/profile-blockage/469271
|
CC-MAIN-2021-31
|
refinedweb
| 207
| 66.74
|
table of contents
NAME¶setxattr, lsetxattr, fsetxattr - set an extended attribute value
SYNOPSIS¶
#include <sys/types.h> #include <attr/xattr.h> int setxattr (const char *path, const char *name, const void *value, size_t size, int flags); int lsetxattr (const char *path, const char *name, const void *value, size_t size, int flags); int fsetxattr (int filedes, const char *name, const void *value, size_t size, int flags);
DESCRIPTION¶Extended).
setxattr sets the value of the extended attribute identified by name and associated with the given path in the filesystem. The size of the value must be specified. pointed to by filedes (as returned by open(2)).
The flags parameter can be used to refine the semantics of the operation. XATTR_CREATE specifies a pure create, which fails if the named attribute exists already. XATTR_REPLACE specifies a pure replace operation, which fails if the named attribute does not already exist. By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.
RETURN VALUE¶On success, zero is returned. On failure, -1 is returned and errno is set appropriately.
If XATTR_CREATE is specified, and the attribute exists already, errno is set to EEXIST. If XATTR_REPLACE is specified, and the attribute does not exist, errno is set to ENOATTR.
If there is insufficient space remaining to store the extended attribute, errno is set to either ENOSPC, or EDQUOT if quota enforcement was the cause.
If extended attributes are not supported by the filesystem, or are disabled, errno is set to ENOTSUP.
The errors documented for the stat(2) system call are also applicable here.
|
https://manpages.debian.org/stretch/libattr1-dev/fsetxattr.2.en.html
|
CC-MAIN-2019-30
|
refinedweb
| 270
| 55.84
|
Tutorials > Win32 > Message Loop
In the last tutorial, we learnt how to create windows. You will have noticed in the previous
tutorial that the window appeared and then suddenly disappeared. This is because no messages
being sent to the window were processed. All messages were sent to the
DefWindowProc procedure.
This tutorial will be built upon the last. We will deal with what needs to be changed.
Contents of main.cpp :
Firstly we need to create a function that will be used to process windows messages. The
signature may remind you of the extremely long WinMain function.
We'll explain each part separately below.
An LRESULT is a signed result of message processing. This
is what is returned from the function.
CALLBACK is a calling convention for callback
functions. This is similar to the WINAPI macro which is used
as a calling convention for system functions. A callback function is something that is
called periodically by the application. You usually need to specify a function pointer
to a function.
HWND hwnd - This is the handle to the window that
received the message.
UINT msg - This is the message that was received.
There are too many messages to display below so we'll name a few that will be used
in the near future. Any other messages encountered in future tutorials will be explained
when they are reached.
A WPARAM and a LPARAM are
both message parameters. These give extra information on the messages received.
These are different for every message and will be discussed when the messages
are discussed.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
We use a switch statement to check what message has
been received.
switch(msg)
{
When the close button is pressed, we want to destroy the window. This can be done
by using the DestroyWindow function. This function takes one parameter, being
the handle to the window you want to destroy.
case WM_CLOSE :
DestroyWindow(hwnd);
break;
When you use the DestroyWindow function, it sends a WM_DESTROY
message. When this occurs, we want to send a quit message
to our application to exit the program. The PostQuitMessage can be used to
achieve this. This function takes one parameter, being the return code you wish to
use. We pass 0 as no error has occurred.
case WM_DESTROY :
PostQuitMessage(0);
break;
}
Any other message not processed must be passed onto the DefWindowProc function.
The function takes the same parameters passed onto our WndProc function.
return DefWindowProc(hwnd, msg, wParam, lParam);
}
One change we have to make is to point our lpfnWndProc variable in the
WNDCLASSEX structure to our new WndProc function instead
of the DefWindowProc.
wc.lpfnWndProc = WndProc;
After showing the window, we need to add what is called the message loop, this is used
to catch messages and pass them onto our WndProc function.
First we need to declare a MSG variable. This is used to hold
the message that has been caught by the window.
MSG msg;
To find out what the last message received was, we can use the GetMessage
function. The parameters for the function are given below.
LPMSG lpMsg - After the function call, the parameter
passed onto here will contain the message that was received.
HWND hwnd - This is used to specify what window the
message must be retrieved for. If a NULL is passed,
a message for any window will be retrieved.
UINT wMsgFilterMin & UINT wMsgFilterMax - This
specifies the range of messages to receive. Each message has an integer value so you can
specify exactly what messages you want to receive. If you pass 0
for both parameters, all messages are received.
The return value is 0 if a WM_QUIT
message has been received. If the return value is less than 0,
some error has occurred. We only want to continue if there was no error and if there
is no quit message. Remember that we caused a quit message to be sent if the window was
closed.
When the GetMessage function is called, the function halts until a message is received.
If you do not want this, you can use the PeekMessage function which doesn't halt,
even if there was no message. This is usually used if you are busy computing something else.
If you go through the OpenGL or
DirectX tutorials, you will use this.
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
2 Functions are required to send the message onto the WndProc function.
First we use the TranslateMessage function. The translate message function translates
virtual-key messages into character messages which is needed. This function takes
one parameter, being the MSG variable containing the message
received.
TranslateMessage(&msg);
The next function we need to use is the DispatchMessage function. This sends
the message through to the window procedure (WndProc). It also takes one MSG
parameter.
DispatchMessage(&msg);
}
Above we used the PostQuitMessage function and passed the value of 0.
This could have been a different value we had passed so we cannot just return 0
as normal. We return the msg.wParam value which is the return
code passed onto the PostQuitMessage function.
return (int)msg.wParam;
Congratulations. You should now be able to process simple windows messages. If you
run the program, you will notice that the window will stay on the screen until you
close the window. This will destroy the window and close the program efficiently.
Please let me know of any comments you may have : Contact Me
Back to Top
Read the Disclaimer
|
http://www.zeuscmd.com/tutorials/win32/06-MessageLoop.php
|
CC-MAIN-2016-50
|
refinedweb
| 913
| 66.74
|
An abstract layout item that provides generic methods for node based shapes such as polygon or polylines. More...
#include <qgslayoutitemnodeitem.h>
An abstract layout item that provides generic methods for node based shapes such as polygon or polylines.
Definition at line 29 of file qgslayoutitemnodeitem.h.
Constructor for QgsLayoutNodesItem, attached to the specified layout.
Definition at line 43 of file qgslayoutitemnodeitem.cpp.
Constructor for a QgsLayoutNodesItem with the given polygon nodes, attached to the specified layout.
Definition at line 49 of file qgslayoutitemnodeitem.cpp.
Method called in addNode.
Implemented in QgsLayoutItemPolyline, and QgsLayoutItemPolygon.
Method called in paint.
Implemented in QgsLayoutItemPolyline, and QgsLayoutItemPolygon.
Method called in readXml.
Implemented in QgsLayoutItemPolyline, and QgsLayoutItemPolygon.
Method called in removeNode.
Implemented in QgsLayoutItemPolyline, and QgsLayoutItemPolygon.
Method called in writeXml.
Implemented in QgsLayoutItemPolyline, and QgsLayoutItemPolygon.
Add a node in current shape.
Definition at line 93 of file qgslayoutitemnodeitem.cpp.
Definition at line 33 of file qgslayoutitemnodeitem.cpp.
Compute an euclidian distance between 2 nodes.
Definition at line 87 of file qgslayoutitemnodeitem.cpp.
Deselects any selected nodes.
Definition at line 108 of file qgslayoutitemnodeitem 73 of file qgslayoutitemnodeitem.cpp.
Returns the estimated amount the item's frame bleeds outside the item's actual rectangle.
For instance, if the item has a 2mm frame stroke, then 1mm of this frame is drawn outside the item's rect. In this case the return value will be 1.0.
Returned values are in layout units.
Reimplemented from QgsLayoutItem.
Definition at line 38 of file qgslayoutitemnodeitem.cpp.
Moves a node to a new position.
Definition at line 253 of file qgslayoutitemnodeitem.cpp.
Search for the nearest node in the shape within a maximal area.
Returns the index of the nearest node or -1 if no node was found.
Definition at line 207 of file qgslayoutitemnodeitem.cpp.
Gets the position of a node in scene coordinates.
Definition at line 232 of file qgslayoutitemnodeitem.cpp.
Returns the nodes the shape consists of.
Definition at line 45 of file qgslayoutitemnodeitem.h.
Returns the number of nodes in the shape.
Definition at line 93 of file qgslayoutitemnodeitem.
Reimplemented in QgsLayoutItemPolyline.
Definition at line 269 of file qgslayoutitemnodeitem.cpp.
Remove a node with specified index from the shape.
Definition at line 245 of file qgslayoutitemnodeitem.cpp.
Rescale the current shape according to the item's bounding box.
Useful when the shape is resized thanks to the rubber band.
Definition at line 293 of file qgslayoutitemnodeitem.cpp.
Returns the currently selected node, or -1 if no node is selected.
Definition at line 103 of file qgslayoutitemnodeitem.h.
Set whether the item's nodes should be displayed.
Definition at line 60 of file qgslayoutitemnodeitem.h.
Sets the nodes the shape consists of.
Definition at line 27 of file qgslayoutitemnodeitem.cpp.
Selects a node by index.
Definition at line 310 of file qgslayoutitemnodeitem.cpp.
Called when the bounding rect of the item should recalculated.
Subclasses should update currentRectangle in their implementations.
Definition at line 336 of file qgslayoutitemnodeitem.cpp.
Update the current scene rectangle for this item.
Definition at line 323 of file qgslayoutitemnodeitem.cpp.
Stores item state within an XML DOM element.
Reimplemented from QgsLayoutItem.
Reimplemented in QgsLayoutItemPolyline.
Definition at line 347 of file qgslayoutitemnodeitem.cpp.
Current bounding rectangle of shape.
Definition at line 168 of file qgslayoutitemnodeitem.h.
Max symbol bleed.
Definition at line 138 of file qgslayoutitemnodeitem.h.
Shape's nodes.
Definition at line 135 of file qgslayoutitemnodeitem.h.
|
https://qgis.org/api/3.4/classQgsLayoutNodesItem.html
|
CC-MAIN-2019-43
|
refinedweb
| 563
| 55.3
|
Java Classes and Objects keyword
class:
Main.java
Create a class named "
Main" with a
variable x:
public class Main { int x = 5; }
Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.); } }
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of
Main:
public class Main { int x = 5; public static void main(String[] args) { Main myObj1 = new Main(); // Object 1 Main myObj2 = new Main(); // Object 2 System.out.println(myObj1.x); System.out.println(myObj2.x); } }
Using Multiple Classes
You can also create an object of a class and access it in another class. This
is often used for better organization of classes (one class has all the
attributes and methods, while the other class holds the
main() method (code to
be executed)).
Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory/folder:
- Main.java
- Second.java
Main.java
public class Main { int x = 5; }
Second.java
class Second { public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } }
When both files have been compiled:
C:\Users\Your Name>javac Second.java
Run the Second.java file:
And the output will be:
You will learn much more about classes and objects in the next chapters.
|
https://www.w3schools.com/java/java_classes.asp
|
CC-MAIN-2020-50
|
refinedweb
| 243
| 53
|
Haskell Quiz/Verbal Arithmetic/Solution Jethr0
From HaskellWiki
< Haskell Quiz | Verbal Arithmetic(Difference between revisions)
Revision as of 10:47, 12 July 2007
I'm using a StateT monad inside a list monad for backtracking. The State monad keeps track of the digits associated with characters and also a carry state, that remembers the carried number from prior additions.
Several constraints are already implemented (like leading digits not being zero, all associations being unique), but of course there could be lot added (checking for zero, even/odd-ness, ...)
Solution should be far quicker than generic brute-force/backtracking since it tries to fail as early as possible and with more elaborate constraints it should become even faster!
I couldn't be bothered to write yet another regexp/parser, as that didn't really interest me.
module Main where import qualified Data.Map as Map import qualified Data.List as List import Data.Char (intToDigit) import Control.Monad import Control.Monad.State import Data.Maybe (fromJust) type Carry = Integer type Assocs = Map.Map Char Integer type St = (Assocs, Carry) parts = ["forty", "ten", "ten"] result = "sixty" -- turn words into pairs of digits digitize :: [String] -> String -> [([Char], Char)] digitize ps res = zip ps' (reverse res) where ps' = (List.transpose . map reverse $ ps) ++ repeat "" solve :: [String] -> String -> StateT St [] () solve parts' res' = do let digitPairs = digitize parts' res' let constraints = makeConstraints parts' res' sequence_ . map (setDigitPairs constraints) $ digitPairs {- construct constraints from actual data TODO: a+b=a => b=0 a+a=c => c even -} makeConstraints :: [String] -> String -> [StateT St [] ()] makeConstraints parts' res' = -- leading digits shouldn't be zero map (constraintCheck (guard . (0/=))) firsts where firsts = map head (res' : parts) constraintCheck cstr c = do (s,_) <- get case Map.lookup c s of Nothing -> return () Just i -> cstr i -- set digits, make per-digit check with carry and apply constraints setDigitPairs cstrs (ds,res) = do ls <- sequence . map placer $ ds r <- placer res (_,carry) <- get let r' = sum ls + carry guard $ r' `mod` 10 == r let carry' = r' `div` 10 modify (\(a,_) -> (a,carry')) sequence cstrs -- place number if not yet set and check for uniqueness, -- otherwise return already set value placer :: Char -> StateT St [] Integer placer l = do (assoc,_) <- get case Map.lookup l assoc of Just i -> return i Nothing -> do a <- lift [0..9] guard $ a `notElem` (Map.elems assoc) modify (\(ass,c) -> (Map.insert l a ass, c)) return a main = mapM_ print . Map.toList . fst . head $ execStateT (solve parts result) (Map.empty :: Assocs, 0)
|
http://www.haskell.org/haskellwiki/index.php?title=Haskell_Quiz/Verbal_Arithmetic/Solution_Jethr0&diff=prev&oldid=14224
|
CC-MAIN-2014-10
|
refinedweb
| 417
| 55.64
|
Confused about "files inside a JAR"807605 Jul 18, 2007 11:11 AM
I have a program that has a Properties file which I would like to "save" into the JAR file, so it is not outside the JAR.?
PS...writing demo programs is kind of fun :)?
Thanks for any help!Thanks for any help!
package SBX; import java.util.*; import java.io.*; public class MyProgram { // Instance Variables public MyProperties myProp = new MyProperties(); public String stringOne = "Will this be loaded?"; public String stringTwo = "How about this one?"; // Main Method public static void main(String[] args) { new MyProgram(); } // Constructors public MyProgram() { if ((new File("properties.txt")).exists()) { myProp.updateProgram(this); } System.out.println("1) " + stringOne); System.out.println("2) " + stringTwo); myProp.updateProgram(this); System.out.println("3) " + stringOne); System.out.println("4) " + stringTwo); myProp.updateProperties(this); // -- // // Now that we've "updated" stringOne & stringTwo and "updated" myProp and saved it, // we should be able to get the values "ONE" and "TWO" for print outs 1 & 2 when we next // run the program, instead of "Will this be loaded?" and "How about this one?", as we got during the first run. // However, the thing I need help with is saving the Properties to the JAR file so it's not accessable // outside of the JAR file. How can this be done? } } class MyProperties { // Instance Variables private Properties properties; // Constructors public MyProperties() { Properties defaults = new Properties(); defaults.setProperty("stringOne", "ONE"); defaults.setProperty("stringTwo", "TWO"); properties = new Properties(defaults); try { FileInputStream fis = new FileInputStream("properties.txt"); properties.load(fis); fis.close(); } catch (Exception e) { System.out.println("No properties file found, ignore this; one will be saved when the program exits."); } } // Methods public void updateProgram(MyProgram prg) { prg.stringOne = properties.getProperty("stringOne"); prg.stringTwo = properties.getProperty("stringTwo"); } public void updateProperties(MyProgram prg) { properties.setProperty("stringOne", prg.stringOne); properties.setProperty("stringTwo", prg.stringTwo); try { FileOutputStream fos = new FileOutputStream("properties.txt"); properties.store(fos, "A header"); fos.close(); } catch (Exception e) { e.printStackTrace(); } } }
PS...writing demo programs is kind of fun :)
This content has been marked as final. Show 4 replies
1. Re: Confused about "files inside a JAR"800322 Jul 18, 2007 11:16 AM (in response to 807605)You can't modify files in a JAR. Look at Preferences.
2. Re: Confused about "files inside a JAR"800308 Jul 18, 2007 11:23 AM (in response to 807605)Fossie,
Yup... you can jar up your properties file... you just need to add it to manifest file and jar (the program) takes care of the rest... google that there's loads of existing articles.
BUT, I don't think you can modify the properties file in the jar... it may be possible, but I just don't know how. Instead (I think) you ship your default properties file in the jar, but still save a local properties file to the same directory as the jar (obviously won't work for applets)... then you load your defaults, and the local settings over the top.
and PS I don't see how sticking a properties file in the jar would "secure" it in any fashion... it's just a zip file after all... would you care to elaborate?
Cheers,
Keith.
3. Re: Confused about "files inside a JAR"807605 Jul 18, 2007 6:37 PM (in response to 800308)Thanks for the replies!
I'm checking out the Preferences class right now.
And corlettk, what I think I was trying to get at with more secure was that it wouldn't be easily viewable / openable by a user. That, and it will make the program's directory look cleaner. I'll also try your suggestion, though, and read up about this manifest creature. I feel stupid not knowing fully what it is!
Cheers
4. Re: Confused about "files inside a JAR"807605 Jul 18, 2007 11:53 PM (in response to 807605)I wish I had known about Preferences much earlier than this thread, it would have saved me a ton of work on a ton of things.
Thanks for the help. :)
|
https://community.oracle.com/thread/2092528?tstart=87720
|
CC-MAIN-2017-22
|
refinedweb
| 674
| 68.06
|
Net::BitTorrent::Peer - Remote BitTorrent Peer
Net::BitTorrent::Peer represents a single peer connection.
new ( { [ARGS] } )
Creates a Net::BitTorrent::Peer object. This constructor should not be used directly. reserved if the peer has not completed the handshake.
as_string ( [ VERBOSE ] )
Returns a 'ready to print' dump of the object's data structure.
If called in void context,
the structure is printed to
STDERR.
VERBOSE is a boolean value.
As of version
0.049_8 of this module,
peer_disconnect callbacks are provided with a language agnostic,
numeric reason.
So far,
this is the list of possible disconnections:
The connection closed by remote peer for unknown reasons
We connected to ourself according to PeerID.
Remote peer attempted to create a session related to a torrent we aren't currently serving.
Occasionally,
this will also provide an
Infohash parameter for your callback.
A remote peer sent us a bad plaintext handshake. This is triggered when, after a particular infohash was implied in an encrypted handshake, the remote peer sent us a mismatched infohash in the plaintext handshake.
Bad plaintext handshake. May be malformed or, if encryption is disabled locally, the remote peer attempted an encrypted handshake.
This is given when the remote peer gives us a malformed packet. See also DISCONNECT_MALFORMED_HANDSHAKE.
Already connected to this peer.
When there are too many established connections with a particular peer (as determined by their PeerID),
we disconnect further connections with the reason.
This reason provides the remote peer's
PeerID when triggered.
Enough peers already! We've hit the hard limit for the number of peers allowed globally or per torrent.
This reason is given when a remote peer connects to us while the torrent they're seeking is busy being hash checked (potentially in another thread).
This is given when we and the remote peer are both seeds.
Peer failed to complete plaintext or encrypted handshake within 30s.
Peer has been connected for at least 3m and is neither interested nor interesting.
Failed to sync MSE handshake at stage five.
To import this list of keywords into your namespace,
use the
disconnect tag.
Please note that this API tweak is experimental and may change or be removed in a future version.
...it's also probably incomplete..
|
http://search.cpan.org/~sanko/Net-BitTorrent-0.052/lib/Net/BitTorrent/Peer.pm
|
CC-MAIN-2016-26
|
refinedweb
| 370
| 59.8
|
MPI_Info_set - Set a (key, value) pair in an MPI_Info object
#include <mpi.h> int MPI_Info_set(MPI_Info info, char *key, char *value)
key - null-terminated character string of the index key value - null-terminated character string of the value
info - info object _INFO_KEY - This error class is associated with an error code that indicates that a null key, empty key, or key that was longer than MPI_MAX_INFO_KEY characters was passed as an argument to an MPI function where it was not allowed. MPI_INFO_NOKEY - This error class is associated with an error code that indicates that a key that was looked up on an MPI_Info object and was not found. MPI_ERR_INTERN - An internal error has been detected. This is fatal. Please send a bug report to the LAM mailing list (see- mpi.org/contact.php ).
For more information, please see the official MPI Forum web site, which contains the text of both the MPI-1 and MPI-2 standards. These documents contain detailed information about each MPI function (most of which is not duplicated in these man pages).
infoset.c
|
http://huge-man-linux.net/man3/MPI_Info_set.html
|
CC-MAIN-2018-13
|
refinedweb
| 178
| 58.62
|
This is the second in the series on Data Attribute Notation (DAN). DAN is an object-oriented coding style that emphasizes data abstraction. DAN binds the abstract concepts defined in a project's analysis and design stages with the actual implementation stage.
This article covers how DAN can represent relationships that occur in most problems. Also discussed are functions as attributes and how DAN can represent iterator classes.
Relationships can be static or dynamic. A static relationship is always true, even if there are no instances of classes representing those relationships. For example, class definitions declare a static relationship between the components of the class, even if the class is never instantiated. This is the definition relationship. The truth value of dynamic relationships is determined during execution. For example, Ted is married to Alice as long as they are not divorced.
The married example shows that analysis and design determines whether a relationship is static or dynamic. If the system design does not support divorce, then Ted being married to Alice is a static relationship.
In a system that allows for divorce, marriage is a dynamic relationship. That is, the relationship must be checked at run-time to see if Ted is married to Alice. Note that even here, a static relationship is needed to relate Ted to Alice. For example, each person needs a Spouse attribute. Then you can ask if Ted's Spouse is Alice and Alice's Spouse is Ted. If they are, then Ted is married to Alice. Thus, there needs to be a static relationship like spouse to evaluate a dynamic relationship like marriage.
In this article, we use declarative code to represent relationships. Declarative code is easy to write and easy to check for correctness. It can be non-procedural, since most declarations may be re-ordered.
The rest of this article uses people and car owners as examples.
The listing below shows the function owner() that returns a non-zero value if the given person owns the given car model.
class Person { /*...*/ }; enum Model { Ford, Chevy }; Person ted(Ford); int owner(Person& p, Model m); // ... if (owner(ted,Chevy)) // ...
The value returned by the owner() is determined at run-time.
Non-member functions have these benefits:
They handle derived arguments fairly well.
They can be extended to n-ary relationships.
They express dynamic relationships well.
They handle non-commutative relationships well (i.e. they can distinguish between a @ b and b @ a, where @ is some relationship between objects a and b).
They can be overloaded to handle similar functions for different types, e.g. home owners or car owners
A non-member function can be overloaded, but can not serve as base for another function in the same sense that one class can serve as a base for another class. A member function of a base class, on the other hand, can be overridden by a derived class member function. Further, if the member function is virtual, invoking the correct function depends on the type of the instance for which the function is invoked. Thus, relationships represented by functions can be extended when using virtual member functions. Another benefit of using member functions is that the implied first argument (i.e. the this pointer) is not implicitly converted. This eases the problem of a function accepting either base or derived class instances as arguments.
Classes can represent static relationships. For example, an Owner relationship between a Person and a Car is shown below.
class Person { }; class Car { }; class Owner { Person p; // part 1 Car c; // part 2 };
A FordOwner relationship can be defined as a class using composition and inheritance:
class Ford : public Car { }; class FordOwner : public Person { Ford f; };
The listing below goes all the way and defines a ChevOwner only in terms of inheritance:
class Person { }; class Chev { }; class ChevOwner : public Person, public Chev {};
If a Person can be taxed and a Chev can get "fixed", then you can get a ChevOwner "fixed" and taxed all at the same time. This shows that a class shares all the attributes of any one of its inherited parts. If the class represents a relationship and it inherits some of its parts, then what is true for any one of its inherited parts applies to the relationship as a whole. When a relationship like Owner inherits some of its attributes, those parts should make sense in toto. Thus, the previous example shows poor design. In contrast, a useful derived class composed only of inherited base classes is a FilledCircle. It inherits all attributes from its two base classes: FillPattern and Circle.
DAN states that a class is defined by its attributes. Consistent with this is the fact that member and friend functions of a class are also attributes of the class.
For example, if an Owner has to renew his car license every year, an attribute Renewed can be defined. To check if this attribute is set, a function member isRenewed can be invoked.
int isRenewed() { return Renewed(*this)==1; } // . . . Owner o; // . . . if (o.isRenewed()) // . . .
The function isRenewed could also be defined as an attribute class, IsRenewed.
#include <iostream.h> #include <string.h> class Renewed { int r; public: Renewed(const int rr=0) { r = rr; } operator int() const { return r; } }; class Car { }; class Person { char *n; public: Person(const char *nn="") { strcpy(n,nn); } friend ostream& operator << (ostream& os, Person& p) { os << p.n; } }; class Owner : public Person { Car c; Renewed r; public: Owner(const char *n) : Person(n) { } operator Renewed() const { return r; } Owner& operator << (const Renewed& rr) { r = rr; return *this; } }; class IsRenewed { Renewed r; public: IsRenewed(const Owner& o) { r = Renewed(o); } operator int() const { return r; } }; int main() { Owner owner("Ted"); owner << Renewed(1); if (IsRenewed(owner)) cout << Person(owner) << " has renewed\n"; return 0; }
This shows that dynamic relationships can be converted into a static relationship of some kind as represented by an attribute class.
Relationships can be one-to-one, one-to-many, many-to-one and many-to-many. The previous relationships were all one-to-one. I have shown that a one-to-one relationship can be represented by a function or an attribute class. I would like to extend this to the other relationships. It seems fairly obvious that a one-to-many relationship can be represented by a function member where the class instance is the "one" and the "many" is the argument list. In the case of a non-member function, the first argument is the "one" and the "many" is the rest of the argument list. (Neither of these two implementations implies the order of evaluation of the arguments is the same as the order of the arguments.) In the case of the many-to-one and many-to-many relationships, things get more interesting.
The "many" could be represented by a single class containing the "many". This "many" class can any form mentioned earlier in the car and owner example. That is, it could a complete composite of all the "many", it could be a mixture of inherited parts and parts composing the "many" class. It could also be a completely inherited class where all the parts of the "many" are inherited. The form of the class is problem dependent.
In a many-to-one relationship, a member function can be used if the class instances represent the "many" and the "one" represents the single function argument.
In a many-to-many relationship, a function member can have its class instance represent the first "many" and the single arguments represent the second "many". Non-member functions have two arguments, each representing a "many".
In implementing one-to-many, many-to-one and many-to-many relationships, the most important concept is that the "many" can be represented by a single class. Given this fact, complete relationships can be represented by one class per relationship. This code section shows classes representing each of these relationships.
class Person { }; class Car { }; class People // any # of people { Person **pp; }; class Fleet // any # of cars { Car **cp; }; // 1:1 relationship of CarOwner class CarOwner { Person p; Car c; }; // 1:m relationship of one person // owning any number of cars class FleetOwner { Person p; // one person Fleet f; // many cars }; // m:1 relationship of a group of // people owning one Car class TaxiCoop { People p; // many people Car cp; // one car }; // m:m relationship of many cars // owned by many people class FleetOwners { People p; // many people Fleet f; // many cars };
Pure composition was used in all these classes. A mixture of composition and inheritance might be more appropriate, depending on the problem.
It is important to note that in any relationship, you must be able to encapsulate each side of the relationship into a class. For example, if a number of persons own a number of cars, you have a group called People and a group called Fleet. FleetOwners is the resulting relationship. In the case of the one-to-one relationship called CarOwner, one side was encapsulated into one Person and the other side was encapsulated into a Car.
The relationship classes we have just discussed often contain collections. Iterator classes are used to iterate over collections of objects. The rest of this article uses iterator classes to show how code normally thought to be procedural in nature can be written in a declarative fashion using DAN.
Normally, an iterator class has next(), prev() and reset() function members or their equivalent.
For example, consider iterating over the collection FleetOwner so that a report is produced showing the list of cars owned in the collection Fleet. A classic C++ program using iterators would look something like this.
class FleetOwner { friend class FOIter; Person p; Fleet f; }; class FOIter { int status; // =0 if empty CurrElem c; // save cur elem public: FOIter(FleetOwner& fo); int next(); // =0 at end int prev(); // =0 at start void reset(); friend ostream& operator << (ostream& os, FOIter& foi) { return os << foi.c; } }; int main() { FleetOwner fo; FOIter foI(fo); foI.reset(); while(foI.next()) cout << foI << endl; return 0; }
A more DAN-like approach for the same example would look thus.
class FleetOwner { friend class FOIter; Person p; Fleet f; }; class Next { }; class Prev { }; class Reset { }; class CurrElem { public: friend ostream& operator << (ostream& os, CurrElem& c); }; class FOIter{ int status; // =0 if empty CurrElem c; // save cur elem public: FOIter(FleetOwner& fo) { status = 0; } operator Next(); operator Prev(); operator Reset(); operator int() { return status; } friend ostream& operator << (ostream& os, FOIter& foi) { return os << foi.c; } }; int main() { FleetOwner fo; FOIter foI(fo); Reset(foI); while(Next(foI)) cout << foI << endl; return 0; }
In the listing above, I have written executable code when my intention was to illustrate writing declarative statements. To express this fragment of code in declarative format, we need to agree that all fragments have a basic form. The form is: an initialization stage, Init; a main stage, Body; and a termination stage, Term; any or all of which can be empty. Further, when two fragments are placed together, the result is also a fragment. As such, we can declare any fragment to be a class of the simplified form. The following example illustrates this technique.
class Code { }; class Init : public Code { }; class Body : public Code { }; class Term : public Code { }; class Fragment // order of parts { // in this class Init ii; // determines the Body bb; // order of Term tt; // initialization public: Fragment(Init i,Body b,Term t) : ii(i), bb(b), tt(t) { } Fragment() { } Fragment& operator << (Fragment& f); };
This contains no definition for the insert operator << function. This was intentional. Combining code may be problem and language dependent. In a sequential machine, the termination stage of one fragment can be concatenated with the initialization stage of the next fragment. In a parallel machine, all initialization stages may be executed in parallel. In a C++ program, there is a difference between static and dynamic data. Thus, initialization code would need to be subdivided in those two types of data before initialization could be performed. Regardless of these variations, the listing below is true.
Init i1, i2; Body b1, b2; Term t1, t2; Fragment f1(i1,b1,t1); Fragment f2; f2 << f1; Fragment p1(i2,b2,t2); Fragment p2; p2 << f1 << f2;
Both f1 and p1 are statically defined fragments. This is consistent with languages like C++ that are static in nature. Languages like LISP exhibit behavior like f2 and p2 that can only be evaluated at run-time.
Let us return to the example of the iterator. For simplicity sake, let strings of tokens serve as arguments to the Init, Body and Term constructors.
Init i1("FleetOwner fo; FOIter foI(fo); "); Init i2("foI << r;"); Body b2("while(Next(foI)) cout << foI << endl; "); Term t1("return 0;"); Fragment f1(i2,b2,Term("")); Fragment program(i1,f1,t1);
This is pure declarative in nature. The only sequencing rule used is that things must be defined before use.
In this part of the series, we have discussed relationships. We have shown that a relationship can be static or dynamic as defined by the problem domain. Representing a relationship can be done in a number of ways. We mainly discussed declarative code using classes. In using the classes we also discussed the effect of using composition, partial inheritance and total inheritance. We introduced classes as forms of relationships. We also discussed member and friend functions as forms of dynamic relationships. In defining many-to-one and one-to-many relationships, we spoke about the concept of combining the "many" into classes expressing the commonalty of the "many". We used iterators as an example of coded relationships and showed how they could be represented using DAN. From this step, we became more abstract and illustrated how any program can be represented using DAN-type declarative statements.
|
https://accu.org/index.php/journals/568
|
CC-MAIN-2020-29
|
refinedweb
| 2,300
| 53.61
|
Suppose we have a non-negative integer called num, we have to check whether it is a palindrome or not, but not using a string.
So, if the input is like 1331, then the output will be true.
To solve this, we will follow these steps −
ret := 0
x := num
while num > 0, do −
d := num mod 10
ret := ret * 10
ret := ret + d
num := num / 10
return true when x is same as ret
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool solve(int num) { int ret = 0; int x = num; while(num > 0){ int d = num % 10; ret *= 10; ret += d; num /= 10; } return x == ret; } }; main() { Solution ob; cout << (ob.solve(1331)); }
1331
1
|
https://www.tutorialspoint.com/palindrome-integer-in-cplusplus
|
CC-MAIN-2021-17
|
refinedweb
| 130
| 71.89
|
I am trying to learn how to use classes.The book i am using gave me this example.
In Vechile.as
package{
import flash.display.MovieClip;
import flash.events.Event;
public class Vehicle extends MovieClip{
public var _gasMileage:Number;
public var _fuelAvailable:Number;
public var _milesTraveled:Number =0;
public var _go:Boolean;
public function Vehicle(mpg:Number=21, fuel:Number=18.5){
_gasMileage=mpg;
_fuelAvailable = fuel;
this.addEventListener(Event.ENTER_FRAME, onLoop, false,
0, true);
}
public function onLoop (evt:Event):void{
if (_go){
_fuelAvailable--;
_milesTraveled+=_gasMileage;
if (_fuelAvailable < 1){
this.removeEventListener(Event.ENTER_FRAME,
onLoop);
}
trace(this, _milesTraveled,_fuelAvailable);
this.x=_milesTraveled;
}
}
public function go():void{
_go = true;
}
}
}
In the main.fla
In frame 1
var vehicle:Vehicle = new Vehicle(21,18.5);
addChild(vehicle);
vehicle.go();
when I compile it gives an output error.
Error #2136: The SWF file contains invalid data.
at Vehicle/frame1()
I am stumped
If I recreate the files and scenario that would support what you show, it works fine. Describe what you have done as far as creating/placing the files and the Vehicle object.
What i did is created Vehicle.as and typed in the above text. Then I created the Main.fla. I entered next three lines into script editor for frame 1. I then assign Vehicle to document class box in the property box. After that I hit Crtl + enter, and the output dialog box popped up the error.
" I then assign Vehicle to document class box in the property box" Do not assign the Vehicle as the document class... remove it from there.
In the main file, if you didn't already create one, create a movieclip symbol (just draw a shape in it for now). Right click the symbol in the library and select the Linkage option. In the interface that appears, select the option to Export for Actionscript, and assign it the Class name "Vehicle" in the field labeled "Class"
Make sure you save the Vehicle.as file after you put the code into it and have that file in the same folder as your Main.fla file.
If you do the things I just described you should see an instance of the movieclip moving across the stage when you run the file.
Thank you. That sure would have been a nice step for the book author to put in.
You're welcome
|
http://forums.adobe.com/message/4410796
|
CC-MAIN-2014-10
|
refinedweb
| 393
| 67.76
|
in reply to Re: Finding CPU stats on Win32?in thread Finding CPU stats on Win32?
-- philip
We put the 'K' in kwality!
Detecting hyperthreading has to be done from assembler, and I'm not aware of any Win32 API that provides that information. There is an article on the Intel website that explains the intracacies.
Update: Here's an implementation in D. It should be trivial to convert to C.
import std.stream;
import std.stdio;
void main ( ) {
int ht_supported = 0;
int cores_per_socket = 1;
asm{
mov EAX, 0;
cpuid;
test EAX, 0x10000000;
jz NO_HYPER;
mov ht_supported, 1;
mov EAX, 4;
cpuid;
and EAX, 0xfc000000;
shr EAX, 26;
add EAX, 1;
mov cores_per_socket, EAX;
NO_HYPER:;
};
if( ht_supported ) {
printf( "Hyperthreading is supported and there are %d cores pe
+r cpu\n",
cores_per_socket );
}
else {
printf( "Hyperthreading is not supported on this processor\n"
+);
}
}
[download]
Update2: I also turned up this quite comprehensive cpu features detector sample on MSDN
1. Keep it simple
2. Just remember to pull out 3 in the morning
3. A good puzzle will wake me up
Many. I like to torture myself
0. Socks just get in the way
Results (283 votes). Check out past polls.
|
http://www.perlmonks.org/?node_id=448332
|
CC-MAIN-2016-44
|
refinedweb
| 198
| 75.5
|
Properties in C++
When I wrote a property using C#, I wondered why such a feature doesn't exist in C++. It was a challenging question and because I know how important such a thing is to C++ developers, I spent three days developing this article. I hope you will find it useful also.
What Properties Are
Properties are like variables that store data, but trigger events that fire when reading or writing data from them. In other words, a property is an interactive variable evaluating itself and having different values when reading and writing to#.
You will understand how to use the macros that were written to declare and implement properties. If you are an expert C++ developer and you need to understand how it works, you will not face any problem in reading the macros defined in "Properties.h".
Why Properties Are Important
Imagine that you need to write an object that represents a person. This object may contain data such as:
Full Name Age Year of birth Gender
It could be written using C++, as follows:
class Person { public: Person( ){} virtual ~Person( ){} private: //data members char m_fName[20]; char m_lName[20]; UINT m_YearOfBirth; bool m_bGender; };
Note: In most cases, you can't define a data member as public to be used directly because the data member should be maintained through the business logic that is implemented by the object.
If you need to get or set the value of m_bGender, you need to implement methods as shown below.
class Person { public: Person( ){} virtual ~Person( ){} void SetGender(bool bGender) {m_bGender = bGender;} bool GetGender() {return m_bGender;} private: //data members char m_fName[20]; char m_lName[20]; UINT m_YearOfBirth; bool m_bGender; };
The disadvantage of using this method is that you need to know which method should be used to change the Gender. But with properties, life is better because to do the same thing all you need is to know the name of the property you need. Also, a single property can support different data types. In other words, in the example, you can let Gender accept string and Boolean values to use it, as shown below.
Person.Gender = "Male";
or
Person.Gender = true;
Of course, life now became much easier with Properties and the code now also became more readable.
Property Declaration
Now, I will show you how to write properties. Start by writing the Gender property as shown below.
class Person { public: Person( ){} virtual ~Person( ){} Begin_Property(char*,Gender) __get(char*,Gender) _set(char*); _get(bool); _set(bool); __release(Gender) End_Property(Gender) private: //data members char m_fName[20]; char m_lName[20]; UINT m_YearOfBirth; bool m_bGender; };
Now, look at the code. I started with the Property definition by using the Begin_Property macro. It takes two parameters, property data type and property name. Because Gender property is a string property, it should be char*. After I started defining my property, I needed to declare the events get(ers) and set(ers) that will fire each time it's being used, as shown below.
// This will fire _set(bool) event Person.Gender = true; // this will fire _get(bool) event bool gender = Person.Gender ; //This will fire _set(char*) Person.Gender = "Male"; //This will fire _get(char*) printf("Gender :%s\n",(char*)Person.Gender);
_get and _set are two macros that take one parameter that represent the data types that can be accepted by the property. You can notice the data type of _set and _get events independent of the data type of property. In other words, although the data type of the "Gender" property is char*, it has bool getters and setters. In this way, it can accept as Boolean or string values as shown above.
The last two macros I used are _release to release the memory it allocates (this will be covered in detail later) and End_Property to close property declaration and both macros take property name as a parameter.
Property Implementation
After declaring properties, you need to implement set(ers) and get(ers). You can do so in the same place as shown below.
. . . Begin_Property(char*,Gender) __get(char*,Gender) _set(char*) { //do something here return Gender; } _get(bool) { //do something here return iValue; } _set(bool) { //do something here return iValue; } __release(Gender) End_Property(Gender) . . .
You can implement it by using implementation macros, but before showing you how to use those macros, let me explain two other points: what macro __get is and why set(ers) should return a value. All you need to do in _get(char*) is just to return a pointer to it this way: "return Gender;". This is what __get does. __get is the default getter of the Property; because "Gender" is a char* property, you used it in this way: "__get(char*,Gender)".
Now, to the second question, why should set(ers) return value like get(ers)? Simply, in C++ set(ers) can act as get(ers), as shown below.
bool bGender = Person.Gender = true;
Now, implement the Gender Property by using Imp_set and Imp_get macros. Both macros take three parameters: data type, Class name, and property name, as shown below.
Imp_set(char*,Person,Gender) { PROPERTY_PROLOGUE(Person,Gender) if (!Gender) Gender = new char[7]; if (strlen(iValue)<6 ) { int result; if ((result=strcmp(iValue,"Male"))==0) pThis->m_bGender = true; else { if ((result=strcmp(iValue,"Female"))==0) pThis->m_bGender = false; } if(result==0) strcpy(Gender,iValue); } return Gender; } Imp_set(bool,Person,Gender) { PROPERTY_PROLOGUE(Person,Gender) if (!Gender) Gender = new char[7]; if (pThis->m_bGender = iValue) strcpy(Gender,"Male"); else strcpy(Gender,"Female"); return (bool)iValue; } Imp_get(bool,Person,Gender) { PROPERTY_PROLOGUE(Person,Gender) return pThis->m_bGender; }
Because set(ers) and get(ers) can't access class members directly, you used the PROPERTY_PROLOGUE macro. It defines a pointer to the class of the property as shown above, called "pThis".
Also, in class termination, you need to free the memory and any allocated resources being used by the property. This is done by using the function __release macro. __release is a default release macro and its job is done as shown below.
if (Gender) { delete Gender; Gender = NULL; }
You also can implement release events yourself by using _release and Imp_release, as shown below.
Imp_release(Person,Gender) { // Release allocated resources here. }
The Demo Project
This project demonstrates how to write properties and how properties can affect each other. For example, in the person class, the YearOfBirth property changes the age value property and vice versa. Also, you can use class as property datatype; for example, I used CTime as a datatype of "LeaveDate" and "ContractDate" properties.
Finally, I hope I had covered the subject as much as I can/ For any inquires feel free to email me. Thanks a lot.
|
http://mobile.codeguru.com/cpp/cpp/algorithms/general/article.php/c13039/Properties-in-C.htm
|
CC-MAIN-2017-34
|
refinedweb
| 1,110
| 53.81
|
Christmas Competition 2016 - ExecuteInMainThread
On 07/12/2016 at 02:16, xxxxxxxx wrote:
Hello everyone,
nothing but glory to win here.
But I thought maybe some of you have fun in a small Christmas "riddle".
There came up a request for a simple to use ExecuteInMainThread function (execute on main thread).
These are the requirements, that have to be fulfilled to win nothing:
- Arbitrary functions should be executed in main thread
- Arbitrary parameter constellations for the called function would be nice
- No constraints on where the function is called (e.g. parallel calls from multiple threads have to work)
- Should be easy to use/integrate in any project
- Registering of plugins to reach the goal is explicitly allowed
- Deadline you need to reach to get absolutely nothing: 2017-01-15
So, I hope, some of you are eager to win nothing. Please post your solutions in this thread.
Hopefully you will have fun.
I'm sure our community will be thankful, but we won't tell you, as you are supposed to get nothing.
Have a nice Christmas time,
your SDK Team
On 15/12/2016 at 02:20, xxxxxxxx wrote:
Does we must stick to python or it can be a c++ plugin? :)
And moreover even if it's a compition can we talk about our implementation?
On 16/12/2016 at 00:42, xxxxxxxx wrote:
Hello,
talking about and presenting your implementation is the only point of this "competition"
Please feel free to try your ideas in Python or C++, just as you like.
best wishes,
Sebastian
On 19/12/2016 at 18:11, xxxxxxxx wrote:
My first intuition was to deal with c4d.SpecialEventAdd().
The uggly methold but that will work ! Trust me it's very dirty :p
First you need to register 5 unique id for the SpecialEventAdd. ( I will explain it later why)
Ask for a unique Call ID(all current in use CallID are stored into a container in worldcontainer)
Take any kind of python data. Do a bits representation of if and then convert it in a list of integer.
And at each time you call the SpecialEventAdd() with this bit in argument 1. And the second arguments is an Unique call ID(unique to each script you will understand the use of it after)
In your PluginMessage plugin you catch this message and check if this unique call ID existst if not it initialize new dic with the unique call ID. And after each call data are happend to the current data.
In your script after each byte are passed, you call another specialEventAdd with a new id to tell it's finish for this call ID, and arg2 with a int checksum representing the byte (like that we can confirm we got everything ok in the main thread)
For the variable idea are the same but just a litlle change
You loop into each variable to 2 SpecialEventAdd
first SpecialEventAdd with arg1 = data, arg2=call ID
second arg1=int corresponding of an enum of the datatype, arg2= callID
After the execution MessagePlugin return value overide the container stored in the worldcontainer at ID(callID) with a container contening return value.
Then finaly our script read back the return value and then free the CallID into the container
Pro: easy to setup
Pro: accept any kind of data
Con: Not optimized at all
My second approch is to use the same namespace. In this nothing fancing.
Just create an empty class put values into this class
Then do a c4d.SpecialEventAdd()
Register any plugin who is in the mainThread.
Catch this call.
Read data from the class and that's it !
Pro: Clean way
Con: Is not portable
Con: Is not easy to use for other developper
Maybe I will talk about some other way ! :)
Got some others idea but still got some stuff to test before. (one usin HyperFile other are using some 3rd-party solution like memcache)
On 23/12/2016 at 15:01, xxxxxxxx wrote:
I'm going to share part of my solution since it's not clear if I can share one of the modules. I have two modules -- One is a simple C4D plugin, the other is a normal Python module.
I called the C4D plugin executeInMainThreadListener.pyp. Here it is:
> import c4d
>
> from c4d import plugins
>
>
>
>
> import c4d_threading
>
>
>
>
> # Plugin IDs 1000001-1000010 are reserved for development.
>
> # You may use these freely to test scripts, but must request an ID in
>
> # order to release them.
>
> PLUGIN_ID = 1000001
>
>
>
>
> class ExecuteInMainThreadListener(c4d.plugins.MessageData) :
>
> '''
>
> Listens to messages from that should be executed in the main thread.
>
> Use executeDeferred or executeInMainThreadWithResult.
>
> '''
>
>
>
> def CoreMessage(self, messageId, bc) :
>
> '''Override.'''
>
>
>
> if messageId == PLUGIN_ID:
>
> c4d_threading._process_queued()
>
>
>
> return True
>
>
>
>
> if __name__ == '__main__':
>
> plugins.RegisterMessagePlugin(PLUGIN_ID, 'executeInMainThreadListener', 0, ExecuteInMainThreadListener())
>
>
>
The c4d_threading module is where you would call executeInMainThreadWithResult(fn, *args, **kwargs).
There should be a global queue in this module that stores the function to execute, the args, and kwargs. executeInMainThreadWithResult will add these to the queue, call c4d.SpecialEventAdd(PLUGIN_ID), then block using a threading condition. c4d.SpecialEventAdd will cause CoreMessage to run in the main thread. In CoreMessage, fn, args, and kwargs will be dequeued and fn will be called. After the function is executed, it will store the result in a global variable inside of c4d_threading, and notify and release the condition so that executeInMainThreadWithResult can continue running. The rest of executeInMainThreadWithResult will get the result from the global variable and return it.
For error handling, you can do it the same way you do with the result. Store the exception in a global variable, then raise it at the end of executeInMainThreadWithResult.
_<_img src="" height="720" width="1280" border="0" /_>_
There's a big warning you should know about though. If ExecuteInMainThreadListener is not running, calling executeInMainThreadWithResult will freeze Cinema 4D and you will have to force it to close. This is because executeInMainThreadWithResult waits for its condition to be released by the plugin.
I hope this helps anyone who has had threading issues in C4D.
On 26/12/2016 at 02:11, xxxxxxxx wrote:
I've written a number of small helper libraries over the years that I put on GitHub. Just recently I merged
them into one "bigger" Python package. One of the modules is nr.concurrency which I've always used for
asynchronous jobs that I have to synchronize with the main thread somehow. :)
Unfortunately there's no docs yet, but the code is fairly well documented. The solution that @erk
proposed is what I would usually be going for if I also needed to wait for the result of the function
running in the main thread. With the nr.concurrency.Job class, it would look something like this:
*Please make sure you import 3rd party modules safely*
with localimport('res/modules') as _imp: _imp.disable(['nr']) from nr.concurrency import Job, SynchronizedDeque, synchronized class JobRunner(c4d.plugins.MessageData) : PluginID = ... Jobs = SynchronizedDeque() def CoreMessage(self, msg, bc) : if msg == self.PluginID: with synchronized(self.Jobs) : jobs = list(self.Jobs) self.Jobs.clear() for job in jobs: job.start(as_thread=False) return True @classmethod def PutJob(cls, job) : cls.Jobs.append(job) c4d.SpecialEventAdd(self.PluginID) def RunInMainThread(func, *args, **kwargs) : job = Job(lambda: func(*args, **kwargs)) JobRunner.PutJob(job) # Blocks until the Job is finished or re-raises the exception that occurred # in the function. return job.get()
Now, usually I don't want to wait for the result of the function executed in the main thread. I could
instead just return the Job object from RunInMainThread(). But most of the time I use the EventQueue
object to trigger certain actions for example in a Dialog.
with localimport('res/modules') as _imp: _imp.disable(['nr']) from nr.concurrency import EventQueue events = EventQueue() events.new_event_type('preset-loaded', True) events.new_event_type('presets-changed', True) events.new_event_type('tree-changed', True) events.new_event_type('reloaded', True) events.new_event_type('show-dialog', False) events.new_event_type('request-exception', False) class Dialog(c4d.gui.GeDialog) : def CoreMessage(self, msb, bc) : if msg == c4d.EVMSG_CHANGE: self.ProcessEvents() return True def ProcessEvents(self) : for ev in events.pop_events() : self.ProcessEvent(ev.type, ev.data) def ProcessEvent(self, event, data) : if event == 'preset-loaded': self.grid.Redraw() elif event == 'presets-changed': self.storage.reload() self.UpdateGrid() elif event == 'tree-changed': self.storage.reload() self.UpdateGrid() self.tree.Refresh() elif event == 'reloaded': self.UpdateGrid() self.tree.Refresh() elif event == 'show-dialog': c4d.gui.MessageDialog(str(data)) elif event == 'request-exception': self.storage.online_node.error = "Connection error" logger.debug(data) else: logger.warn("unhandled event: {0!r}".format(evnet)) # Somewhere from a thread events.add_event('presets-changed')
Cheers,
Niklas
|
https://plugincafe.maxon.net/topic/9847/13260_christmas-competition-2016--executeinmainthread
|
CC-MAIN-2020-40
|
refinedweb
| 1,440
| 57.87
|
Lexical::Types - Extend the semantics of typed lexicals.
Version 0.12
{ :
Strpackage to be defined ;
Strto be a constant sub returning a valid defined package.
so make sure you follow one of those two strategies to define your types.
This pragma is not implemented with a source filter.
import [ as => [ $prefix | $mangler ] ]
Magically called when writing
use Lexical::Types. All the occurences of
my Str $x in the current lexical scope will be changed to call at each run a given method in a given package. The method and package are determined by the parameter
'as' :
TYPEDSCALARmethod in the
Strpackage will be called.
use Lexical::Types; my Str $x; # calls Str->TYPEDSCALAR
$prefixis passed as the value, the
TYPEDSCALARmethod in the
${prefix}::Strpackage will be used.
use Lexical::Types as => 'My::'; # or "as => 'My'" my Str $x; # calls My::Str->TYPEDSCALAR
$mangler, it will be called at compile-time with arguments
'Str'and
'TYPEDSCALAR'and is expected to return :
use Lexical::Types as => sub { return $_[0] =~ /Str/ ? @_ : () }; my Str $y; # calls Str->TYPEDSCALAR my Int $x; # nothing special
Magically called when writing
no Lexical::Types. Turns the pragma off..
A C compiler. This module may happen to build with a C++ compiler as well, but don't rely on it, as no guarantee is made in this regard.
XSLoader (standard since perl 5.006).
Vincent Pit,
<perl at profvince.com>,.
You can contact me by mail or on
irc.perl.org (vincent).
Please report any bugs or feature requests to
bug-lexical-types at rt.cpan.org, or through the web interface at. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
You can find documentation for this module with the perldoc command.
perldoc Lexical::Types
Tests code coverage report is available at.
Inspired by Ricardo Signes.
Thanks Florian Ragwitz for suggesting the use of constants for types.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
|
http://search.cpan.org/dist/Lexical-Types/lib/Lexical/Types.pm
|
CC-MAIN-2014-23
|
refinedweb
| 341
| 66.74
|
The.
And every non-Sun/Oracle JAR files has a copy of some or all of the Java API embedded in it because it’s technically necessary to include a shadow of the API in compiled bytecode in order to invoke the API.
Let me demonstrate.
Here’s a perfectly legal Java program that I wrote and I own the copyright to:
public class HelloWorld { public static void main(String[] args) { int strlen = 0; for (int x = 0; x < args.length; x++) { strlen += args[x].length(); } System.out.println("Hello, world, you passed in "+args.length+" arguments, "+ "total size: "+strlen); } }
Nothing in there looks infringing. I run the program through the OpenJDK Java compiler,
javac which results in a
HelloWorld.class file. According to how the industry has used Java and compilers in general, the resulting bytecode is a derivative work of the source code and I own the copyright in the source code.
So, let’s take a look at the resulting bytecode, disassembled with
javap:
dpp@crown:~/proj/dpp-blog/images$ javap -c HelloWorld Compiled from "HelloWorld.java" public class HelloWorld { public HelloWorld(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_0 1: istore_1 2: iconst_0 3: istore_2 4: iload_2 5: aload_0 6: arraylength 7: if_icmpge 25 10: iload_1 11: aload_0 12: iload_2 13: aaload 14: invokevirtual #2 // Method java/lang/String.length:()I 17: iadd 18: istore_1 19: iinc 2, 1 22: goto 4 25: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 28: new #4 // class java/lang/StringBuilder 31: dup 32: invokespecial #5 // Method java/lang/StringBuilder."<init>":()V 35: ldc #6 // String Hello, world, you passed in 37: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 40: aload_0 41: arraylength 42: invokevirtual #8 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 45: ldc #9 // String arguments, 47: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 50: ldc #10 // String total size: 52: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 55: iload_1 56: invokevirtual #8 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder; 59: invokevirtual #11 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 62: invokevirtual #12 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 65: return }
Oh my… look, some of the Java APIs snuck right into the code.
In fact, the JVM requires the call site (the place where code is called) to include information about the API that’s being called in order for the JVM to figure out the method to be called. And not just the method name, but also the parameter types passed in and the expected return type.
So each and every compiled JAR contains some part of the Java API embedded in it. Each and every compiled JAR file is a copyright violation under the Oracle decision.
“But,” you say, “the JAR file doesn’t contain all of the disputed API.”
First, how much is enough. The Oracle court explicitly rejected the argument that the APIs were a small part of the overall work of the Java base classes and that percentage arguments were not persuasive.
Second, for repositories like Maven Central that house tens of thousands of JAR files, substantially all of the Java APIs are copied into the collective works that are housed in those JAR files.
What to do?
If I were hosting a ton of JAR files, I’d be on the phone to my lawyers trying to figure out what to do. Yeah, maybe there’s an inducement argument because Oracle distributes
javac and therefore is inducing me to copy the Java APIs. But still, it’s a technical violation of the Oracle court’s decision.
If I were the Apache Software Foundation or the Free Software Foundation, I’d be filing an ex parte motion this morning to get a stay of the Oracle decision because it means that what we’ve been thinking is our software that we can license on our open terms in fact contains Oracle copyrighted code and we will have to suspend all of our JVM-related open source projects.
Oh, and I should point out that if Oracle claims that the APIs copied into the JAR files are not covered by copyright, then all Google has to do is pull all the JAR files from Maven Central, find all the Java API references in all those JAR files and use that information to declare an API for Android. That’s about 10 man-days of effort, at most.
You just say so. I don’t think this is related to the court decision. Please back up your claims with some references. It looks like complete bullshit.
|
http://www.javacodegeeks.com/2014/05/okay-everybody-who-touches-java-bytecode.html
|
CC-MAIN-2015-35
|
refinedweb
| 807
| 62.68
|
I'm seeing a behavior that would seem to indicate that partitioning based on numerical values for user-defined parallelism (using the annotation) must have a contiguous range of values. For example, if I have 20 channels of data each with a chNum attribute in the range of 0-19 and I set the width of the parallelism to 20 and the partitioning attribute to chNum it works perfectly as expected with each parallel region processing a different channel. However, if I filter the input to the parallel region to eliminate a couple of the channels but add a couple at the top end (i.e. the chNum values are now 0-3, and 6-21, which still amounts to a total of 20 channels, but with channels 4 and 5 replaced with 20 and 21) . Two of the parallel regions show as not processing any values (presumably they might still be looking for chNum's 4 and 5 which are no longer in the input stream, but that's a guess) and channels 19 and 20 never appear in the output.
As a followup test I then increased the width to 22 and still got the two "unused" parallel regions, but the data for the additional two channels did appear in the output. The makes me believe that something in the splitter for numerical partitioning attributes is expecting a contiguous set of values not just a unique mapping to number specified by the width. Is that supposed to be the case? What else might be impacting this behavior? If it matters, this on v4.1QSE
Answer by Michael.K (1380) | Jan 22, 2016 at 02:39 AM
Hello Jim.
Excerpt from the Knowledge Center:
When the parallel region is partitioned, the splitter uses the partition keys, which are the attribute values of each tuple, to determine where it routes the tuple. The splitter achieves the routing process by creating a hash from the set of tuple attributes.
This means, even if you use a contiguous range of integer values, it is not ensured that every channel is used. It depends on the hash value that is generated. You can think of the routing as a Split operator with the following index parameter:
index : hashCode(attribute)
This ensures only that tuples with the same attribute value are routed to the same channel.
Regards, Michael.
Answer by Jim Sharpe (68) | Jan 22, 2016 at 10:26 AM
Hi Michael,
Thanks for the quick response. However I still don't understand why I end up missing values (i.e. not processing tuples) from some channels if I have sufficiently wide parallelism. I.e. if I have 20 different unique values in the partitioning attribute and have a width of 20. I would expect that all 20 parallel sections will get used and output for tuples containing all 20 of those attribute values will be produced. Neither is what I am observing. It appears that tuples with attribute values greater than the specified parallel width are not getting routed anywhere, but instead are getting dropped even though there is sufficient width for the hashing algorithm to map each value to a unique parallel region. Furthermore, the hashing algorithm which decides where to route the tuples is also not mapping values to two of the available parallel sections as no tuples are procssed by them even though I have exactly the same number of attribute values as the width of the parallelism. Because the hashing works fine with contiguous (uint32) attribute values and things do not appear to function correctly when there is a gap I can't help but wonder if there is a bug.
Hello Jim.
Is it possible that you paste your good & your bad application here?
My expectation is that every tuple gets processed. It might happen that the some channels process more than one tuple, but at the end, all tuples must be processed.
From your explanation I understand that you noticed tuple loss, so I want to do some investigation and need your applications for this.
Thank you in advance.
Answer by Jim Sharpe (68) | Jan 22, 2016 at 01:43 PM
The issue is occurring within a much larger app so I can't include the entire example but below are some slightly tweaked extracts that illustrate what the code is doing. And yes I'm definitely experiencing unexpected tuple loss and have verified that by printing the contents of the streams passing into and out of the parallel region. The incoming stream includes equal numbers of tuples with chNum values between 0 and 49 inclusive with all values represented. If I set parallelChannels to 22 tuples with output values of 20 and 21 are output. But when I set it to 20 then I get no tuples output that have chNum equal to 20 or 21. (Note that in this version of the filter values 4 and 5 are removed so the total number of values to be hashed is 20.)
stream<ChannelDataT> Channels = Filter(AllChannels) { param filter : has((list<uint32>)[0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], chNum) ; } @parallel(width =(int32) getSubmissionTimeValue("parallelChannels"), partitionBy = [ { port = Channels, attributes = [ chNum ] } ]) stream<PeriodDataT> PeriodData = ProcessChannels(Channels) { }
Answer by Michael.K (1380) | Jan 22, 2016 at 02:43 PM
Hello Jim.
Please find below my test application. I put a Beacon in front of your operators, added some FileSinks, and used a Functor inside ProcessChannels. Please let me know whether this application fits your scenario.
The Beacon produces 50 tuples with chNum value between 0 and 49.
If I set parallelChannels to 22. I get the following 20 tuples in the result.txt file:
{chNum=0,channel=0} {chNum=1,channel=20} {chNum=2,channel=6} {chNum=3,channel=3} {chNum=6,channel=18} {chNum=7,channel=15} {chNum=8,channel=21} {chNum=9,channel=9} {chNum=10,channel=12} {chNum=11,channel=10} {chNum=12,channel=16} {chNum=13,channel=13} {chNum=14,channel=4} {chNum=15,channel=1} {chNum=16,channel=7} {chNum=17,channel=5} {chNum=18,channel=11} {chNum=19,channel=8} {chNum=20,channel=19} {chNum=21,channel=2}
If I set parallelChannels to 20, I get the following 20 tuples in the result.txt file:
{chNum=0,channel=0} {chNum=1,channel=6} {chNum=2,channel=3} {chNum=3,channel=14} {chNum=6,channel=15} {chNum=7,channel=9} {chNum=8,channel=12} {chNum=9,channel=10} {chNum=10,channel=16} {chNum=11,channel=13} {chNum=12,channel=4} {chNum=13,channel=1} {chNum=14,channel=7} {chNum=15,channel=5} {chNum=16,channel=11} {chNum=17,channel=8} {chNum=18,channel=19} {chNum=19,channel=2} {chNum=20,channel=0} <-- as chNum=0 {chNum=21,channel=6} <-- as chNum=1
As I tried to explain in my first response, it might happen that a unique chNum value is passed to a channel that is also used for another unique chNum value. In this case, chNum 0 and 20 are handled in UDP channel 0, and chNum 1 and 21 are handled in UDP channel 6.
Please let me know whether this application is fitting to your scenario and whether it produces in your environment less than 20 tuples. Or, whether I am missing something ;) Thank you in advance.
The application:
namespace application; type ChannelDataT = tuple<uint32 chNum>; type PeriodDataT = tuple<uint32 chNum, uint32 channel>; composite ProcessChannels(input stream<ChannelDataT> I; output stream<PeriodDataT> O) { graph stream<PeriodDataT> O = Functor(I) { output O: channel = (uint32)getChannel(); } } composite Main { graph stream<ChannelDataT> AllChannels as O = Beacon() { param iterations: 50; period: 1.0; output O: chNum = (uint32)IterationCount(); } () as BeaconSink = FileSink(AllChannels) { param file: "beacon.txt"; format: txt; flush: 1u; } stream<ChannelDataT> Channels = Filter(AllChannels) { param filter : has((list<uint32>)[0, 1, 2, 3, /* 4, 5, */ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], chNum) ; } @parallel(width =(int32) getSubmissionTimeValue("parallelChannels"), partitionBy = [ { port = Channels, attributes = [ chNum ] } ]) stream<PeriodDataT> PeriodData = ProcessChannels(Channels) { } () as UDPSink = FileSink(PeriodData) { param file: "result.txt"; format: txt; flush: 1u; } }
Answer by Jim Sharpe (68) | Jan 22, 2016 at 03:58 PM
You example does match my scenario but not the behavior I observe. In my case if I set parallel channels to 20 it does not seem to "repurpose" the vacated paths to process the tuples with chNum = 20/21. Rather those tuples just don't appear at all on the output (unless I set width to 22 or greater).
I'll try your example as well as do some more testing with my application later this evening to see if I can pin down what might be different.
Answer by Jim Sharpe (68) | Jan 22, 2016 at 07:40 PM
Hi Michael,
I just tried running your example and although it does output all the tuples it doesn't behave in the way I expected. Specifically, channels 0 and one are each used to process tuples with two different chNum values while channels 4 and 5 do not process any tuples. (See attached.) Your example above appears to not use channels 17 and 18). Is that what you would expect? If so is there any way to force it to use all the channels before reusing any and/or prohibiting any channel to process tuples for more than one chNum? Doubling up on some channels while not using others at all is problematic for at least a couple of reasons.
Answer by Michael.K (1380) | Jan 26, 2016 at 05:01 AM
Hello Jim.
Today, the distribution algorithm calculates, as mentioned in the first answer, a hash code from your specified partitionBy attributes. The hash code algorithm is fixed and cannot be changed.
The distribution algorithm takes the calculated hash code, runs a modulo operation (hash code mod number of channels) to calculate an index, and sends the tuple to the output port with the resulting index. This is identical to the behavior of a Split operator.
For sure this means, if your partitionBy attributes have a small set of value combinations only, for example, 4 combinations, it does not make sense to have more than 4 channels because a maximum of 4 channels would be used only. If the hash code and modulo calculation produces the same results for different value combinations, the number might be smaller than 4.
On the other hand, if you have a huge set of value combinations and an application streaming data for weeks and months, the application will probably use all channels, at least in average.
And here the answers to your questions.
Q: Is that what you would expect?
The different channel numbers are possible because I used another Streams version, and there might be changes in the hash code or distribution algorithm. This is not known to me, but since you got all tuples, the result is not wrong.
Q: If so is there any way to force it to use all the channels before reusing any and/or prohibiting any channel to process tuples for more than one chNum?
No because the destination channel must be calculated from the partitionBy attributes. That means, you want to have a fast algorithm, and building a hash code is one of the fastest generic approaches. If you would do some equal load partitioning, you would need to store the values, which would be much slower.
Q: Doubling up on some channels while not using others at all is problematic for at least a couple of reasons.
As I mentioned before, if there are few value combinations only, it does not make sense to have more channels. But for a typical application, you will have a large set of value combinations and therefore, a nearly "equal load" distribution from a value perspective. I assume that seeing some channels being reused, is a test issue only ... too few test data. If you would try with a million different numbers, all channels will be used and each channel will handle a similar number of value combinations.
Regards, Michael.
Answer by Jim Sharpe (68) | Jan 26, 2016 at 07:46 AM
Hi Michael,
Thanks for he response, but it's rather disappointing news. In my current use case I'm doing a sequence of steps of time series processing in each of the parallel channels. As currently written, each of the channels expects, and can only process, a single signal. Mixing state from different signals in the same channel would produce an erroneous result. Simply using partitioned windows for some of the operators doesn't really help because that is not supported by all operators in the parallel region. The reason your example application isn't losing tuples but mine is, relates only to the nature of what happens inside the parallel region. Since I had [erroneously] assumed that each channel would be processing only a single signal, merging multiple signals together in a single channel results in corrupting both and losing one.
Given the relatively small number of channels I need (less than a few hundred) the workaround I've been using to ensure that each channel only processes a single signal is to set the width greater than or equal to the largest numerical partitioning attribute. In the case where all the numerical chNum's are contiguous that works great with each channel getting used for exactly one chNum. However, as illustrated in your test program, things fall apart if not all the partitioning attribute values are used. Additionally this hack of a workaround is wasteful of computational resources if the partitioning attribute values are sparse since many channels would be created but never used.
Prior to the arrival of the @parallel annotation we would probably have used a combination of mixed mode and custom operators with for implementing something like this. Is quite a loss of convenience not to be able to use the parallel operator UDP. I guess I'll have to dust off my perl and recode it the "old fashioned" way.
Please consider this a feature request for a future version Streams to allow an alternate split/hashing algorithm that would support the situation where the width of the parallel region exactly matches the number of partitioning values to provide a 1:1 mapping.
Answer by MikeSpicer (386) | Jan 26, 2016 at 06:18 PM
As Michael has described, the partitioning uses a hash so the behavior of data not being evenly spread over the number of available channels is possible but you should not see lost tuples. If you double check your test and are seeing lost tuples its a defect and we will fix it. We have a feature request to allow custom partitioning functions.
Another suggestion for a workaround would be to have an upstream operator assign each signal id to a contiguous channel number in the range of 0 to chNum -1. I realize that this is additional processing and does not remove the need for the feature request but it should allow you to get the behavior you need in the interim.
53 people are following this question.
control ports on a user defined parallel region 1 Answer
Why does the partitionAge in a partitioned, count based sliding window have no effect? 1 Answer
in Teda i use Ite Application and i have problem: 2 Answers
Scalability of replicated operator in parallel region. 3 Answers
@parallel split on rstring attribute 1 Answer
|
https://developer.ibm.com/answers/questions/249150/$%7Bauthor.url%7D/
|
CC-MAIN-2019-51
|
refinedweb
| 2,586
| 57.91
|
>
I'm trying to create a function which returns a gameobject with random scripts attached to it. What I'm trying to do is to get the scripts via prefabs and using AddComponent into them with this script.
using UnityEngine;
using System.Collections;
public class CreateRandom : MonoBehaviour {
public GameObject EnemyShell;
public ~~GameObject[]~~ MovementArray; //All these arrays shouldn't be of GameObject type. I made a mistake. It should be some way of getting different script names (Movement0,Movement1 etc.) into an array)
public ~~GameObject[]~~ PatternArray;
public ~~GameObject[]~~ BulletArray;
private GameObject NewEnemy;
GameObject CreateEnemy(){
NewEnemy = EnemyShell;
NewEnemy.AddComponent<MovementArray[Random.Range(int 0, MovementArray.Length-1)]>();
NewEnemy.AddComponent<PatternArray[Random.Range(int 0, PatternArray.Length-1)]>();
NewEnemy.AddComponent<BulletArray[Random.Range(int 0, BulletArray.Length-1)]>();
return NewEnemy;
}
}
However with this script, I'm getting the error "Invalid rank specifier: expected ',' or ']'" when I try to use the AddComponent method.
Answer by Graham-Dunnett
·
Jul 01, 2015 at 10:20 AM
GameObject.AddComponent is documented as adding a script to a GO. Your MovementArray is an array of GameObjects. You cannot add a GO as a component. I think you are suggesting that the GOs in the MovementArray all have different scripts applied. So, you'll need to use GetComponents to get a list of the components on the GO. So, something like (not compiled, might have bugs, but you get the idea):
GameObject.AddComponent
MovementArray
GameObject
GetComponents
GameObject movementGO = MovementArray[Random.Range(int 0, MovementArray.Length-1)];
A[] a = movementGO.GetComponents<A>();
B[] b = movementGO.GetComponents<B>();
C[] c = movementGO.GetComponents<C>();
if (a.length > 0)
NewEnemy.AddComponent<A>();
if (b.length > 0)
NewEnemy.AddComponent<B>();
if (c.length > 0)
NewEnemy.AddComponent<C>();
where your script components are called A, B and C. I suspect they have a more descriptive name (which will be the name of the class in your c# scripts.)
Oh wow I didn't realise I used GameObject[] for the array. I was actually intending to be able to drag a script into the editor like referencing a normal game object, rather than creating a prefab for each script.
The method you proposed sounds like a good alternative, though I don't quite understand the purpose of having multiple arrays. I kinda forgot to add context, but what I'm trying to do is to create a script that will attach a random script from each array onto the NewEnemy GameObject and return that.
From what I understand of your code, is it taking all the scripts in the GO and adding all of them to NewEnemy? Because I'm trying to just get one script from each.
Multiple Cars not working
1
Answer
Distribute terrain in zones
3
Answers
Unet Procedure Calls?
0
Answers
Script is moving player to the wrong position
2
Answers
Detect if build target is installed
1
Answer
|
https://answers.unity.com/questions/997637/getting-invalid-rank-specifier-when-adding-compone.html
|
CC-MAIN-2019-22
|
refinedweb
| 477
| 52.05
|
.
Lets build a class and begin to understand its parts. Our class will be called. Whenwe create one of ourobjects (just like creating a cookie), we will want to specifythe radius of each circle. We will want to have the ability to interrogate the variousobjects we might have created and ask for the area, circumference, or diameter.public class Circle{//This part is called the//particular circle.public Circle(double r){radius = r;}
//This is a. It performs some action (in this case it calculates the//area of the circle and returns it.public double area( ) //{double a = Math.PI * radius * radius;return a;}public double circumference( ) //{double c = 2 * Math.PI * radius;return c;}public double radius; //This is aalso called//andIt is available to code// in ALL the methods in this class.}Now, lets use our cookie cutter (theclass) to create two cookies (Place the following code in themethod of a different class ().
objects).
calledhaving a radius of 20.6. From this point on we dont refer towe refer toand.Lets suppose we wish to store the radius ofHeres the code to do this:
in a variable called
15-2. Instead
double xx = cir1.radius;Now lets ask for and printout the area of
System.out.println ( cir2.area( ) );We will now look at the(also called amethod and then examine each part.
) of this
15-3Lets create a new method in which the parenthesis isempty. Our newmethod will be called. The purpose of this is so that after the objecthas been created (at which time a radius is initially set), we can change ourmind and establish aradius for this particular circle. The new signature(and code) will be as follows:public void setRadius(double nr){radius = nr; //set the state variable radius to the new radius}//value, nrWe see two new things here:a.means we arereturning a value from this method. Noticethere is noin the code as with the other methods.b.
class.
15-4public Circle(double r){radius = r;}The entire purpose of the constructor is to set values for some of the state variables of anobject at the time of its creation (construction). In ourclass we set the value of thestate variable,, according to a double precision number that is passed to theconstructor as a parameter. The parameter is called within the constructor method;however, it could be given any legal variable name.The constructor is itself a method; albeit a very special one with slightly different rulesfrom ordinary methods.1.
is always specified.
3. This is actually a void method (since it doesnt return anything); however, thespecifier is omitted.4. The required parenthesis may or may not have parameters. Our example abovedoes. Following is another example of aconstructor withparameters. Aconstructor with no parameters is called the.public Circle( ){radius =100;}What this constructor does is to just blindly set the radii to 100 of allobjects that it creates.
method as.
|
https://de.scribd.com/doc/304639819/bpj-lesson-15
|
CC-MAIN-2019-47
|
refinedweb
| 487
| 58.28
|
A Django test runner based on unittest2's test discovery.
Project description
Note
This runner has been added to Django 1.6 as the default test runner. If you use Django 1.6 or above you don’t need this app.
An alternative Django TEST_RUNNER which uses the unittest2 test discovery from a base path specified in the settings, or any other module or package specified to the test management command – including app tests.
If you just run ./manage.py test, it’ll discover and run all tests underneath the current working directory. E.g. if you run ./manage.py test full.dotted.path.to.test_module, it’ll run the tests in that module (you can also pass multiple modules). If you give it a single dotted path to a package (like a Django app) like ./manage.py test myapp and that package does not itself directly contain any tests, it’ll do test discovery in all submodules of that package.
Note
This code uses the default unittest2 test discovery behavior, which only searches for tests in files named test*.py. To override this see the TEST_DISCOVER_PATTERN setting or use the --pattern option.
Why?
Django’s own test discovery is very much tied to the directory structure of Django apps, partly due to historic reasons (the unittest library didn’t have its own discovery for a long time) and prevents Django app authors from being good Python citizens. django-discover-runner uses the official test discovery feature of the new unittest2 library which is included in Django.
By default there is no way to put project specific tests in a separate folder outside the Python package of the Django project, which is a great way to organize your code, separating the tests and non-test code. django-discover-runner helps you clean up your project tests.
There is also no way to specify fully dotted import paths to test modules, functions, class or methods to the test management command but only Django’s odd standard <appname>.<TestClassName>. django-discover-runner allows you to specify any type of label to Django’s test management command.
By default Django’s test runner will execute the tests of Django’s own contrib apps, which doesn’t make sense if you just want to run your own app’s or project’s tests. django-discover-runner fixes this by allowing you to specify which tests to run and organize your test code outside the reach of the Django test runner.
More reasons can be found in Carl Meyer’s excellent talk about Testing and Django (slides).
Installation
Install it with your favorite installer, e.g.:
pip install -U django-discover-runner
django-discover-runner requires at least Django 1.4 and also works on 1.5.x. Starting in Django 1.6 the discover runner is a built-in.
Setup
TEST_RUNNER (required) needs to point to the DiscoverRunner class to enable it:
TEST_RUNNER = 'discover_runner.DiscoverRunner'
Add 'discover_runner' to your INSTALLED_APPS setting to enable the ability to override the discovery settings below when using the test management command.
TEST_DISCOVER_TOP_LEVEL (optional) should be the directory containing your top-level package(s); in other words, the directory that should be on sys.path for your code to import. This is for example the directory containing manage.py in the new Django 1.4 project layout. The management command option is called --top-level.
TEST_DISCOVER_PATTERN (optional) is the pattern to use when discovering tests and defaults to the unittest2 standard test*.py. The management command option is called --pattern.
Examples
Django app
To test a reusable Django app it’s recommended to add a test_settings.py file to your app package to easily run the app tests with the test management command. Simply set the TEST_RUNNER setting to 'discover_runner.DiscoverRunner', configure the other settings necessary to run your tests and call the test management command with the name of the app package, e.g.:
django-admin.py test --settings=myapp.test_settings myapp
Django project
If you want to test a project and want to store the project’s tests outside the project main package (recommended), you can simply follow the app instructions above, applying it to the “project” package, but set a few additional settings to tell the test runner to find the tests:
from os import path TEST_DISCOVER_TOP_LEVEL = path.dirname(path.dirname(__file__))
This would find all the tests within a top-level “tests” package. Running the tests is as easy as calling:
django-admin.py test --settings=mysite.test_settings tests
Alternatively you can specify the --top-level-directory management command option.
Multiple Django versions
In case you want to test your app on older Django versions as well as Django >= 1.6 you can simply conditionally configure the test runner in your test settings, e.g.:
import django if django.VERSION[:2] < (1, 6): TEST_RUNNER = 'discover_runner.DiscoverRunner'
Changelog
1.0 06/15/2013
- GOOD NEWS! This runner was added to Django 1.6 as the new default! This version backports that runner for Django 1.4.x and 1.5.x.
- Removed TEST_DISCOVER_ROOT setting in favor of unittest2’s own way to figure out the root.
- Dropped support for Django 1.3.x.
0.4 04/12/2013
- Added ability to override the discover settings with a custom test management command.
0.3 01/28/2013
- Fixed setup.py to work on Python 3. This should make this app compatible to Python 3.
0.2.2 09/04/2012
- Stopped setting the top level variable in the case of using a module path as the test label as it made the wrong assumption that the parent directory is the top level.
0.2.1 08/20/2012
- Fixed a rather esoteric bug with testing test case class methods that was caused by a wrong import and the way Django wraps itself around the unittest2 module (if availale) or unittest on Python >= 2.7.
0.2 05/26/2012
- Added ability to use an optionally installed unittest2 library for Django projects using Django < 1.3 (which added unittest2 to the django.utils.unittest package).
0.1.1 05/23/2012
- Fixed a bug that prevented the project based feature to work correctly.
0.1 05/20/2012
- Initial release with support for Django >= 1.3.
Thanks
This test runner is a humble rip-off of Carl Meyer’s DiscoveryRunner which he published as a gist a while ago. All praise should be directed at him. Thanks, Carl!
This was also very much related to ticket #17365 which eventually led to the replacement of the default test runner in Django. Thanks again, Carl!
Project details
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/django-discover-runner/1.0/
|
CC-MAIN-2018-22
|
refinedweb
| 1,128
| 66.64
|
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
hello there i have this sketch that tells me if they are faces on the screen and depending on how close or far you are to the cam then the rectangle would change its size, my question is how can i tell if the box is getting bigger or smaller WITHOUT ME actually being able to look at the screen?
what i really want to do is write to the port a string that on the other side i can have a midi sd card read wav/midi files pertaining to the size of the rectangle
import gab.opencv.*; import processing.video.*; import java.awt.*; import processing.serial.*; Capture video; OpenCV opencv; Serial port; void setup() { size(640, 480); port = new Serial(this, Serial.list()[0], 19200); video = new Capture(this, 640/2, 480/2, "360HD Hologen"); opencv = new OpenCV(this, 640/2, 480/2); opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE); video.start(); } void draw() { scale(2); opencv.loadImage(video); image(video, 0, 0 ); noFill(); stroke(0, 255, 0); strokeWeight(1); Rectangle[] faces = opencv.detect(); println(faces.length); for (int i = 0; i < faces.length; i++) { rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height); } } void captureEvent(Capture c) { c.read(); }
Answers
@erkosone hmmmm thanks for that though i guess what im looking for is a way to account for the Z axis and so i thought that if i use my original logic that will suffice for z
-Graciaz
@erkosone how do we find the
height and widthof this function?
i think i tried just about every combination known in this formula to try to merge just like we did with faces but nothing is giving me or letting me combine other variables to make up the
height and width
i would like to accomplished the same thing we done with faces
this is what i last just tried so ill share with you guy although it did not work for me "just to show that i really am trying to learn and explore"
|
https://forum.processing.org/two/discussion/16012/looking-for-a-way-to-read-if-a-box-rectangle-is-small-or-big-on-the-screen
|
CC-MAIN-2019-47
|
refinedweb
| 357
| 63.63
|
Opened 7 years ago
Closed 6 years ago
Last modified 6 years ago
#5142 closed Bugs (invalid)
type_erased feels unnecessary.
Description
type_erased Range Adaptor is in release brunch of Boost 1.46.0, but I feel that this is unnecessary. It is enough if there is any_range:
#include <iostream> #include <vector> #include <boost/assign/list_of.hpp> #include <boost/range/any_range.hpp> #include <boost/range/algorithm/for_each.hpp> #include <boost/range/adaptor/filtered.hpp> typedef boost::any_range< int , boost::forward_traversal_tag , int , std::ptrdiff_t > integer_range; void disp(int x) { std::cout << x << std::endl; } void disp_all(integer_range r) { boost::for_each(r, disp); } bool is_even(int x) { return x % 2 == 0; } int main() { const std::vector<int> v = boost::assign::list_of(1)(2)(3)(4)(5); disp_all(v | boost::adaptors::filtered(is_even)); }
Even if there is few it, I feel that I am premature to include it in 1.46.0 official release.
Attachments (0)
Change History (3)
comment:1 Changed 7 years ago by
comment:2 Changed 6 years ago by
I didn't feel it was too early to put this into the release branch. The core of the interface design is built upon experience gained with other any_iterator implementations. The implementation of any_interface has been tested in production environments successfully. The inclusion of the type_erased definitely has application particularly when chaining adaptors that are passing results to templatised range algorithms that are not specialised for any_range.
At this point experience shows that the feature is popular and working.
comment:3 Changed 6 years ago by
The core of the interface design is built upon experience gained with other any_iterator implementations.
I cannot find the experience. Where can it be seen? At least, with the sample on a document, I do not think that it is useful.
<del>Even if there is few it, I feel that I am premature to include it in 1.46.0 official release.</del> At least, I feel that it is too early to include type_erased into 1.46.
|
https://svn.boost.org/trac10/ticket/5142
|
CC-MAIN-2017-47
|
refinedweb
| 334
| 57.77
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.