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 |
|---|---|---|---|---|---|
Cheat Sheet
NooBaa Cheat Sheet
NooBaa is a free and open source data management platform for Kubernetes and Red Hat OpenShift platforms. NooBaa is designed to provide agnostic data management on-prem and in the cloud. It enables easy data portability and tiering seamlessly to the application.
This cheat sheet will walk you through the basics, installation, deployment, monitoring and maintenance, and troubleshooting.
Cheat Sheet Excerpt“
Log in to your Kubernetes or OpenShift. Run deployment with the following command. By default, it will deploy NooBaa’s operator and pod under the
noobaa namespace. Use
-n for another namespace
noobaa install -n noobaa
The deployment will deploy everything and print to the screen all the information that is needed to start using NooBaa. You can skip to S3 information, connect your application, and start working
Want to see more? Get the full cheat sheet.Download | https://developers.redhat.com/cheat-sheets/noobaa-cheat-sheet | CC-MAIN-2021-39 | refinedweb | 144 | 57.16 |
Overriding the OnPaint Method
The basic steps for overriding any event defined in the .NET Framework are identical and are summarized in the following list.
To override an inherited event
Override the protected OnEventName method.
Call the OnEventName method of the base class from the overridden OnEventName method, so that registered delegates receive the event.
The Paint event is discussed in detail here because every Windows Forms control must override the Paint event that it inherits from Control. The base Control class does not know how a derived control needs to be drawn and does not provide any painting logic in the OnPaint method. The OnPaint method of Control simply dispatches the Paint event to registered event receivers.
If you worked through the sample in How to: Develop a Simple Windows Forms Control, you have seen an example of overriding the OnPaint method. The following code fragment is taken from that sample.
public class FirstControl : Control{ public FirstControl() {} protected override void OnPaint(PaintEventArgs e) { // Call the OnPaint method of the base class. base.OnPaint(e); // Call methods of the System.Drawing.Graphics object. e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle); } }
The PaintEventArgs class contains data for the Paint event. It has two properties, as shown in the following code.
ClipRectangle is the rectangle to be painted, and the Graphics property refers to a Graphics object. The classes in the System.Drawing namespace are managed classes that provide access to the functionality of GDI+, the new Windows graphics library. The Graphics object has methods to draw points, strings, lines, arcs, ellipses, and many other shapes.
A control invokes its OnPaint method whenever it needs to change its visual display. This method in turn raises the Paint event. | https://msdn.microsoft.com/en-us/library/cksxshce(v=vs.80).aspx | CC-MAIN-2015-35 | refinedweb | 288 | 56.66 |
This section describes the modules that are provided by Boost.Build. The import rule allows rules from one module to be used in another module or Jamfile.
The
modules module defines basic functionality
for handling modules.
A module defines a number of rules that can be used in other modules. Modules can contain code at the top level to initialize the module. This code is executed the first time the module is loaded.
A Jamfile is a special kind of module which is managed by the build system. Although they cannot be loaded directly by users, the other features of modules are still useful for Jamfiles..
$(__file__) does not contain
the full path to the file. If you need this, use
modules.binding.).
rules called this way may accept at most 8 parameters. will be
available without qualification in the caller's module. Any
members of
rename-opt will be taken as the names
of the rules in the caller's module, in place of the names they
have in the imported module. If
rules-opt = '*',
all rules from the indicated module are imported into the
caller's module. If
rename-opt is supplied, it must have the
same number of elements as
rules-opt.
The
import rule is available
without qualification in all modules.).
Performs various path manipulations. Paths are always in a 'normalized' representation. In it, a path may be either:
'.', or
['/'] [ ( '..' '/' )* (token '/')* token ]
In plain english, a path can be rooted,
'..'
elements are allowed only at the beginning, and it never
ends in slash, except for the path consisting of slash only.
rule make ( native )
Converts the native path into normalized form.
rule native ( path )
Builds the native representation of the path.
rule is-rooted ( path )
Tests if a path is rooted.
rule has-parent ( path )
Tests if a path has a parent.
rule basename ( path )
Returns the path without any directory components.
rule parent ( path )
Returns the parent directory of the path. If no parent exists, an error is issued.
rule reverse ( path )
Returns
path2 such that
[ join path path2 ] = ".".
The path may not contain
".."
element or be rooted.
rule join ( elements + )
Concatenates the passed path elements. Generates an error if any element other than the first one is rooted. Skips any empty or undefined path elements.
rule root ( path root )
If
path is relative, it is rooted at
root. Otherwise, it is unchanged.
rule pwd ( ).
rule exists ( file )
Returns true if the specified file exists.
rule all-parents ( path : upper_limit ? : cwd ? )
Find out the absolute name of path and return the list of all the parents,
starting with the immediate one. Parents are returned as relative names. If
upper_limit is specified, directories above it
will be pruned.
rule glob-in-parents ( dir : patterns + : upper-limit ? )
patterns in parent directories
of
dir, up to and including
upper_limit, if it is specified, or
till the filesystem root otherwise.
rule relative ( child parent : no-error ? )
Assuming
child is a subdirectory of
parent, return the relative path from
parent to
child.
rule relative-to ( path1 path2 )
Returns the minimal path to path2 that is relative path1.
rule programs-path ( )
Returns the list of paths which are used by the operating system for looking up programs.
rule makedirs ( path )
Creates a directory and all parent directories that do not already exist. the string.
"$" matches the end of the string.
"\<" matches the beginning of a word.
"\>" matches the end of a word.
rule split ( string separator )
Returns a list of the following substrings:
from beginning till the first occurrence of
separator or till the end,
between each occurrence of
separator and the next occurrence,
from the last occurrence of
separator till the end.
If no separator is present, the result will contain only one element.
rule split-list ( list * : separator )
Returns the concatenated results of applying regex.split to every element of the list using the separator pattern.
rule match ( pattern : string : indices * )
Match
string against
pattern, and return the elements
indicated by
indices.
rule transform ( list * : pattern : indices * )
Matches all elements of
list against
the
pattern and returns a list of elements
indicated by
indices of all successful
matches. If
indices is omitted returns a list
of first parenthesized groups of all successful matches.
rule escape ( string : symbols : escape-symbol )
Escapes all of the characters in
symbols
using the escape symbol
escape-symbol for of
$(sequence) for which
[ $(predicate) e ] has a non-null value.
rule transform ( function + : sequence * )
Return a new sequence consisting of
[ $(function) $(e) ] for each element
e of
$(sequence).
rule reverse ( s * )
Returns the elements of
s in
reverse order.
rule insertion-sort ( s * : ordered * )
Insertion-sort
s using the
BinaryPredicate
ordered.
rule merge ( s1 * : s2 * : ordered * )
Merge two ordered sequences using the BinaryPredicate
ordered.
rule join ( s * : joint ? )
Join the elements of
s into one
long string. If
joint is supplied, it
is used as a separator.
rule length ( s * )
Find the length of any sequence.
rule unique ( list * : stable ? )
Removes duplicates from
list.
If
stable is passed, then the order
of the elements will be unchanged.
rule max-element ( elements + : ordered ? )
Returns the maximum number in
elements.
Uses
ordered for comparisons or
numbers.less
if none is provided.
rule select-highest-ranked ( elements * : ranks * )
Returns all of
elements for which
the corresponding element in the parallel list
rank is equal to the maximum value in
rank.
be recognized as targets of type
type.
Issues an error if a different type is already specified for any
of the suffixes.
rule registered ( type )
Returns true iff type has been registered.
rule validate ( type )
Issues an error if
type is unknown.
rule set-scanner ( type : scanner )
Sets a scanner class that will be used for this type.
rule get-scanner ( type : property-set )
Returns a scanner instance appropriate to
type
and
property-set.
rule base ( type )
Returns a base type for the given type or nothing in case the given type is not derived.
rule all-bases ( type )
Returns the given type and all of its base types in order of their distance from type.
rule all-derived ( type )
Returns the given type and all of its derived types in order of their distance from type.
rule is-derived ( type base )
Returns true if
type is equal to
base or has
base
as its direct or indirect base.
rule set-generated-target-suffix ( type : properties * : suffix )
Sets a file suffix to be used when generating a target of
type with the
specified properties. Can be called with no properties if no suffix has
already been specified for the
type. The
suffix parameter can be an empty
string (
"") to indicate that no suffix should be used.
Note that this does not cause files with
suffix
to
type with the given properties.
rule set-generated-target-prefix ( type : properties * : prefix )
Sets a target prefix that should be used when generating targets of
type with the specified properties. Can
be called with empty properties if no prefix for
type has been specified yet.
The
prefix parameter can be empty string
(
"") to indicate that no prefix
should be used.
type with the given properties.
rule type ( filename )
Returns file type given its name. If there are several dots in filename, tries each suffix. E.g. for name of "file.so.1.2" suffixes "2", "1", and "so" will be tried. | http://www.boost.org/build/doc/html/bbv2/reference/modules.html | CC-MAIN-2015-22 | refinedweb | 1,219 | 67.65 |
tag:blogger.com,1999:blog-8712770457197348465.post5659396501065294711..comments2016-06-24T12:30:19.354-07:00Comments on Javarevisited: Why main method is public static in JavaJavin Paul JVM understands execution completed of void me...How JVM understands execution completed of void methods , since void doesn't return anything ??hackermanid, this is interesting question beause ma.... Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-30941593283378232602015-06-14T21:54:07.118-07:002015-06-14T21:54:07.118-07:00why main has to be void?why main has to be void?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-45775590405209376392014-07-16T10:10:23.095-07:002014-07-16T10:10:23.095-07:00If public modifier is removed (made default or mad...If public modifier is removed (made default or made private)then JVM reports following: -<br />Main method not public.<br /><br />If arguments are modified like (String[]args, int i)...to test overloading....then it reports following: -<br />Exception in thread "main" java.lang.NoSuchMethodError: main<br /><br />This leads to a conclusion that this is a STANDARD FORMAT, JVM looks for, Omkar sir you tesch us that main method must be pu...hello sir you tesch us that main method must be public because public method can access easily outside the class i agree with you but non specifire methods are also like a public but this code is not run<br />static void main(String s[]) why it is also accessable outside the classMoaz Amin is how you can invoke NON-STATIC method from ...This is how you can invoke NON-STATIC method from main<br /><br />public class TestMain {<br /><br /> public static void main(String[] args) {<br /> TestMain test = new TestMain();<br /> test.invokeMethodFromMain();<br /> }<br /> <br /> private void invokeMethodFromMain(){<br /> System.out.println("inovked NON-STATIC method from main method");<br /> }<br />}<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-84099165704121156392013-08-26T02:57:41.987-07:002013-08-26T02:57:41.987-07:00similarly i want that my functions in one class ca...similarly i want that my functions in one class can be called by any other class that i define, without creating object of class whose function i want to be called how do i accomplish this<br />keep in mind no friend function is allowed<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-43069582463686175582013-08-26T02:53:28.340-07:002013-08-26T02:53:28.340-07:00for exmaple my main fuction is not static how can ...for exmaple my main fuction is not static how can i call main function i.e can i call main function after creating an object of class in which it is defined and calling it keeping in view that main function is not defined "Static" Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-38540671084781776932013-08-21T01:32:56.937-07:002013-08-21T01:32:56.937-07:00does any one knows how to call a non static method...does any one knows how to call a non static method from main method in Java? I am getting "cannot make a static reference to the non-static method" error while calling a non static method, declared in same class. please helpAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-10979603872900733762013-08-13T09:16:51.100-07:002013-08-13T09:16:51.100-07:00This is really helpful for a beginner. Thanks This is really helpful for a beginner. Thanks Docket Smart other static methods are executed after main()...why other static methods are executed after main() method is executed even when main() method is also static?Sasmita Nayak you please tell why it si mandatory to pass St...can you please tell why it si mandatory to pass String args[] as a argument to main ()?neha shirlekar is my list of frequently asked question on ma...Here is my list of frequently asked question on main in Java<br />1. Can we overload main method in Java?<br />2. Can we make main method final in Java ?<br />3. can we override main in Java ?<br />4. How to call a non static method from main in Java ?<br />5. can we make main method synchronized ?<br /><br />These are good questions for any beginner to know more about Main method in Java.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-66424119707755891702012-08-14T06:00:38.086-07:002012-08-14T06:00:38.086-07:00In order to access the Class must be public. All J...In order to access the Class must be public. All JVM are written using JVM specification and I have never heard of any JVM changing signature of Main method, if you have better reason than please share.Javin Paul does not find for the Main Method its the JNI....JVM does not find for the Main Method its the JNI. Secondly your logic that why main is public has no reason. Since the class is never instantiated it doesn't matter is its public or not.<br /><br />Main method is entry point for any Core Java program, "Any"...no<br /><br />should be "public, static and void in Java", no you can write your own JVM and instead have some Aster are few more questions like why main is stati...here are few more questions like why main is static:<br /><br />Why run method in Java doesn't return any thing ?<br />Why start method is used to start thread instead of run ?<br /><br />By the way you can run Java class even without main method, just put your code inside static initializer block and it will be run when class will be loaded.Peternoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-75044641507642422172012-03-27T20:51:13.646-07:002012-03-27T20:51:13.646-07:00Can main method throw Exception in Java? indeed ma...Can main method throw Exception in Java?<br />indeed main method can throw Exception both checked and unchecked.<br /><br />Can main method be overloaded in java?<br />Yes main method in java can be overloaded but JVM will only invoke main method with standard signature.<br /><br />Can main method be overridden in java?<br />Yes main method in java can be overridden and the class you passed to Dimistrinoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-63599990908870320862012-03-27T01:28:47.054-07:002012-03-27T01:28:47.054-07:00Can we throw exception from main method in Java ? ...Can we throw exception from main method in Java ? I am asking both checked and unchecked Exception. Also when do we get error "no main class found your program will terminate"Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-85295390642857727582012-02-15T07:00:04.565-08:002012-02-15T07:00:04.565-08:00Can we declare main method private? this was the q...Can we declare main method private? this was the question asked to me. What will happen if we make main method private in Java, i said we can not access it from outside of Class since its private and also can not run Java program, was that correct answer ?Radhikanoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-6947096798648477362012-01-17T21:28:31.905-08:002012-01-17T21:28:31.905-08:00Java Main method can also throw any Exception or E...Java Main method can also throw any Exception or Error in its throws clause, following main method in java is perfectly legal:<br />public static void main(String args[]) throws AssertionErrorAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-47751684856116430062012-01-14T06:47:39.451-08:002012-01-14T06:47:39.451-08:00even though main method should not return values,i...even though main method should not return values,it can use empty return statement.<br />ex return; allowed<br />but return somevalue; not allowediTfinGer Ode you know how to pass arguments to main method i...do you know how to pass arguments to main method in Java and how to get those arguments inside java program ?Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-8712770457197348465.post-36113967542054088622011-12-30T07:16:48.887-08:002011-12-30T07:16:48.887-08:00Nice explanation of 'public static void main(S...Nice explanation of 'public static void main(Strin args[])'. here is my post on the same '<a href="" rel="nofollow">public static void main(String args[]): Explained</a><br /><br />here is point too on main:<br /><br />The main method can be overloaded.farhan khwaja We have servlet & other as managed jav...@Neeraj<br / Ashutosh Agarwal are valid main method signature: public...Following are valid main method signature:<br /><br />public static void main(String[] argument)<br />public static void main(String argument[])<br />public static void main(String... args)<br />public static synchronized void main(String... args)<br />public static strictfp void main(String... args)<br />public static final void main(String... args)Anonymousnoreply@blogger.com | http://javarevisited.blogspot.com/feeds/5659396501065294711/comments/default | CC-MAIN-2016-26 | refinedweb | 1,502 | 57.67 |
You can subscribe to this list here.
Showing
6
results of 6
On 09/25/2012 03:40 AM, anonymous coward wrote:
>
> However, support for parentheses around an
> operand (as suggested by #327364-001 3.5)
> is tricky: for reg ops the parentheses simply
> evaluate, but for mem ops the parser has to
> explicitly skip them -- however, that decision
> hinges on the leading transform modifier and
> there is no clear reg versus mem distinction,
> because of the D(...) down converts: they do
> use reg ops, but with mem transforms.
>
> I have not decided the most suitable course
> yet -- add extra parse-ahead to find '[', parse
> down convert instructions specially, or, well,
> ignore Intel's suggested syntax (i.e. no (...),
> and permit all modifiers before and after any
> operand, reg or mem [with subsequent tests
> for their sanity/validity, of course]).
>
Hi...
Cyrill and I looked at this last night, and we're not entirely sure what
you mean. Our thinking has been to treat braced keywords simply as a
separate keyword space, which would mean a slightly looser syntax but
probably okay. I seriously did not follow the big about parens, though...
-hpa
--
H. Peter Anvin, Intel Open Source Technology Center
I work for Intel. I don't speak on their behalf.
> Third, covering all the cases and making them work with the matching
> engine could take a fair bit of time.
I think this is the biggest issue. I actually suggested something like
this to Jules way back in 1998 or so. (Though my suggestion was to
introduce just one new prefix keyword, e.g. "alt", that would cause
nasm to use the less-common variant encoding for the following
instruction. Of course that falls apart for cases that have three
possible encodings.) He was vaguely sympathetic to the idea, but I
think he felt (rightly) that it was a fair bit of work for the amount
of payoff (particularly if future upkeep is taken into account).
b
On 11/20/2012 07:37 AM, Marat Dukhan wrote:
>
>?
>
Well, there are a few problems:
First, NASM is largely a volunteer project, so getting the resources to
do it is always a problem.
Second, and this may be the bigger issue, is that it causes namespace
issues; someone may be using e.g. "rex" as a variable. However, the
Xeon Phi assembler syntax already are addressing this by adding new
keywords recognized only if they are inside curly braces, so perhaps we
could just make that a general keyword space and make the syntax {rex}
and so on.
Third, covering all the cases and making them work with the matching
engine could take a fair bit of time.
If you are interested in this as a project, it is certainly something
that would be welcome.
-hpa
--
H. Peter Anvin, Intel Open Source Technology Center
I work for Intel. I don't speak on their behalf.
Dear NASM developers,
I work on a high-performance library of optimized functions, and use NASM
to assemble the x86/x86-64 specific implementations.
For high-performance code on some x86 microachitectures (e.g. Intel Atom,
Intel Nehalem, AMD Bulldozer) it is essential to align
groups of instructions on certain boundaries (8 or 16 bytes) to achieve
full CPU front-end performance.
There are three ways to align instruction groups on a 8- or 16-byte
boundary: insert NOPs, make instructions longer by adding
prefixes, or make instructions longer by using longer instruction forms.
1. Since NOPs consume decoder resources, they do not help to improve
decoder performance.
2. Adding instruction prefixes helps to certain degree, but CPU decoders
are limited in the number of instruction prefixes they
can decode per cycle, so this technique has limited use.
3. Using different (longer) encoding forms is the optimal solution, but it
requires support from the assembler.
NASM already supports some specifications of instruction forms, e.g.
MOV ecx, [esi] ; encoded without memory displacement
MOV ecx, [byte esi] ; encoded with 8-bit memory displacement
MOV ecx, [dword esi] ; encoded with 32-bit memory displacement
AND ecx, 0F ; encoded with 8-bit immediate
AND ecx, dword 0F ; encoded with 32-bit immediate
MOV ecx, [eax * 2] ; encoded as [eax + eax*1] without offset
MOV ecx, [nosplit eax * 2] ; encoded as [eax*2] with offset
I would like this functionality in NASM to be extended to more instruction
forms,
and suggest new keywords acc, modrm, sib, rex, vex3:
acc keyword forces NASM to use special rax/eax/ax/al encoding form.
Example for acc keyword:
ADD eax, 32 ; encoded as ModR/M + imm8
acc ADD eax, 32 ; encoded as special eax form + imm32
modrm keyword forces NASM to use ModR/M encoding
Example for modrm keyword:
ADD al, 32 ; encoded as special eax form + imm8
modrm ADD al, 32 ; encoded as ModR/M form + imm8 (1 byte londer than the
above version)
PUSH ecx ; encoded as 50+rd
modrm PUSH ecx ; encoded as FF /6
sib keyword forces NASM to use SIB byte even if ModR/M would be enough
Example for sib keyword:
MOV ecx, [esi + 4] ; encoded as ModR/M + imm8
MOV ecx, [sib esi + 4] ; encoded as ModR/M + sib + imm8?
Kind regards,
Marat Dukhan
On Tue, Nov 13, 2012 at 07:58:29PM -0800, H. Peter Anvin wrote:
>.
Sure. But this would require more code. I'll take a look
once time permits, at moment fast fix should be enough..
-hpa
--
H. Peter Anvin, Intel Open Source Technology Center
I work for Intel. I don't speak on their behalf. | http://sourceforge.net/p/nasm/mailman/nasm-devel/?viewmonth=201211 | CC-MAIN-2014-23 | refinedweb | 925 | 59.23 |
.13 Series¶
Release 0.13¶
IPython 0.13 contains several major new features, as well as a large amount of bug and regression fixes. The previous version (0.12) was released on December 19 2011, and in this development cycle we had:
- ~6 months of work.
- 373 pull requests merged.
- 742 issues closed (non-pull requests).
- contributions from 62 authors.
- 1760 commits.
- a diff of 114226 lines.
The amount of work included in this release is so large, that we can only cover here the main highlights; please see our detailed release statistics for links to every issue and pull request closed on GitHub as well as a full list of individual contributors.
Major Notebook improvements: new user interface and more¶:
:
):
Cluster management¶
The notebook dashboard can now also start and stop clusters, thanks to a new tab in the dashboard user interface:
.
New notebook format¶.
JavaScript refactoring¶
examples/widgets that lets you directly communicate with one or more
parallel engines, acting as a mini-console for parallel debugging and
introspection.
Improved tooltips¶.
Other improvements to the Notebook¶
These are some other notable small improvements to the notebook, in addition to many bug fixes and minor changes to add polish and robustness throughout:
- The notebook pager (the area at the bottom) is now resizeable by dragging its divider handle, a feature that had been requested many times by just about anyone who had used the notebook system. PR #1705.
- It is now possible to open notebooks directly from the command line; for example:
ipython notebook path/will automatically set
path/as the notebook directory, and
ipython notebook path/foo.ipynbwill further start with the
foo.ipynbnotebook opened. PR #1686.
- If a notebook directory is specified with
--notebook-dir(or with the corresponding configuration flag
NotebookManager.notebook_dir), all kernels start in this directory.
- Fix codemirror clearing of cells with
Ctrl-Z; PR #1965.
- Text (markdown) cells now line wrap correctly in the notebook, making them much easier to edit PR #1330.
- PNG and JPEG figures returned from plots can be interactively resized in the notebook, by dragging them from their lower left corner. PR #1832.
- Clear
In []prompt numbers on “Clear All Output”. For more version-control-friendly
.ipynbfiles, we now strip all prompt numbers when doing a “Clear all output”. This reduces the amount of noise in commit-to-commit diffs that would otherwise show the (highly variable) prompt number changes. PR #1621.
- The notebook server now requires two consecutive
Ctrl-Cwithin 5 seconds (or an interactive confirmation) to terminate operation. This makes it less likely that you will accidentally kill a long-running server by typing
Ctrl-Cin the wrong terminal. PR #1609.
- Using
Ctrl-S(or
Cmd-Son a Mac) actually saves the notebook rather than providing the fairly useless browser html save dialog. PR #1334.
- Allow accessing local files from the notebook (in urls), by serving any local file as the url
files/<relativepath>. This makes it possible to, for example, embed local images in a notebook. PR #1211.
Cell magics¶:
%%!: run cell body with the underlying OS shell; this is similar to prefixing every line in the cell with
!.
%%bash: run cell body under bash.
%%capture: capture the output of the code in the cell (and stderr as well). Useful to run codes that produce too much output that you don’t even want scrolled.
%%file: save cell body as a file.
%%perl: run cell body using Perl.
%%prun: run cell body with profiler (cell extension of
%prun).
%%python3: run cell body using Python 3.
%%ruby: run cell body using Ruby.
%%script: run cell body with the script specified in the first line.
%%sh: run cell body using sh.
%%sx: run cell with system shell and capture process output (cell extension of
%sx).
%%system: run cell with system shell (
%%!is an alias to this).
%%timeit: time the execution of the cell (extension of
%timeit).:
- Cython magics (extension
cythonmagic)
- This extension provides magics to automatically build and compile Python extension modules using the Cython language. You must install Cython separately, as well as a C compiler, for this to work. The examples directory in the source distribution ships with a full notebook demonstrating these capabilities:
- Octave magics (extension
octavemagic)
- This extension provides several magics that support calling code written in the Octave language for numerical computing. You can execute single-lines or whole blocks of Octave code, capture both output and figures inline (just like matplotlib plots), and have variables automatically converted between the two languages. To use this extension, you must have Octave installed as well as the oct2py package. The examples directory in the source distribution ships with a full notebook demonstrating these capabilities:
- R magics (extension
rmagic)
- This extension provides several magics that support calling code written in the R language for statistical data analysis. You can execute single-lines or whole blocks of R code, capture both output and figures inline (just like matplotlib plots), and have variables automatically converted between the two languages. To use this extension, you must have R installed as well as the rpy2 package that bridges Python and R. The examples directory in the source distribution ships with a full notebook demonstrating these capabilities:
Tab completer improvements¶).
.
Improvements to the Qt console¶
The Qt console continues to receive improvements and refinements, despite the fact that it is by now a fairly mature and robust component. Lots of small polish has gone into it, here are a few highlights:
- A number of changes were made to the underlying code for easier integration into other projects such as Spyder (PR #2007, PR #2024).
- Improved menus with a new Magic menu that is organized by magic groups (this was made possible by the reorganization of the magic system internals). PR #1782.
- Allow for restarting kernels without clearing the qtconsole, while leaving a visible indication that the kernel has restarted. PR #1681.
- Allow the native display of jpeg images in the qtconsole. PR #1643.
Parallel¶:
The parallel tools now default to using
NoDB as the storage backend for
intermediate results. This means that the default usage case will have a
significantly reduced memory footprint, though certain advanced features are
not available with this backend.:
- add to_send/fetch steps for moving connection files around.
- add SSHProxyEngineSetLauncher, for invoking to
ipcluster engineson a remote host. This can be used to start a set of engines via PBS/SGE/MPI remotely..
Kernel/Engine unification¶mag.
Official Public API¶
We have begun organizing our API for easier public use, with an eye towards an
official IPython 1.0 release which will firmly maintain this API compatible for
its entire lifecycle. There is now an
IPython.display module that
aggregates all display routines, and the
traitlets.config namespace has
all public configuration tools. We will continue improving our public API
layout so that users only need to import names one level deeper than the main
IPython package to access all public namespaces.
IPython notebook file icons¶.
New top-level
locate command¶.
Other new features and improvements¶
- %install_ext: A new magic function to install an IPython extension from a URL. E.g.
%install_ext.
- The
%loadpymagic is no longer restricted to Python files, and has been renamed
%load. The old name remains as an alias.
- New command line arguments will help external programs find IPython folders:
ipython locatefinds the user’s IPython directory, and
ipython locate profile foofinds the folder for the ‘foo’ profile (if it exists).
- The
IPYTHON_DIRenvironment variable, introduced in the Great Reorganization of 0.11 and existing only in versions 0.11-0.13, has been deprecated. As described in PR #1167, the complexity and confusion of migrating to this variable is not worth the aesthetic improvement. Please use the historical
IPYTHONDIRenvironment variable instead.
- The default value of interactivity passed from
run_cell()to
run_ast_nodes()is now configurable.
- New
%alias_magicfunction to conveniently create aliases of existing magics, if you prefer to have shorter names for personal use.
- We ship unminified versions of the JavaScript libraries we use, to better comply with Debian’s packaging policies.
- Simplify the information presented by
obj?/obj??to eliminate a few redundant fields when possible. PR #2038.
- Improved continuous integration for IPython. We now have automated test runs on Shining Panda and Travis-CI, as well as Tox support.
- The vim-ipython functionality (externally developed) has been updated to the latest version.
The
%savemagic now has a
-fflagimprovements, which allow things like progress bars and other simple animations to work well in the notebook (PR #1563):
clear_output()clears the line, even in terminal IPython, the QtConsole and plain Python as well, by printing
rto streams.
clear_output()avoids the flicker in the notebook by adding a delay, and firing immediately upon the next actual display message.
display_javascripthides its
output_areaelement,.
Major Bugs fixed¶
In this cycle, we have closed over 740 issues, but a few major ones merit special mention:
- The
%pastebinmagic has been updated to point to gist.github.com, since unfortunately has closed down. We also added a -d flag for the user to provide a gist description string. PR #1670.
- Fix
%pastethat would reject certain valid inputs. PR #1258.
- Fix sending and receiving of Numpy structured arrays (those with composite dtypes, often used as recarrays). PR #2034.
- Reconnect when the websocket connection closes unexpectedly. PR #1577.
- Fix truncated representation of objects in the debugger by showing at least 80 characters’ worth of information. PR #1793.
- Fix logger to be Unicode-aware: logging could crash ipython if there was unicode in the input. PR #1792.
- Fix images missing from XML/SVG export in the Qt console. PR #1449.
- Fix deepreload on Python 3. PR #1625, as well as having a much cleaner and more robust implementation of deepreload in general. PR #1457.
Backwards incompatible changes¶
- The exception
IPython.core.error.TryNextpreviously accepted arguments and keyword arguments to be passed to the next implementation of the hook. This feature was removed as it made error message propagation difficult and violated the principle of loose coupling. | http://ipython.readthedocs.io/en/stable/whatsnew/version0.13.html | CC-MAIN-2018-34 | refinedweb | 1,662 | 56.15 |
> Given that log4j.dtd has an impact on the interaction among
> log4* projects, should we rename log4j.dtd to a more neutral
> name and move it to Logging Services?
Do you also intend to make the dtd itself more neutral, for example do you
propose changing the namespace?
If you change the namespace it becomes a different schema which needs to be
supported separately by the log4 frameworks. That means that you can add
back in the #required attribute on sequenceNumber and make any other
breaking changes you want. Maybe we could rename the <throwable> element
<exception> as it is a more globally understood term.
Cheers,
Nicko
----
Nicko Cadell
log4net dev | http://mail-archives.apache.org/mod_mbox/logging-general/200405.mbox/%3C487B2B5FD092D411977400D0B73EB0A23B756B@titan.neoworks.co.uk%3E | CC-MAIN-2015-27 | refinedweb | 111 | 74.59 |
NAME
libroar - RoarAudio sound library
SYNOPSIS
#include <roaraudio.h>
DESCRIPTION
libroar is a central library used to comunicate with RoarAudio servers. It supports all commands from simple commands to play some audio up to complex commands to controll the server and do nice things over the network. It also includes several useful functions from buffer mangement to IO abstraction.
EXAMPLES
The basic tools shiped with RoarAudio are designed to also work as examples for the lib. You may start by looking at roarcat(1)s source code as an example on how to simply play back some audio. A more complex example is roarvorbis(1) which also includes meta data updates. You should also have a look at VS API, see roarvs(7) for a overview.
TUTORIALS
Tutorials can be found in roartut(7).
ENVIRONMENT VARIABLES
The following variables are used in libroar itself so they are common to all clients using libroar. HOME The users home directory. ROAR_SERVER The address of the listening server. This may be in form of host:port for TCP/IP connections and /path/to/sock for UNIX Domain Sockets. If a value of '+fork' is given a roard is forked and used. This roard will not listen on any sockets so it is used exclusiv by this client. See roard(1) for more information. ROAR_PROXY Set the type of the proxy being used to connect to the server. Valid values are 'socks4', 'socks4a', 'socks4d', 'http' and 'ssh' for the moment. You can add type depending options in form 'type/opts'. socks_proxy The SOCKS4/4a/4d/5 proxy to use in form [user@]host[:port]. Default port is 9050. http_proxy, https_proxy The HTTP/HTTPS Proxy server. This server needs to understand the CONNECT request type. Give the server name in this format: [http://]host[:port][/] The default port is 8080. ssh_proxy The remote host to use as SSH Proxy server. Give the server name in this format: [user@]host[:port] The default port is 22. Note that you may need to use publickey based auth or ssh-agent because the application may start SSH in a non interactive environment and SSH can not ask you for a password.
FILES
/etc/roarserver This is a symlink to the server socket. If all types of server addresses are supported. Example: ln -s /tmp/roar /etc/roarserver ln -s somehost /etc/roarserver ln -s mynode:: /etc/roarserver
BUGS
A lot...
SEE ALSO
roar-config(1), roartypes(1), roarvs(7), roartut(7), roard(1), roartips(7), RoarAudio(7).
HISTORY
See RoarAudio(7). | http://manpages.ubuntu.com/manpages/precise/man7/libroar.7.html | CC-MAIN-2016-36 | refinedweb | 423 | 67.65 |
wcscmp man page
Prolog
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
wcscmp — compare two wide-character strings
Synopsis
#include <wchar.h> int wcscmp(const wchar_t *ws1, const wchar_t *ws2);
Description
The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008 defers to the ISO C standard..
Return Value
Upon completion, wcscmp() shall return an integer greater than, equal to, or less than 0, if the wide-character string pointed to by ws1 is greater than, equal to, or less than the wide-character string pointed to by ws2, respectively.
Errors
No errors are defined.
The following sections are informative.
Examples
None.
Application Usage
None.
Rationale
None.
Future Directions
None.
See Also
wcscasecmp(), wcsncmp()scasecmp(3p), wcscoll(3p), wcsncmp(3p), wcsxfrm(3p). | https://www.mankier.com/3p/wcscmp | CC-MAIN-2019-04 | refinedweb | 177 | 50.23 |
Material Design
Material.
What you should already know
- How to create apps with activities and fragments, and navigate between fragments passing data
- Using views and view groups to lay out a UI, in particular
RecyclerView
- How to use Architecture Components, including
ViewModel, with the recommended architecture to create a well-structured and efficient app
- Data binding, coroutines, and how to handle click events
- How to connect to the internet and cache data locally using a
Roomdatabase
- How to set view attributes, and how to extract resources into and use resources from XML resource files
- How to use styles and themes to customize the look of your app
What you'll learn
- How to apply Material Design principles to the UI of your app
- How to use Material components to make your app beautiful
- How to extract and use dimensions
- How to create and use custom and Material color schemes for your app's UI
What you'll do
- Improve the UI of a given app using Material components, dimensions, and color...
Step 1: Add a FAB to the home fragment layout
- Download and run the GDGFinderStyles app, which is the starter app for this codelab. If you did the preceding codelab, you can continue from the final code of that codelab.
- In
build.gradle(Module: app), verify that the material library is included. To use Material Design components, you need to include this library. Make sure to use the latest library version.
implementation 'com.google.android.material:material:1.2.0'
- Open
res/layout/home_fragment.xmland switch to the Text tab.
Currently, the home screen layout uses a single.
- In
home_fragment.xml, add a
CoordinatorLayoutaround the
ScrollView.
<androidx.coordinatorlayout.widget.CoordinatorLayout android: ... </androidx.coordinatorlayout.widget.CoordinatorLayout>
- Replace <
ScrollView>with <
androidx.core.widget.NestedScrollView>. Coordinator layout knows about scrolling, and you need to use
NestedScrollViewinside another view with scrolling for scrolling to work correctly.
androidx.core.widget.NestedScrollView
- Inside and at the bottom of the
CoordinatorLayout, below the
NestedScrollView, add a
FloatingActionButton.
<com.google.android.material.floatingactionbutton.FloatingActionButton android:
- Run your app. You see a colored dot in the top-left corner.
- Tap the button. Notice that the button visually responds.
- Scroll the page. Notice that the button stays put.
Step 2: Style the FAB
In this step, you move the FAB to the bottom-right corner and add an image that indicates the FAB's action.
- Still in"
- Check in the Preview pane that the button has moved.
- Add a
layout_marginof
16dpto the FAB to offset it from the edge of the screen.
android:layout_margin="16dp"
- Use the provided
ic_gdgicon as the image for the FAB. After you add the code below, you see a chevron inside the FAB.
app:srcCompat="@drawable/ic_gdg"
- Run the app, and it should look like the screenshot below.
Step 3: Add a click listener to the FAB
In this step, you add a click handler to the FAB that takes the user to a list of GDGs. You've added click handlers in previous codelabs, so the instructions are terse.
- In
home_fragment.xml, in the
<data>tag, define a variable
viewModelfor the provided
HomeViewModel.
<variable name="viewModel" type="com.example.android.gdgfinder.home.HomeViewModel"/>
- Add the
onClicklistener to the FAB and call it
onFabClicked().
android:onClick="@{() -> viewModel.onFabClicked()}"
- In the home package, open the provided }
- In the home package, open the
HomeFragmentclass. Notice that
onCreateView()creates the
HomeViewModeland assigns it to
viewModel.
- Add the
viewModelto the
bindingin
onCreateView().
binding.viewModel = viewModel
- To eliminate the error, clean and rebuild your project to update the binding object.
- Also in() } })
- Make the necessary imports from
androidx. Import this
findNavControllerand
Observer:
import androidx.navigation.fragment.findNavController import androidx.lifecycle.Observer
- Run your app.
- Tap the FAB and it takes you to the GDG list. If you are running the app on a physical device, you are asked for the location permission. If you are running the app in an emulator, you may see a blank page with the following message:
If you get this message running on the emulator, make sure you are connected to the internet and have location settings turned on. Then open the Maps app to enable location services. You may also have to restart your emulator..
Step 1: Use Material theme attributes
In this step, you change the styling of the title headers on the home screen to use Material Design theme attributes to style your views. This helps you follow the Material style guide while customizing your app's style.
- Open the Material web page for typography theming:
The page shows you all the styles available with Material themes.
- On the page, search or scroll to find
textAppearanceHeadline5(Regular 24sp) and
textAppearanceHeadline6(Regular 20sp). These two attributes are good matches for your app.
- In"
- Preview your changes. Notice that when the style is applied, the font of the title changes. This happens because the style set in the view overrides the style set by the theme, as shown by the style-priority pyramid diagram below..
- In the
title
TextView, replace the styling you just added with a
textAppearance.
- Preview your changes, or run the app to see the difference. For comparison, the screenshots below show the differences when the Material style is applied to the title and overrides the
Titlestyle.
Step 2: Change the style in the Material theme.
- Open
styles.xml.
- Delete the
Titleand
Subtitlestyles. You are already using
textAppearanceHeadline5instead of
Title, and you are going to remove the need for
Subtitle.
- Define a>
- Inside this style, override the default
textAppearanceHeadline6of the theme, by defining an item that styles
textAppearanceHeadline6with the custom style that you just added.
<item name="textAppearanceHeadline6">@style/TextAppearance.CustomHeadline6</item>
- In
home_fragment.xml, apply
textAppearanceHeadline6to the
subtitleview and reformat your code (Code > Reformat code).
android:textAppearance="?attr/textAppearanceHeadline6"
- Run the app. Notice the difference in font color, which is subtle, but makes a big difference in how readable the screen is..
Step: Use theme overlays.
- Open
activity_main.xmland find where the
Toolbaris defined (
androidx.appcompat.widget.Toolbar). The
Toolbaris part of Material Design and allows more customization than the app bar that activities use by default.
- To change the toolbar and any of its children to the dark theme, start by setting the theme of the
Toolbarto the
Dark.ActionBartheme. Make sure you do this in the
Toolbar, not in the
ImageView.
<androidx.appcompat.widget.Toolbar android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
- Change the background of the
Toolbarto
colorPrimaryDark.
android:>IMAGE_4<<.
- In the
ImageViewinside the
Toolbar, set the tint to
colorOnPrimary. Because the drawable includes both the image and the GDG Finder text, both will be light.
android:tint="?attr/colorOnPrimary"
- Run the app and notice the dark header from the theme. The.
Step 1: Examine your code
- Open
home_fragment xml.
- Look at the Design tab and make sure the blueprint is visible.
- In the Component Tree, select the
start_guidelineand
end_guideline. They should be slightly highlighted in the blueprint.
- Notice the number 16 on the left and the number 26 on the right, indicating the inset of the start and end guidelines, respectively.
- Switch to the Text tab.
- Notice that at the bottom of the.
Step 2: Create a dimension
- In
home_fragment xml, using the Text view, put your cursor on the
16dpof
app:layout_constraintGuide_begin="16dp".
- Open the intentions menu and select Extract dimension resource.
- Set the Resource Name of the dimension to
spacing_normal. Leave everything else as given and click OK.
- Fix
layout_constraintGuide_endto also use the
spacing_normaldimension.
<androidx.constraintlayout.widget.Guideline android:id="@+id/end_grid" app:layout_constraintGuide_end="@dimen/spacing_normal"
- In Android Studio, open Replace All (
Cmd+Shift+Ron the Mac or
Ctrl+Shift+Ron Windows).
- Search for 16dp and replace all occurrences, except the one in
dimens.xml, with
@dimen/spacing_normal.
- Open
res/values/dimens.xmland notice the new
spacing_normaldimension. Make sure you didn't accidentally replace the 16dp with a self-reference!
- Run your app.
- Notice that the spacing on the left and right of the text is now the same. Also, notice that the spacing affects line breaks, and the text in the right screenshot is one line shorter..
Step 1: Create a Material color scheme
- Open. You can use this tool to explore color combinations for your UI.
- Scroll down in the MATERIAL PALETTE on the right to see more colors.
- Click Primary, then click a color. You can use any color you like.
- Click Secondary and click a color.
- Click Text to choose a text color if you want a color that is different from the one the tool has calculated for you. Pick various text colors to explore contrast.
- Click the ACCESSIBILITY tab. You will see a report like the one below. This gives you a report about how readable the currently selected color choices are.
- Look for the triangular exclamation mark icons.
- In the tool, switch to the CUSTOM tab and enter the following two colors.
- Primary: #669df6
- Secondary: #a142f4.
- On the top-right of the window, select EXPORT and ANDROID. The tool initiates a download.
- Save the
colors.xmlfile in a convenient location.
Step 2: Apply the Material color scheme to your app
- Open the downloaded
colors.xmlfile in a text editor.
- In Android Studio, open
values/
colors.xml.
- Replace the resources of
values/
colors.xmlwith the contents of the downloaded
colors.xmlfile.
- Open
styles.xml.
- Inside the
AppTheme, delete the colors that show as errors:
colorPrimary,
colorPrimaryDark, and
colorAccent.
- Inside>
- Run the app. This looks pretty good...
- However, notice that
colorOnPrimaryisn't light enough for the logo tint (including the "GDG Finder text") to stand out sufficiently when displayed on top of
colorPrimaryDark.
- In
activity_main.xml, find the
Toolbar. In the
ImageView, change the logo tint to
colorOnSecondary.
- Run the app.
Android Studio project: GDGFinderMaterial.
Floating action buttons
- The floating action button (FAB) floats above all other views. It is usually associated with a primary action the user can take on the screen. You add a click listener to a FAB in the same way as to any other UI element.
- To add a FAB to your layout, use a
CoordinatorLayoutas the top-level view group, then add the FAB to it.
- To scroll content inside a
CoordinatorLayout, use the
androidx.core.widget.NestedScrollView.
Material Design
- Material Design provides themes and styles that make your app beautiful and easier to use. Material Design provides detailed specs for everything, from how text should be shown, to how to lay out a screen. See material.io for the complete specifications.
- To use Material components, you need to include the Material library in your gradle file. Make sure to use the latest library version.
implementation 'com.google.android.material:material:1.2.0'
- Use
?attrto apply material theme attributes to a view:
style="?attr/textAppearanceHeadline5"
Themes and styles
- Use styles to override theme attributes.
- Use theme overlays to apply a theme to just a view and its children. Apply the theme to the parent view. For example:
android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
Then use the
?attr notation to apply attributes to a view. For example:
android:background="?attr/colorPrimaryDark"
Colors
- The Color Tool helps you create a Material palette for your app and download the palette as a
color.xmlfile.
- Setting a tint on the
ImageViewcauses the
ImageViewto be "tinted" to the specified color. For example, you might use
android:tint="?attr/colorOnPrimary". The
colorOnPrimarycolor is designed to look good on
colorPrimary.
Dimensions
- Use dimension for measurements that apply to your whole app, such as margins, guidelines, or spacing between elements.
Udacity course:
Android developer documentation:
- Attributes of Themes
- Add a Floating Action Button
- Dimensions
- Dimension class
- Gutters and Margins
- material.io
- Material Design
- Material Design for Android
- Material Theme and Color
- Material Color System
- Color Tool
- Color Theming.
Question 2
Which
ViewGroup allows you to stack views on top of each other?
▢
CoordinatorLayout
▢
StackedViewsLayout
▢
ConstraintLayout
▢ You cannot stack views
Question 3.
Question 4.
Question 5. | https://developer.android.com/codelabs/kotlin-android-training-material-design-dimens-colors?authuser=1&hl=ko | CC-MAIN-2021-39 | refinedweb | 1,977 | 50.63 |
Not abel to get the list of items using NoSql distributed cache Database- RedisHai Guys,
Please let me know if anyone has worked with the NoSql distributed cache database-Redis
I am trying to do something using the console application. By now I am able to create the Server as well as client and also can connect the server to client. But not able to retrieve the database content like the collections and all.
I want to get the list of the records which are in the database and then I can use the Linq or Lambda expression to filter and query the records.
As I am trying with the Visual Studio and new to this, so getting the issue. I tried to learn from other websites and links but still didn't get the proper solution as most of the places, I can see peoples are just setting the records and then getting them from the cache. But in my case, I already have the database and I need to filter the records from the database.
I am using the below code snippet after installing all the necessary references:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
namespace RedisDemoApp
{
class Program
{
static void Main(string[] args)
{
using (var redisClient = new RedisClient("127.0.0.1", 6391))
{
IRedisTypedClient<Hotel> redis = redisClient.As<Hotel>();
IRedisList<Hotel> mostSelling = redis.Lists["urn:hotel_ids"];// not working
.......
}
}
}
}
Please let me know if anyone has any idea regarding this. It will be great help for me.
Thanks in advance. | http://www.dotnetspider.com/forum/345164-Not-abel-to-get-the-list-of-items-using-NoSql-distributed-cache-Database.aspx | CC-MAIN-2017-17 | refinedweb | 268 | 67.45 |
05 – Static vs. Instance
As simple as classes are there is much we still need to learn about them, so the next several sections are divided into more detailed topics about classes. The first and possibly the most challenging to understand is what is meant by static attributes versus instance attributes.
So far in our sample code our methods have all been statically defined. That makes them available to any class without creating an instance of the class they are defined in. Creating an instance of a class is the most common way that a class is accessed and it allows you to store data specific to the instance of the class along with whatever methods are available to that class. That may seem a bit circular so it may be better expressed with an analogy.
For example, if we wanted to create an abstract representation of a car in our program we would write a car class the encapsulated the critical features of a car in Java code. That class would be a representation of a car idea, though, and not a representation of a specific car. If we wanted a specific car, we would create an instance of that class and programmatically set the attributes of the car to meet our needs.
To make the example more concrete let’s look at an example car class that has a mixture of static and instance methods in it:
public class Car {
private int speed;
private String color;
// This method is our constructor
// we use it to set some initial conditions.
public Car() {
speed = 0;
color = “unknownâ€;
}
// Set our car's speed
public void setSpeed(int value) {
speed = value;
}
// Get our car's speed
public int getSpeed() {
return speed;
}
// Set our car's color
public void setColor(String value) {
color = value;
}
// Get our car's color
public String getColor() {
return color;
}
// Determine if an object happens to be a car
public static boolean isCar(Object thing) {
if (thing instanceof Car) {
return true;
} else {
return false;
}
}
}
This class has a number of interesting features that hopefully help illustrate some of the differences between class and instance methods and variables.
First note that the variables are instance variables (they are not static) and they are private. That means that they can only be accessed by this class and not any external class (this is good programming practice – allowing other code to alter our variables can cause unexpected results). Second, because of this limitation we create what are called accessor methods to get and set these variables. This is a common practice in Java programming as mentioned above. Forcing other code to alter our state through methods we provide in our code means that we as programmers can be in control of the state of our classes.
Lastly this class contains one class method (or static method) that simply helps determine if an object (an instance of a class) is a Car object or not. Let’s take a look at how this class and it’s features might be used within a program.
// Skipping some imports and other stuff
// we'll talk about later.
public class TestCar1 {
public static void main(String[] args) {
// Create an instance of Car called myCar
Car myCar = new Car();
// Call myCar's instance methods
myCar.setSpeed(55);
myCar.setColor(“redâ€);
// Going to call the isCar test method
// statically from the Car class
boolean test = Car.isCar(myCar); // true!
String s = “I'm not a car!â€;
test = Car.isCar(s); // false!
}
}
Hopefully at last the difference between an instance of a class and the class itself is clear now. In the first line of our program above we create a car object – an instance of car. We then proceed to call two of the methods of our car instance. Finally, we perform two tests (although we never do anything with the answer) using the static isCar method from the Car class.
Static vs. Instance Exercise
Create a class using the following stub, which describes a human in code. It should contain an instance variable (not static) to store the person’s age, methods to get and set the age, and a static method to return a String description of a person (in general, not your particular person created when you instantiate your object).
public class Human {
// Instance Variables
// Instance Methods
// Class Method
} | http://nule.org/wp/?page_id=140 | CC-MAIN-2017-13 | refinedweb | 729 | 65.46 |
In the desert land of french IT service it is hard to get satisfaction in our everyday projects, and we have very few opportunities to cross the path of such masters . Personally my only satisfactions come from my own learning from the masters... alas from book, videos, articles.Few chats with one of them in a twitter exchange is worth all the gold on earth.
Stop self-pitying, hopefully, all the time out of the daily job can be dedicated to exploration, discovery...and blog buddies =D
Recently we tried o to promote J2EE 6, hoping that the current client would accept to finally switch to a universally adopted standard, we once more had to start dealing with a mess, some big ball of muddy mixed services and strange God objects. Tough play. Fortunately J2EE 6 is lighter (pruning), easier to use (optional XML, more AOP), richer in terms of API, really more business oriented than the 5.0 level was, and it really gazes to a brighter cloudy future.
Naturally, I came to acquire a copy of a J2EE 6 book in order to upgrade my knowledge from the 5.0 version up to the 6.0 one, in a more friendly approach. I chose Antonio Goncalves' Beginning JavaEE6 with GlassFish 3, 2nd Edition. Don't be foolished by the title. Although every naive java developer can start with the content, every astute J2EE developer can find in almost every page valuable information. Reading this gold mine will help you in grabbing good habits and fully adopting the 6.0 standard peacefully. So, this is a good way to escape from the everyday routine.
As I promised myself to try to deliver something on a regular base(shame on me I am late, too few hours during the day), I did not want to re-do a carbon copy of Mr Goncalves book content. There are still so many presentations exposing J2EE6 and its benefits.
Like a lot of developers I have some difficulties in self organization so I planned to work on a kind of small personal planning board (very, very light kanban one). A J2EE application would be a good approach. In the mean time it came to me how difficult it was to study so many things in parallel (too many books). I have started practicing Scala, upgrading to J2EE6, recently started playing with Clojure, and still gazing to Lisp and Erlang
Why not gathering the J2EE6 adventure and the Scala one, for a while ? It may be ambitious. Maybe not. So before even trying to attempt a Reenskaugh/Coplien DCI approach, selecting my Use Cases, identifying the Roles, planning some form of architecture, I have to set up an environment, a working skeleton as defined by Nat Pryce and Steve Freeman in Growing object Oriented software guided by tests. This approach would allow me to define a broad picture of a working environment mixing Scala and J2EE 6.
How can I start ? The most important thing to do is to start. After all incredible people like David Pollack must have been starting somewhere before becoming experts in application servers design like Lift.
I want to work in a J2EE6 environment using the Scala language. So let set a Maven 3.0 environment to work with my IntelliJ 10.5. I am going through this experience the hard way: I will set the dependencies as the sum of all the dependencies needed both in a J2EE project, and inScala project. For a very first baby step I will focus on creating an entity, paired with some managing EJB service. What I want is a working shell. An embedded environment for TDD. Second step (I hope in some upcoming article) will be to make the stuff deployable.
Let the entity be an elementary task, then I will create a task service.
I want to work with J2EE, so I may need the following dependencies:
org.eclipse.persistence javax.persistence 2.0.3 org.eclipse.persistence eclipselink 2.2.0 org.glassfish javax.ejb 3.1 org.glassfish.extras glassfish-embedded-all 3.1 test org.apache.derby derby 10.8.1.2 junit junit 4.8.2 test org.scala-lang scala-library 2.8.1
The javax.persistence and javax.ejb dependencies reference the J2EE standards definitions. The eclipse link dependency is the JPA 2.0 implementation I chose, following Antonio's recommendations.
For test scope only I set a reference to the Glassfish embedded container. The embedded container appeared in J2EE 6 in order to simplify the development of unitary tests on EJB components but in a standard J2SE context providing the same managed environment - so facilities (transaction, CDI, AOP, security...) -as the one found into application servers.
The Scala library is the 2.8.1 as I have to work with the Scala Maven plugin. Discussing about plugins configuration I defined the following build configuration:
src/main/scala src/test/scala ${project.basedir}/src/main/resources ${project.basedir}/src/test/resources org.scala-tools maven-scala-plugin compile testCompile 2.8.1 org.apache.maven.plugins maven-compiler-plugin 2.3.2 true 1.61.6 1.6 org.apache.maven.plugins maven-jar-plugin 2.3.1
Well, this is really a brute force approach. I defined all I think I needed and chose to work into scala directories.
In order to avoid download problems, I selected the set of following repositories:
UK-plugin scala-tools.org Scala-tools Maven2 Repository glassfish-maven-repository.dev.java.net GlassFish Maven Repository UK EclipseLink Repo scala-tools.org Scala-tools Maven2 Repository
Fine we are ready to start ! IntelliJ starts up, recognizes my Scala facets, So far, so good, happy camper I am.
I need a task. I want to persist it and reload it. For starting purpose, let say my task will have a title and of course an id. The test cases are defined as
import org.junit.Test import org.junit.Assert._ class TestTask { @Test def id_WithTestValue_ShouldBeBound() { val task = new Task task.id = 17 assertEquals(17, task id) } @Test def title_WithTestValue_ShouldBeBound() { val task = new Task task.title = "myTitle" assertEquals("myTitle", task title) } }
This leads me to the following Task definition template:
import javax.persistence._ @Entity @NamedQuery(name = "findAllTasks", query = "SELECT t FROM Task t") class Task { @Id@GeneratedValue var id: Long = 0 @Column(nullable = false) var title: String = null }
For clarity purpose, as a first shot, I chose to annotate my Scala fields. As Scala definitions are short, I found more elegant to leave the annotations on the same lines as the field declarations.
Naturally I flagged the definition template with the @Entity annotation. Then I cheated, anticipating a named query dedicated to the selection of all persisted tasks.
How fine and simple is this class template definition, all the beauty of Scala in the uniform access principle application: "It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove" (A. de Saint Exupery)
Hurrah, I've got an entity... written in Scala.
Now I want a service to manage this basic skeleton task. How will I query the service in an embedded mode ? I need this very nice stuff introduced in J2EE 6 and destined to ease the integration tests: an embedded EJB container !!! As a reference implementation, Glassfish does provide one (the purpose of the reference in the testing scope).
All I have to to then, is to :
- start the embedded container
- find my service through JNDI lookup
- persist my task
- assert my task id has been set
- reload my list of persisted tasks
- assert my list is not empty
So be it:
import org.junit.Test import javax.ejb.embeddable.EJBContainer import com.promindis.planning.entities.Task import org.junit.Assert._ import java.util.List final class TestTaskService { @Test def createTask_WithTestTask() { val ec = EJBContainer.createEJBContainer val ctx = ec.getContext val task = new Task task.title = "testing task" val service: TaskEJB = ctx.lookup("TaskEJB").asInstanceOf[TaskEJB] service.createTask(task) assertNotNull(task id) val foundTasks: List[Task] = service.findAllTasks() assertNotNull(foundTasks) assertEquals(1, foundTasks size) ctx.close() } }
Compilation error ! Of course, I must create the service. The solution comes easilly, thanks to the J2EE 6 AOP approach:
import javax.ejb.{LocalBean, Stateless} import javax.persistence.{EntityManager, PersistenceContext} import com.promindis.planning.entities._ import java.util.List @Stateless @LocalBean class TaskEJB{ @PersistenceContext(unitName = "planningPU") private var em: EntityManager = null def findAllTasks(): List[Task] ={ val query = em.createNamedQuery("findAllTasks", classOf[Task]) query.getResultList } def createTask(task: Task) { em.persist(task) } }
The service is flagged as a stateless local bean, hosting an injected entity manager (Dependency injection is cool when sticking to a standard).
Because I don't know how to proceed for now, I decided not to wrapp the java List in a Scala one (maybe you can help me on that point)
On behalf of the service, the container will manage the transactions during the entity manager invocations.
In upcoming steps I will want to query my service remotely. In a standard Java approach, this would require the definition of an interface flagged with a @Remote annotation. But we know that a 100% abstract Scala trait compiles as an interface.
Let's make a try:
import javax.ejb.Remote import com.promindis.planning.entities.Task import java.util.List @Remote trait TaskEJBRemote { def findAllTasks() : List[Task] def createTask(task: Task) }
Easy, so our service becomes:
import javax.ejb.{LocalBean, Stateless} import javax.persistence.{EntityManager, PersistenceContext} import com.promindis.planning.entities._ import java.util.List @Stateless @LocalBean class TaskEJB extends TaskEJBRemote { @PersistenceContext(unitName = "planningPU") private var em: EntityManager = null def findAllTasks(): List[Task] ={ val query = em.createNamedQuery("findAllTasks", classOf[Task]) query.getResultList } def createTask(task: Task) { em.persist(task) } }
One minute, I have named a persistence unit to bind to the entity manager. So I need a persistence.xml file.
Easy said, (not-so)easy done:
org.eclipse.persistence.jpa.PersistenceProvider com.promindis.planning.entities.Task
Although it is embedded, we are still working with a container, so the transaction type appears to be JTA. The logging level is fixed to FINE as I like to understand what happens.
Note that the database connection properties makes part of the j2ee 6 standard:
- javax.persistence.jdbc.driver
- javax.persistence.jdbc.url
- javax.persistence.jdbc.user
- javax.persistence.jdbc.password
I chose a drop-and-create-tables ddl-generation schema so to get rid of my database table after test.
Everything's ready. Engage. I open a command console and hit
mvn clean test
Test is automatically run. I have a test failure. Ah right. Some problem with the name service binding. Since J2EE 6, apparently, an agreement has been found onto a global uniform naming convention into the JNDI namespace:
java:global[/<app-name>]/<module-name>/<bean-name>[!<fully-qualified-interface-name>]
Riiiight . Logs in my console give me a hint I would not have guessed alone:
Portable JNDI names for EJB TaskEJB : [java:global/classes/TaskEJB!com.promindis.planning.services.TaskEJBRemote, java:global/classes/TaskEJB!com.promindis.planning.services.TaskEJB]
I replace it with the second defintion
val service: TaskEJB = ctx.lookup("java:global/classes/TaskEJB!com.promindis.planning.services.TaskEJB").asInstanceOf[TaskEJB]
relaunch ...and it works !!!
For the moment I have to trust my environment when it tells me he ran the test, persisted and re-loaded my task. But a real complete environment requires to be able to produce a fully deployable application set >_<.
This will be the next step and I will then be able to run an external client and create records in more permanent database.
One moment, before going to bed, I want to check my remote interface (my Scala trait) is really compiled as an interface. After running:
javap -p TaskEJBRemote.class
I get this:
public interface com.promindis.planning.services.TaskEJBRemote { public abstract java.util.List<com.promindis.planning.entities.Task>findAllTasks(); public abstract void createTask(com.promindis.planning.entities.Task); }
Good!!!
So we have seen that the promise of a more universal JVM is not only a promise. It does still require some work to do but we are on our way.
I am tired and need four, five hours sleep.
Be seeing you !!!!
3 comments:
I just had an interesting exchange on twitter with Heiko Seeberger from Typesafe who was kind enough to read the article.
He pointed out - quoting - that "using #Scala for #JEE 6 won't work for real world examples. At least not for CDI." than that
"The #Scala compiler creates too many public fields / final public methods for proxy based solutions like CDI."
I really thank him very much about this fruitful exchange. This will encourage me to go deeper into the exploration of CDI into a more standard way.
The richness of this exchange is very valuable and will guide me into my upcoming experimentation.
Useful post - was able to utilise some of the Maven settings for the book examples :-)
Thank you really. Glad you could use some Maven settings, because I always The Well-Grounded Java Developer MEAP at hand :-). | http://patterngazer.blogspot.com/2011/06/mixing-j2ee-6-and-scala-first-shot.html | CC-MAIN-2019-09 | refinedweb | 2,189 | 50.63 |
How to read file into bytearrayoutputstream
This tutorial shows you how to read file using byteinputstream and then write to another file using bytearrayoutputstream. This example code is very helpful in learning the concept of byte input stream and byte output stream. This is and good example of reading file into bytearrayoutputstream.
This example will teach you how you can read the file into byte array and then write byte array data into a file.
In this example we have used the class InputStream for reading the file content into byte array. The read (byte[] bytes) is used to read the data into byte array. Our example reads the data using read(byte[] bytes) method and then using FileOutputStream class writes the data into a new file.
The fileOutputStream.write(bytes) of the FileOutputStream class is used to write the bytes data into a file.
Here is the code of the example program:
import java.io.*; /** * Example of Reading file into byte array and then write byte array into a file */ public class ReadingFileToByteArrayOutputStream { public static void main(String[] args) { System.out.println("Example of Reading file into byte array and then write byte array into a file"); try{ //Instantiate the file object File file = new File("test.text"); //Instantiate the input stread InputStream insputStream = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int) length]; insputStream.read(bytes); insputStream.close(); //Write the bytes to a file FileOutputStream fileOutputStream = new FileOutputStream("test2.text"); fileOutputStream.write(bytes); }catch(Exception e){ System.out.println("Error is:" + e.getMessage()); } } }
Read more at Java File - Example and Tutorials.
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Discuss: Reading file into bytearrayoutputstream
Post your Comment | http://www.roseindia.net/java/javafile/reading-file-into-bytearrayoutputstream.shtml | CC-MAIN-2014-49 | refinedweb | 296 | 57.67 |
This post is a follow up to Redux Testing: Hard Lessons Learned where I spoke about two important principles for testing redux apps: "Stop Testing your Disconnected Components" and "Build a Small Utility Library". Mostly we went through some of the key utilities that I use to make testing redux apps more manageable. This post will cover another area I called out in the first post: Render Components with a Real Store
For a long time I relied on redux mock store to preload data into my components for rendering during tests. This approach makes it easy to take a snapshot of a component with arbitrary data and ensure that it renders correctly. Where it completely fails is testing interactions.
What happens when I click the close the button or when I select that image? With redux mock store you have a special method named getActions that tells you what actions were fired, but that's it. Those actions don't actually make it to your reducers and they never update the UI. This makes your tests pretty frustrating to write. There's no good way to confirm that a component can transition from one state to another. You can only test snapshots.
The first and quickest way to solve this is to pass your actual redux store into the
<Provider> you use to wrap your tests and then return it. For example:
import { render } from "@testing-library/react"; import { store } from "../app/store"; function renderWithContext(element) { render( <Provider store={store}>{element}</Provider> ); return { store }; }
This immediately gives you all kinds of powers. The first one is the ability to dispatch actions to populate or otherwise your modify redux store. Because those actions are dispatched synchronously you can immediately assert that the UI was updated.
test("table should render all kinds of data", () => { const { store } = renderWithContext(<ResultsTable />); // expect() table to be empty store.dispatch({ type: "POPULATE_DATA", data: { /* ... */ }) // expect() table to be full });
The other thing it lets you do is assert that your redux store changed in response to an event that wouldn't normally affect the component you are testing. For example let's say you had a button that updated a counter, but that counter component lived somewhere else. We can pretty easily test that clicking the button updated the count in our store.
test("counter should update count", () => { const { store } = renderWithContext(<CounterButton />); expect(store.getState().count).toEqual(0); userEvent.click(screen.getByRole("button")); expect(store.getState().count).toEqual(1); });
Now the issue with sharing your actual redux store is that the order of your tests shouldn't matter. You really want to run your tests in isolation. With the shared store approach if you dispatch an event in one test, the changes are propagated to all future tests. And that's why I ended up with the
getStoreWithState method I showed in my previous article as a key utility.
// ... export const store = configureStore({ reducer }); export function getStoreWithState(preloadedState) { return configureStore({ reducer, preloadedState }); }
There are two important parts here. The one that I mentioned before was the
preloadedState option, which lets us render components in tests with state already setup in a specific way (similar to mock redux store). The second and more subtle accomplishment here is that we're giving our generated store access to the same reducers used by our app's store. This gives us an isolated store to use for each test that also has access to the full power of our application's reducers.
One benefit of this approach is that every time we test a component hooked into redux, we're also testing multiple reducers. It more economical and it more accurately reflects how our application actually works. Not to mention your tests are way easier to write this way. If you're used to testing with mock-redux-store this approach is going to give you a huge boost.
If you want to learn more about my approach to testing redux applications please watch my course Confidently Testing Redux Applications with Jest and TypeScript.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/xjamundx/redux-testing-lessons-learned-give-your-components-access-to-your-reducers-508k | CC-MAIN-2022-21 | refinedweb | 675 | 53.1 |
Introduction: How to Use Bluetooth 4.0 HM10
In this example, I will show you how to communicate one micro controller to another micro controller BOTH WAYS via serial with cc2541 (BLE-HM-10). For board design and code please download BLE_Duplex). The Bluetooth 4.0 HM-10 is basically a breakout board for cc2541, it broke out the LED pins, RX/TX and also adding the voltage regulator that regular 5v to 3.3 v.
Bluetooth 4.0 HM-10 Master Slave Module
Bluetooth V4.0 BLE 2540 Hm-10
Step 1: Setup With FTDI + Arduino Serial Monitor + AT Command
Setup with FTDI + Arduino Serial Monitor + AT Command
There are so many things that you can do with Bluetooth 4.0 HM-10, but first you need to setup with FTDI cable to understand what and how it's doing.
You will need a FTDI cable and 4 female to male wires to hook up to Bluetooth 4.0 HM-10 / BLE
Step 2: Sending & Receiving (Both Ways ) Setting the Master-Slave Mode
With this method, you can turn the device on and have them talk to each other right away, without pairing, without initializing ... it is wonderful. The data goes both ways.
First you will need to Query the native MAC address using AT Command AT+ADDR?
You will get something like this 20C38FF61DA1, each BLE has a unique MAC address.
Use AT+CON[param1] and AT+ROLE[param1] to pair to another device.
Example
BLE A has Mac Address 11C11FF11DA1, ASend
Step 3:.
Step 4:.
The Arduino Code
/);
}
Participated in the
Arduino All The Things! Contest
Be the First to Share
Recommendations
27 Comments
4 years ago
Hey there, I need help!
I've a HM-10 and I need to connect to another BLE device that's suppose to supply my HM-10 with a bunch of data every few second.
My current condition is pairing with the device using AT+CON[mac] works and returns AT+CONNA and ends up with AT+CONNF.
I'm not sure what am I missing here. I've tried pairing it with my Android using a bluetooth terminal app and it works perfectly!
Is there any step that I'm missing like pairing or something?
Thanks!
Reply 2 years ago
Hi, I want to connect hm10 to my android phone but getting msg "Connection rejected " , could you please help me ?
Reply 2 years ago
hi,
i am also having the same issue..have u got any solution?
2 years ago
wasn't working for me as I had the version v.520(see "AT+VERR?" ) what i did is to upgrade its firmware and now it's working, also I did setup on the central (AT+ROLE1) with AT+IMME1 and AT+DISC? then AT+CONN[P1] where P1 is the index of the address of the peripheral
Reply 2 years ago
also if you want it to connect when starting set AT+IMME0 on the central after the setup
2 years ago
Hi,
i want to connect HM-10 with another BLE device (VNA-BT). i am able to connect that device on ble serial app in mobile but not with HM-10.can anybody help me ?
Thanks
2 years ago
Hello,
thanks for great job. I am using hm-10. it takes too long to pair with android app. I don't pair it via phone; I open the app and via app pair the hm-10. any suggestion to faster the paring time?
3 years ago
What means: "
exit status 1
'myservo' was not declared in this scope
I'm using Arduino IDE v1.8.3. This sketch does not pass verification. Is it supposed to be complete?
Reply 3 years ago
Disregard Q. Code is missing library call and instantiation:
#include <Servo.h>
Servo myservo;
Thanks.
3 years ago
hello guys, i need a help to proceed with ble
I have BLE HM 10 module and FTDI module . when i start giving AT commands
it responds to following AT COMMANDS
COMMANDS RESPONSE
1. AT - OK
2. AT+ADDR? - 00:15:83:00:57:E2
3. AT+VERSION? - Firmware V3. 0. 6 Bluetooth V4 . 0 .LE
4.AT+NAME? - NO RESPONSE
Please let me know the further procedure (AT COMMANDS) to test and how to connect with android phone.
THANKS!!!
4 years ago
Where did you buy your hm-10 modules. I had a horrible problem with getting fakes online. Also, the voltage level question....
You are using a FTDI cable that operates at 5 VOLTS. Do you need to use a voltage divider circuit (1k ohm/2k ohm) to bring down the voltage level to 3.3V at ftdi-TX/hm10-RX.
I have to ask because i had blown up several hm-10 modules (and a usb aerial module) before figuring this out
4 years ago
4 years ago
5 years ago
Hi,
If you are using the bare HM-10 module, make sure to cross connect RTS and CTS (pins 3 and 4, P1_4 and P1_5, UART_CTS and UART_RTS) otherwise the serial comms won't work. Note: Pins count from 1 top left, counter clock to 34 top right with the CC2541 chip facing you, antenna at the top. The manufacturers manual is confusing as it shows the antenna terminating on the right (Section 1.1 HM-10 Schematic), when it is in fact terminating on the left. Both diagrams in this instructable are correct.
Also note device is a DTE, so TX (pin 1, P1_6, UART_TX) is an output and RX (pin 2, P1_7, UART_RX) is an input.
The diagram in Step 1 eludes to this by cross coupling the TX and RX lines to an FTDI, effectively forming a NUL modem interconnection.
The AT command parser is poor quality (as you would expect), it requires all command strings be entered upper case (other than the name string). A command is considered entered once the interchar timer has been exceeded (for that given baud rate). ie no terminating character '\r'. There is no SReg support to set this via S3 (carriage return character). This means you will need to pre-store any commands and issue all in one go, back to back at your selected baud. This prevents the usual method of typing by hand and hitting enter as with all modem devices. Though to be fair the manual does mention this.
I found that the only consistent way to get activate changes was to either issue AT+RESET or power cycle the module.
Final note, changes are written to flash. ie they are permanent. Power cycling won't get rid of them.
Rgds
SQ
Reply 4 years ago
Thank you for these useful infos.
I succeeded thanks to you.
Reply 4 years ago
You're welcome
5 years ago
Dan,
Thanks for this instructable. Very informative. I hao 1tve an idea for a project that will aconnect 2 arduinos via bluetooth, but also be able to connect a phone 1 of the arduinos via bluetooth. The 2 arduinos will be connected together by default, using your method described above. But if I wanted the phone to connect, I would first need to disconnect them some how. Obviously, I want this to happen automatically. Do any modes support multiple connections in the HM-10. Do you have any idea how to make this work?
Thanks again for your work above. Fantastic!
Reply 4 years ago
I tried connecting two BLE modules by making one of them Master and the other Slave. The two pairs automatically. However if I try to discover the slave device using an iPhone the slave module is not shown on the device unless I disconnect the master. Is there any workaround for this ?
Reply 4 years ago
I also have the same problem - vajee
4 years ago
Very nice tuts. I would like to connect my hm10 module to andruino ide. But ide doesnt recognize that. I connected gnd to black , vvc to red, tx to green and rx to remained led and have plugged that to usb port on my comp.
What is me doing wrong? Thank you. | https://www.instructables.com/How-to-Use-Bluetooth-40-HM10/ | CC-MAIN-2021-21 | refinedweb | 1,361 | 73.98 |
Neighbor and destination cache management. More...
#include "core/net.h"
#include "ipv6/icmpv6.h"
#include "ipv6/ndp.h"
#include "ipv6/ndp_cache.h"
#include "ipv6/ndp_misc.h"
#include "debug.h"
Go to the source code of this file.
Neighbor and destination cache ndp_cache.c.
Definition at line 30 of file ndp_cache.c.
Create a new entry in the Destination Cache.
Definition at line 392 of file ndp_cache.c.
Create a new entry in the Neighbor cache.
Definition at line 50 of file ndp_cache.c.
Search the Destination Cache for a given destination address.
Definition at line 443 of file ndp_cache.c.
Search the Neighbor cache for a given IPv6 address.
Definition at line 103 of file ndp_cache.c.
Flush Destination Cache.
Definition at line 469 of file ndp_cache.c.
Flush Neighbor cache.
Definition at line 264 of file ndp_cache.c.
Flush packet queue.
Definition at line 349 of file ndp_cache.c.
Send packets that are waiting for address resolution.
Definition at line 290 of file ndp_cache.c.
Periodically update Neighbor cache.
Definition at line 133 of file ndp_cache.c. | https://oryx-embedded.com/doc/ndp__cache_8c.html | CC-MAIN-2018-51 | refinedweb | 178 | 57.13 |
2009/9/30 Pritesh Kothari <Pritesh Kothari sun com>: > Hi All, > > Just minor fix's. > > Regards, > Pritesh > I came across this 64bit compile problem (with -Werror) as well, but I would fix it differently: Change the signature of remoteSendStreamData() to use unsigned int instead of size_t. This is possible because remoteSendStreamData() is not part of the public API and it's currently called with len set to 0 or with len set to an int value returned by virStreamRecv(). Matthias
diff --git a/daemon/dispatch.c b/daemon/dispatch.c index e9fe260..ae4f60d 100644 --- a/daemon/dispatch.c +++ b/daemon/dispatch.c @@ -589,7 +589,7 @@ int remoteSendStreamData(struct qemud_client *client, struct qemud_client_stream *stream, const char *data, - size_t len) + unsigned int len) { struct qemud_client_message *msg; XDR xdr; diff --git a/daemon/dispatch.h b/daemon/dispatch.h index a5bf474..ed9d89d 100644 --- a/daemon/dispatch.h +++ b/daemon/dispatch.h @@ -75,6 +75,6 @@ int remoteSendStreamData(struct qemud_client *client, struct qemud_client_stream *stream, const char *data, - size_t len); + unsigned int len); #endif /* __LIBVIRTD_DISPATCH_H__ */ | https://www.redhat.com/archives/libvir-list/2009-September/msg00889.html | CC-MAIN-2015-14 | refinedweb | 171 | 57.77 |
cssutils
A Python package to parse and build CSS Cascading Style Sheets.
Actually querying a parsed stylesheet on a given document or element is planned for probably 0.9.7, for now see the example examples/style.py.
example
# -*- coding: utf-8 -*- import cssutils css = u'''/* a comment with umlaut ä */ @namespace html ""; html|a { color:red; }''' sheet = cssutils.parseString(css) for rule in sheet: if rule.type == rule.STYLE_RULE: for property in rule.style: property.value = 'green' property.priority = 'IMPORTANT' rule.style['margin'] = '01.0eM' # or: ('1em', 'important') sheet.encoding = 'ascii' sheet.namespaces['xhtml'] = '' sheet.namespaces['atom'] = '' sheet.add('atom|title {color: #000000 !important}') sheet.add('@import "sheets/import.css";')
results in
@charset "ascii"; @import "sheets/import.css"; /* a comment with umlaut \E4 */ @namespace xhtml ""; @namespace atom ""; xhtml|a { color: green !important; margin: 1em } atom|title { color: #000 !important }
development version (currently alpha)
Release 0.9.6b1 090609. A few non-backwards compatible changes have been made, please see the online docs help to migrate to 0.9.6. See the docs for full details but the main points here:
- 0.9.6b1: cssutils passes all tests now on Jython from version 2.5RC4
- 0.9.4a4: Started review of cssutils with regard to CSS 2.1 rev 1, e.g. all examples from should work now
- 0.9.4a4: New preference option `keepUnkownAtRules = False`
- 0.9.6a4: Fixes for Issue 22 , Issue 23 and Issue 24
- 0.9.6a4: CHANGE FROM 0.9.6a0: xml.dom.DOMExceptions raised do contain infos about the position where the exception occured in e.line, e.col but due to a problem with PyXML the exception raised can be used like this again: msg = str(e)
- 0.9.6a3: Works with Python 2.6.2 which added a backwards incompatible change for the reversed iterator
- 0.9.6a3: Fixed issue #21
- 0.9.6a3: Updated included to version 0.9
- 0.9.6a2: Refactored Profiles including Custom profiles, added cssutils.profile
- 0.9.6a2: Added CSS3_PAGED_MEDIA properties
- 0.9.6a2: p.valid == False is now set for Properties not valid in the current profile even if they are valid in a different profile
- 0.9.6a2: Logging reports have been refactored
- 0.9.6a2: cssutils.resolveImports adds only given href to resulting sheet but not the complete path anymore (security opt)
- 0.9.6a2: IE alpha values are parsed now
- 0.9.6a1: New documentation in Sphinx format for download (for 0.9.6a1) or online, see Links above
- 0.9.6a1: cssutils.resolveImports(sheet) added and csscombine should work with nested imports now too
- 0.9.6a1: Script csscombine has new option -u URL which parses the given URL
- 0.9.6a1: Should work on GAE as is
- 0.9.6a0: SEE 0.9.6a4!!!: xml.dom.DOMExceptions raised do now contain infos about the position where the exception occured. Use e.g. msg, line, col = e.args[0], e.args[1], e.args[2]
- 0.9.6a0: @page rule accepts named pages in addition to pseudo pages :first :left :right now
- 0.9.6a0: Script cssparse has new option -u URL which parses the given URL
- 0.9.6a0: Added optimizations to some values: #112233 => #123, 010.0em => 10em etc
- 0.9.6a0: Most DEPRECATED attributes are finally removed in this release, CSSStyleSheet.replaceUrls is gone in favor of cssutils.replaceUrls(), Property.normalname is gone in favor of Property.name
More info on the pages or downloads referred to on the sitebar.
deprecated version
Release 0.9.5.1 080811. See the README and CHANGELOG for details. Please see MIGRATE for help to migrate to 0.9.5 from lower versions. | http://code.google.com/p/cssutils/ | crawl-002 | refinedweb | 611 | 62.64 |
Dreamcast flashrom read/write support. More...
#include <sys/cdefs.h>
#include <arch/types.h>
Go to the source code of this file.
Dreamcast flashrom read/write support.
This file implements wrappers for the BIOS flashrom syscalls, and some utilities to make it easier to use the flashrom info. Note that because the flash writing can be such a dangerous thing potentially (I haven't deleted my flash to see what happens, but given the info stored here it sounds like a Bad Idea(tm)) the syscalls for the WRITE and DELETE operations are not enabled by default. If you are 100% sure you really want to be writing to the flash and you know what you're doing, then you can edit flashrom.c and re-enable them there..
System configuration structure.
This structure is filled in with the settings set in the BIOS from the flashrom_get_syscfg() function.
Delete data from the flashrom.
This function implements the FLASHROM_DELETE syscall; given a partition offset, that entire partition of the flashrom will be deleted and all data will be reset to 0xFF bytes.
Get a logical block from the specified partition.
This function retrieves the specified block ID from the given partition. The newest version of the data is returned.
Retrieve DreamPassport's ISP configuration.
This function retrieves the console's ISP settings as set by DreamPassport, if they exist. You should check the valid_fields bitfield for the part of the struct you want before relying on the data.
Retrieve PlanetWeb's ISP configuration.
This function retrieves the console's ISP settings as set by PlanetWeb (1.0 and 2.1 have been verified to work), if they exist. You should check the valid_fields bitfield for the part of the struct you want before relying on the data.
Retrieve the console's region code.
This function attempts to find the region of the Dreamcast. It may or may not work on 100% of Dreamcasts, apparently.
Retrieve the current system configuration settings.
Retrieve information about the given partition.
This function implements the FLASHROM_INFO syscall; given a partition ID, return two ints specifying the beginning and the size of the partition (respectively) inside the flashrom.
Read data from the flashrom.
This function implements the FLASHROM_READ syscall; given a flashrom offset, an output buffer, and a count, this reads data from the flashrom.
Write data to the flashrom.
This function implements the FLASHROM_WRITE syscall; given a flashrom offset, an input buffer, and a count, this writes data to the flashrom. | http://cadcdev.sourceforge.net/docs/kos-2.0.0/flashrom_8h.html | CC-MAIN-2018-05 | refinedweb | 415 | 67.76 |
Subject: Re: [OMPI users] multi-compiler builds of OpenMPI (RPM)
From: Jeff Squyres (jsquyres_at_[hidden])
Date: 2008-01-02 16:56:59
On Dec 31, 2007, at 12:50 AM, Jim Kusznir wrote:
> I have some questions, though.
As you can probably tell, the multi-package stuff hasn't been tested
in quite a while. Thanks for taking it for a spin. :-)
> 1) am I correct in that OpenMPI needs to be complied with each
> compiler that will be used with it?
Short answer: yes.
Longer answer: if you only care about the C bindings for MPI, then
compiling Open MPI with any compiler should be fine. The need for
multiple compilations/installations largely stems from Fortran and C++
support (because different compilers use different symbol mangling
techniques). We usually advocate using the same compiler to compile
both Open MPI and the end-user application. E.g., if you have an end-
user MPI application that only works with compiler X, then have an
OMPI installation that was built with compiler X as well.
> I am currently trying to make rpms using the included .spec file
> (contrib/dist/linux/openmpi.spec, IIRC).
> 2) How do I use it to build against different compilers and end up
> with non-colliding namespaces, etc?
Open MPI's configure script takes the standard arguments to override
compilers -- setting environment variables. For example:
./configure CC=icc CXX=icpc ...etc.
It looks like you already noticed that you can pass in arguments to
OMPI's configure script with the "configure_options" default. So you
can pass CC, CXX, etc. via this mechanism, too:
rpmbuild ... --define 'configure_options CC=icc CXX=icpc ...' ...
>.
Little known fact: RPM will allow as multiple installations of a
single package as you want as long as none of the files overlap.
But I agree that differing solely by version number may be a bit
confusing.
You sent me a few more notes about this off-list; I'll take the
liberty of replying on-list so that the discussion is google-able:
> The rpm build errored out near the end with a missing file. It was
> trying to find /opt/openmpi-gcc/1.2.4/opt/share/openmpi-gcc (IIRC),
> but the last part was actually openmpi on disk. I ended up
> correcting it by changing line 182 (configuration logic) to:
>
> %define _datadir /opt/%{name}/%{version}/share/%{name}
>
> (I changed _pkgdatadir to _datadir). Your later directive if
> _pkgdatadir is undefined took care of _pkgdatadir. I must admit, I
> still don't fully understand where rpm was getting the idea to look
> for that file...I tried manually configuring _pkgdatadir to the path
> that existed, but that changed nothing. If I didn't rename the
> package, it all worked fine.
Hmm. This is actually symptomatic of a larger problem -- Open MPI's
configure/build process is apparently not getting the _pkgdatadir
value, probably because there's no way to pass it on the configure
command line (i.e., there's no standard AC --pkgdatadir option).
Instead, the "$datadir/openmpi" location is hard-coded in the Open MPI
code base (in opal/mca/installdirs/config, if you care). As such,
when you re-defined %{_name}, the specfile didn't agree with where
OMPI actually installed the files, resulting in the error you saw.
Yuck.
Well, there are other reasons you can't have multiple OMPI
installations share a single installation tree (e.g., they'll all try
to install their own "mpirun" executable -- per a prior thread, the --
program-prefix/suffix stuff also doesn't work; see
for details). So this isn't making OMPI any worse than it already
is. :-\
So I think the best solution for the moment is to just fix the
specfile's %_pkgdatadir to use the hard-coded name "openmpi" instead
of %{name}.
I committed these changes (and some other small fixes for things I
found while testing the _name and multi-package stuff) to the OMPI SVN
trunk in r17036 (see
17036) -- could you give it a whirl and see if it works for you?
And another from an off-list mail:
> In the preamble for the separate rpm files, the -devel and -docs
> reference openmpi-runtime statically rather than using %{name}-
> runtime, which breaks dependencies if you build under a different
> name as I am.
Doh. I tried replacing the Requires: with %{_name}-runtime, but then
rpmbuild complained:
error: line 300: Dependency tokens must begin with alpha-numeric, '_'
or '/': Requires: %{_name}-runtime
So it looks like Requires: will only take a hard-coded name, not a
variable (I have no comments in the specfile about this issue, but
perhaps that's why Greg/I hard-coded it in the first place...?).
Yuck. :-(
This error occurred with rpmbuild v4.3.3 (the default on RHEL4U4), so
I tried manually upgrading to v4.4.2.2 from rpm.org to see if this
constraint had been relaxed, but I couldn't [easily] get it to build.
I guess it wouldn't be attractive to use something that would only
work with the newest version RPM, anyway.
We'll unfortunately have to do something different, then. :-
( Obvious but icky solutions include:
- remove the Requires statements
- protect the Requires statements to only be used when %{_name} is
"openmpi"
Got any better ideas?
> 3) Will the resulting -runtime .rpms (for the different compiler
> versions) coexist peacefully without any special environment munging
> on the compute nodes, or do I need modules, etc. on all the compute
> nodes as well?
They can co-exist peacefully out on the nodes because you should
choose different --prefix values for each installation (e.g., /opt/
openmpi_gcc3.4.0/ or whatever naming convention you choose to use).
That being said, you should ensure that whatever version of OMPI you
use is consistent across an entire job. E.g., if job X was compiled
with the openmpi-gcc installation, then it should use the openmpi-gcc
installation on all the nodes on which it runs.
The easiest way to do that might be to use the --enable-mpirun-prefix-
by-default option to configure. This will cause OMPI to use mpirun's
--prefix option by default (even if you don't specify it on the mpirun
command line), which will effectively tell the remote node where OMPI
lives on the remote nodes (assuming your installation paths are the
same on all nodes -- e.g., /opt/openmpi-gcc). Then you can use
environment modules (or whatever) on your head node / the job's first
node to select which OMPI installation you want, use mpicc/mpiCC/
mpif77/mpif90 to compile your job, and then mpirun will do the Right
thing to select the appropriate OMPI installation on remote nodes,
meaning that it will set the PATH and LD_LIBRARY_PATH on the remote
node for you.
Make sense?
See:
for a little more detail.
>?
You'll probably want to check the docs for those compilers.
Generally, GCC-like -O options have similar definitions in these
compilers (they try to be similar to GCC). YMMV.
--
Jeff Squyres
Cisco Systems | https://www.open-mpi.org/community/lists/users/2008/01/4775.php | CC-MAIN-2016-07 | refinedweb | 1,174 | 61.77 |
One thing that inevitably makes its way into our QA process on any project is the unexpected appearance of focus rings.
We’ve had a lot of discussions about how to handle these. The project manager and designer often suggest removing them. While that would be the easy solution, it would be a web design anti-pattern. Default focus rings are provided by all browsers so that keyboard users can determine which element is currently in focus. In fact, focus rings are required to meet accessibility standards:
Any keyboard operable user interface has a mode of operation where the keyboard focus indicator is visible.
- W3 Web Content Accessibility Guidelines
Even when we decide not to remove focus rings, designers are usually unhappy with the default styles. One question that came up recently is if focus ring styles are made for keyboard users to keep track of the focus on the page, why do they need to show up when I click on an element? Can we add focus rings for keyboard users only?
The answer is yes! We can use the
:focus-visible polyfill to add focus rings only when a user is navigating with a keyboard.
How to use the
:focus-visible polyfill
Here’s how you can implement the
:focus-visible in your projects right now.
If you are using ES6 modules, install the polyfill via npm:
npm install --save focus-visible
Import the module into your main JavaScript file:
import 'focus-visible';
When your page loads, your
<body> will get a class of
.js-focus-visible so you can conditionally hide default focus rings only if the polyfill is loaded. Additionally, when you are navigating via keyboard, focused elements will get a class of
.focus-visible.
Now we can add our css:
// override UA stylesheet, only when polyfill is loaded .js-focus-visible :focus:not(.focus-visible) { outline-width: 0; } // establish desired focus ring appearance for appropriate input modalities .focus-visible { outline: 2px solid $bright-brand-color; }
Other Resources
:focus-visiblepolyfill on Github
- Focus-ring on A11y Casts
- The CSS Working Group focus-visible pseudo-class spec
Want to dive deeper into building accessible websites? Join my free email course: ? Common accessibility mistakes and how to avoid them. 30 days, 10 lessons, 100% fun! ? Sign up here!
This post originally appeared on benrobertson.io. | https://www.freecodecamp.org/news/focus-rings-for-keyboard-interactions-only/ | CC-MAIN-2020-05 | refinedweb | 387 | 55.54 |
Building microservices, does size matter?
Shayne Boyer
・3 min read
A few months ago I had a chance to sit down and chat with Glenn Condron and Ryan Nowak from the ASP.NET Team about the new things coming in .NET 3.0 for Microservices.
Topics
- 00:22 - What’s the goal with the Microservice templates in .NET Core 3.0?
- 03:05 - What are the new Worker templates?
- 06:57 - What’s happening with gRPC in .NET Core 3?
- 11:47 - How we developers choose between gRPC and Web APIs?
Resources
- Introduction to gRPC on ASP.NET Core
- Download .NET Core 3.0
- .NET Microservices Architecture Guidance
- Comparing gRPC series with HTTP APIs
Does Size Matter for Microservices?
It got me thinking more about microservices in general and how to think of them. Is "micro" the right prefix here? Are they actually small? Probably not.
The term is more around the responsibility, deployment (not the size of), manageability, service boundary, and development team.
Hello World
Not to retract, but what is the minimal realistic service in .NET Core we can write to get simply produce a "Hello World"?
public class Service { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Service>(); }); public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello, world!"); }); }); } }
Here, a host is created with EndpointRouting set to handle the "/" route and return "Hello, world!".
Using
dotnet run you could browse to and see the Hello, world! output to the screen. Not very practical, however, a single responsible service doing the job.
Use the .NET CLI to create a new API template using
dotnet new webapifor a more complete template to build on. See tutorial/docs here.
Focus on the job
Building the service should be more about the desire to create a "small focused" services instead of just a small service.
There is a risk vs reward conversation to be had here. The desire to create as many small services as possible in order to adhere to a mantra of microservices approach will lead to a degree of overhead not worth it.
Not sure about you, but every time I step in that pile it hurts...
Bounded contexts
Depending on where you look, listen, read, etc., Domain-Driven Design may come into the picture on how to put together complexity in large systems and it has many great tools.
One term used in DDD is aggregate to describe a cluster or collection of objects treated as a single unit. So in an application where we are handling customer orders, it would make sense for all of the "CustomerOrder" operations and data to be handled by a single service.
However, it is easy to have other "Customer" or "Order" operations bleed into the service. Finding yourself grouping classes or entities instead of the actual capabilities of the services.
Having the ability to maintain and deploy each service/schema independently is a large benefit, and scaling each service on a need basis lends itself in this architecture as well. However, being network chatty is a side effect. Are you ok with a bunch of calls as long as they are super fast in exchange for ease of deployments, scalability and, maintainability?
How small is small?
Is the team small? 6-8 engineers or a handful seems to be an ideal number depending on the application, but large systems have been built by smaller teams and vice versa.
My code use to be measured by the number of lines?
Size on disk? Disk space is cheap some would say.
Containers are getting smaller every day, until you put an app in it.
What are your thoughts?
GraphQL performance issues & an easy solution
One of the biggest GraphQL flaws is missing of some basic implementations know from REST which are crucial for application performance.
I worked on a team that thought services should be split along the same lines that equivalent classes might be - the single responsibility advice taken to an extreme. The result: ~50% of the code in each service was boilerplate, intra-service issues were much far harder to debug, huge amounts of wasted time/effort/money, upstream SLAs were failing because of JSON serialization time, etc. That was when I learned the phrase distributed monolith.
In their defense, some of that came from leadership directives: "We'll definitely become the Amazon of ___, so..." (They didn't.)
Sometimes it's okay to mash things together. | https://dev.to/dotnet/building-microservices-does-size-matter-2l88 | CC-MAIN-2019-43 | refinedweb | 764 | 67.04 |
Hello geeks and welcome in today’s article, we will cover the Matplotlib draw rectangle. Along with that, for an overall better understanding, we will also look at its syntax and parameter. Then we will see the application of all the theory part through a couple of examples.
So to draw rectangles on matplotlib plot, we use the function matplotlib patches Rectangle. This function helps us in plotting the rectangular patch with a specific width and height. As we move ahead, things will become a lot clearer to us. We will be looking at the syntax associated with this function, followed by parameters.
Contents of Tutorial
Syntax
matplotlib.patches.Rectangle()
This is the general syntax for our function. It has several parameters associated with it, which we will be cover in the next section of this article.
Parameters
1. xy:
This parameter represents the lower left point from which the rectangle plotting will start.
2. width
Through this parameter user specifies the width of the rectangle that he or she wants to create.
3. height
Through this parameter user specifies the height of the rectangle that he or she wants to create.
4. angle
This parameter represents the angle of rotation for the created rectangle.
ExamplesExamples
As we are done with all the theory portion related to the Matplotlib draw rectangle. This section will be looking at how this function works and how it helps us achieve our desired output. We will start with an elementary level example and gradually move our way to more complicated examples.
1. How to draw a rectangle in a plot
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle fig, ax = plt.subplots() ax.plot([1,5,2],[2,3,4],color="cyan") ax.add_patch(Rectangle((2, 2), 1, 3,color="yellow")) plt.xlabel("X-AXIS") plt.ylabel("Y-AXIS") plt.title("PLOT-1") plt.show()
Here we can see the very first example related to matplotlib patches Rectangle. The primary aim of this example was to get aware of the syntax and how it is executed. To do it at first, we have imported the necessary modules. Then we have created a simple plot and changed its color as per my wish. Then to make a rectangle, we have used our functions syntax. Here (2,2) represents the lower-left point from which the rectangle formation will start. Next, we have defined 1 and 3 as their width and height, respectively, for the rectangle. From seeing the output image, it is quite evident that we have executed the program successfully.
2. Draw Matplotlib Rectangle on a scatter plot
import matplotlib.pyplot as plt from matplotlib.patches import Rectangle fig, ax = plt.subplots() ax.scatter([5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6],[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86]) ax.add_patch( Rectangle((5, 82.5), 5, 7.5, fc='none', color ='yellow', linewidth = 5, linestyle="dotted") ) plt.xlabel("X-AXIS") plt.ylabel("Y-AXIS") plt.title("PLOT-2") plt.show()
Above, we can see an example related to the scatter plot. A Scatter plot is seen commonly in statistics. Herewith the help of for function, we have tried to create a boundary between the like points and outliners. Outliners can be understood as points that are a way to apart from the rest of the data. If taken into consideration, they can hurt the calculation for the value of central tendencies.
To do so, first, we have created a scatter plot. After this, we have used our function as the above example. Here we have made specific customization to the function. Like we have used “fc,” which decides whether the rectangle will be color filled or not. Then we have used the “linewidth” and “line style” parameters to customize the rectangle border.
3. Plotting a Matplotlib Rectangle on an Image
import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image import numpy as np x = np.array(Image.open('89.jpg')) plt.imshow(x) fig, ax = plt.subplots(1) ax.imshow(x) rect = patches.Rectangle((500, 1500), 1400, 1300, linewidth=1, edgecolor='r', facecolor="none") ax.add_patch(rect) plt.show()
Here we have successfully created a rectangle on an image. To so, we have used our function and specified all the parameters we need.
4. Drawing a 3D Rectangle
The essential thing to draw 3d rectangle is a set of proper coordinates. Using mpl toolkits, you can then plot a 3d rectangle or parallelepiped using the right sets for vertices. Below you can see the code through which we can create a 3d rectangle
import numpy as np from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import matplotlib.pyplot as plt points = np.array([[-1, -1, -1], [1, -1, -1 ], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1 ], [1, 1, 1], [-1, 1, 1]]) Z = points Z = 10.0*Z fig = plt.figure() ax = fig.add_subplot(111, projection='3d') r = [-1,1] X, Y = np.meshgrid(r, r) ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2]) verts = [[Z[0],Z[1],Z[2],Z[3]], [Z[4],Z[5],Z[6],Z[7]], [Z[0],Z[1],Z[5],Z[4]], [Z[2],Z[3],Z[7],Z[6]], [Z[1],Z[2],Z[6],Z[5]], [Z[4],Z[7],Z[3],Z[0]]] ax.add_collection3d(Poly3DCollection(verts, facecolors='cyan', linewidths=1, edgecolors='r', alpha=.20)) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show()
Also Read: 6 Ways to Plot a Circle in Matplotlib
Conclusion
In this article, we covered the Matplotlib draw rectangle. The function matplotlib patches Rectangle is used to create rectangles in a plot. about ways to convert float to string next.
2 thoughts on “Python Pool: 4 Ways to Draw a Rectangle in Matplotlib”
the information was good
thank you | https://www.coodingdessign.com/python/python-pool-4-ways-to-draw-a-rectangle-in-matplotlib/ | CC-MAIN-2021-10 | refinedweb | 984 | 59.3 |
I wanted to generate RSS 2.0 feeds in Python. Nothing fancy but for certain tasks I needed it something that is quick and just works out of the box. I found rfeed – a library to generate RSS 2.0 feeds in Python. It is in my opinion straightforward to use.
Installation
First clone the repo, run:
$ git clone
Sample outputs:
Cloning into 'rfeed'... remote: Counting objects: 213, done. remote: Total 213 (delta 0), reused 0 (delta 0), pack-reused 213 Receiving objects: 100% (213/213), 40.81 KiB | 0 bytes/s, done. Resolving deltas: 100% (136/136), done. Checking connectivity... done.
The library is a single file rfeed.py, so you could simply copy it wherever you need it. You can also install it using the following command:
$ cd rfeed/
$ python setup.py install
Sample outputs:
running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying rfeed.py -> build/lib.linux-x86_64-2.7 running install_lib copying build/lib.linux-x86_64-2.7/rfeed.py -> /usr/local/lib/python2.7/dist-packages byte-compiling /usr/local/lib/python2.7/dist-packages/rfeed.py to rfeed.pyc running install_egg_info Removing /usr/local/lib/python2.7/dist-packages/rfeed-1.0.0.egg-info Writing /usr/local/lib/python2.7/dist-packages/rfeed-1.0.0.egg-info
Example
Let us create a file named test.py:
$ vi test.py
Append the following text into it:
import datetime
from rfeed import *
# year, month, date, hh, mm, ss
item1 = Item(
title = “My 10 UNIX Command Line Mistakes”,
link = “”,
description = “Here are a few mistakes that I made while working at UNIX/Linux prompt.”,
author = “Vivek Gite”,
guid = Guid(“”),
pubDate = datetime.datetime(2017, 8, 01, 4, 0))item2 = Item(
title = “Top 25 Nginx Web Server Best Security Practices”,
link = “”,
description = “Best Nginx web server hardening and security practice for Linux/Unix sysadmins and developers.”,
author = “Vivek Gite”,
guid = Guid(“”),
pubDate = datetime.datetime(2017, 8, 01, 4, 2))feed = Feed(
title = “nixCraft Updated Tutorials/Posts”,
link = “”,
description = “nixCraft Linux and Unix Sysadmin Blog – Recently updated posts”,
language = “en-US”,
lastBuildDate = datetime.datetime.now(),
items = [item1, item2])print feed.rss()
Where,
- The main object of the RSS 2.0 feed is the Feed class.
- The Feed class supports a list of Item instances.
- To specify the guid attribute of an item, you can use a Guid instance.
- Item: Represents an item of a feed’s channel.
- To get the final RSS content, you can use the rss() method of the Feed class.
Just run it:
$ python test.py
OR
$ python test.py > /var/www/nfs/atom/updated.xml
For more info see rfeed on github. | https://websetnet.net/how-to-generate-rss-2-0-feed-quickly-using-python/ | CC-MAIN-2021-25 | refinedweb | 446 | 62.04 |
CSE143 Section #5 problens In this section we will be learning about linked lists. Each list is composed of individual nodes of type ListNode. The class ListNode has two data fields: one for storing the item of data and the other for storing a reference to the next node. public class ListNode { int da.ta; ListNode next; / / data stored in this node / / link to next node in the list / / post: consLructs a node with data 0 and nul1 link ListNodeO { this (0, null) ; constructs a node with given data and, nurl link ListNode(int data) ( t,his(data, nu11); t data and given rink data, LisENode next) { this.data = data; this.next n€xt; ) in rnr,n.It paq: you'll see-pictures of linked nodes before and after some changes. Write the code that will produce
- Spring '08
- SR
Click to edit the document details | https://www.coursehero.com/file/5656051/Section5Problems-1/ | CC-MAIN-2017-30 | refinedweb | 146 | 73.17 |
WebReference.com - Part 1 of Chapter 3: Professional XML Web Services, from Wrox Press Ltd (4/7)
Professional XML Web Services
Envelope
The
Envelope element, as its name would suggest, serves as a container for the
other elements of the SOAP message. As it is the top element, the
Envelope is the message.
The example below shows the same message we saw earlier, but this time, the
Envelope
element has been highlighted to stress its position in the>
Envelope Namespace
SOAP messages indicate their version by the namespace of the
Envelope
element. The only version recognized by the 1.1 Note is the URI
"". Messages that do not use this namespace are
invalid, and endpoints that receive messages with another namespace must return a "fault". We will
discuss
Fault elements later in this section.
The use of the Envelope namespace to indicate message versions is a good example of how much the SOAP specification relies on XML Namespaces. Without XML Namespaces, it would be extremely difficult to define an open XML format for messages that did not result in name conflicts with the payload XML of the message.
encodingStyle attribute
The specification defines an attribute called
encodingStyle that can be used to
describe how data will be represented in the message. Encoding is the method used to represent data. The
encodingStyle attribute can appear on any element in the message, but in the case of SOAP
encoding, it often appears on the
Envelope element. We will discuss the
encodingStyle attribute and encoding in general in more detail later in the chapter.
Body
The
Body element of a SOAP message is the location for application-specific data. It
contains the payload of the message, carrying the data that represents the purpose of the message.
It could be a remote procedure call, a purchase order, a stylesheet, or any XML that needs to be
exchanged using a message. The
Body element is highlighted in the message below:
>
The
Body element must appear as an immediate child of the
Envelope
element. If there is no
Header element, then the
Body element is the first child;
if a
Header element does appear in the message, then the
Body element immediately
follows it. The payload of the message is represented as child elements of
Body, and is
serialized according to the chosen convention and encoding. Most of this chapter deals with the contents
of the
Body and how to build payloads.
Created: November 12, 2001
Revised: November 12, 2001
URL: | http://www.webreference.com/authoring/languages/xml/webservices/chap3/1/4.html | CC-MAIN-2016-07 | refinedweb | 415 | 51.58 |
updated copyright year
\ image dump 15nov94py \ Copyright (C) 1995,1997,2003,2006,2007,2010,2011. : delete-prefix ( c-addr1 u1 c-addr2 u2 -- c-addr3 u3 ) \ if c-addr2 u2 is a prefix of c-addr1 u1, delete it 2over 2over string-prefix? if nip /string else 2drop endif ; :@ s" GFORTHDESTDIR" getenv delete-prefix save-mem-dict new-addr i 2* cells + 2! LOOP maxalign ; : update-maintask ( -- ) throw-entry main-task udp @ throw-entry next-task - /string move ; : dump-fi ( addr u -- ) w/o bin create-file throw >r update-image-included-files update-image-order update-maintask here forthstart - forthstart 2 cells + ! forthstart begin \ search for start of file ("#! " at a multiple of 8) 8 - dup 3 s" #! " str= until ( imagestart ) here over - r@ write-file throw r> close-file throw ; : savesystem ( "name" -- ) \ gforth name dump-fi ; | http://www.complang.tuwien.ac.at/viewcvs/cgi-bin/viewcvs.cgi/gforth/savesys.fs?view=markup&sortby=rev&sortdir=down&only_with_tag=v0-7-0 | CC-MAIN-2013-20 | refinedweb | 138 | 64.81 |
An Introduction to Assembly Language: Part I
Introduction
Most programmers shy away from Assembler (or assembly language). People tend to consider it as a very difficult language to understand and use. Moreover, anyone who knows how to use it is tended to be regarded with some reverence by other programmers in his community.
This tutorial is the first in a series that will attempt to dismiss these misgivings about Assembler and demonstrate that, in actual fact, it's not difficult to use; quite the contrary. It will demonstrate the tools that greatly simplify the authoring of Assembler, and show you how to integrate these with Visual Studio.
The advantage of using Assembler over other languages is speed. Sheer, raw, unmitigated speed. Even with the modern compiler's ability to optimise code, the code that it produces would have trouble competing with the same written and optimised by hand in Assembler.
Now, Assembler isn't for every job. It is possible to write whole applications in Assembler, but with C++ and the other high languages available today, it'd be masachistic to do so. For the vast majority of applications, the speed of C++ and even the .NET languages is quite acceptible.
Where Assembler comes into its own is when speed is essential; for instance, in graphics applications. For writing small, incredibly fast functions addressing large blocks of memory, Assembler can't be beaten. Bitmap manipulation is a typical example of where a knowledge of how to use Assembler can reap huge rewards.
So, now that I've covered what Assembler is and what its advantages are, how do you use it?
Writing Assembler in Visual C++
The first way that you can write Assembler in C++ is by using __asm blocks:
DWORD Function(DWORD dwValue) { __asm { mov eax, dwValue add eax, 100 mov dwValue, eax } return dwValue; }
Here, you can see a few Assembler instructions enclosed in an __asm block. The C++ compiler will translate these directly into their machine language codes.
Don't worry about what it means. Just know that 'add' is an add instruction and 'mov' is a move instruction that moves values about. The code above just adds 100 to the value passed in.
So, that's it, you might have thought. Well, you'd be wrong. Writing code in __asm blocks is all right for small chunks of Assembler, but if you want to write any functions of length, it starts to become somewhat tedious. For, instance an 'if..else' statement would look something like this:
DWORD Function2(DWORD dwValue1, DWORD dwValue2) { DWORD dwValue3 = 0; #if 0 // this is the Assembler if (dwValue1 == dwValue2) { dwValue3 = 1; } else { dwValue3 = 2; } #endif __asm { mov eax, dwValue1 ; this is the test of the values, i.e. if dwValue1 == dwValue2 cmp eax, dwValue2 ; jump to 'Else' if they are not equal jne Else mov eax, 1 jmp EndIf Else: mov eax, 2 EndIf: mov dwValue3, eax } return dwValue3; }
Again, don't worry too much about the actual instructions, but can you imagine having to do something like this for every if statement?
Using __asm code blocks is like writing C++ using Notepad and the command prompt. Yes, you can do it, but it is a lot more time-consuming than using a dedicated tool for the job.
So, what dedicated tools are there? Well, there's the Microsoft Macro Assembler. Yes, you did hear right. Microsoft has an Assembler. In fact, they've had an Assembler since 1980; it's just that not many people know about it. And what's more, it's freeware. And, even better, it'll produce .obj files that are compatible with the Visual C++ linker. It'll even produce .obj files containing debug information so you can step through your code.
It's called MASM32 and is available at.
I strongly recommend that you download and install it now before proceeding.
So, what's so good about it?
First, it comes with an extensive set of help files available in the \msasm32\help directory.
Second, it has macros defined for just about every single job you might want to do. Not only that, but if you use the macros, you know you'll always be using the most efficient method of performing each task.
For example, look at the preceding code written using MASM:
Function proc dwValue1:DWORD, dwValue2:DWORD mov eax, dwValue1 .if eax == dwValue2 mov eax, 1 .else mov eax, 2 .endif ret Function endp
I think that you'll agree that this is a lot more readable.
So, now that you've downloaded and installed the assembler, I'll take you through a step-by-step guide of adding an Assembler file to an existing C++ project, what to enter into the project settings to compile it, and how to access functions written in Assembler in C++.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c9411/An-Introduction-to-Assembly-Language-Part-I.htm | CC-MAIN-2014-41 | refinedweb | 817 | 64.61 |
WhatWhat
Register your route as natural as Express' way, PLUS adding name/label to it.
Then you can generate URL by calling
urlFor.
ExampleExample
Either:
// In index.jsrouter;router;router;router;
or:
// In index.jsrouter;router;// In path/to/module/user/index.jsuserRouter;userRouter;// In path/to/module/article/index.jsarticleRouter;articleRouter;
You can:
router -> '/users/0'router -> '/users/2/edit'router -> '/articles'router -> '/articles/love-craft'
Sample ProjectSample Project
See route-label-sample for sample integration on express.js.
WhyWhy
Define route in a way you define constants (name => route), because:
- No need to remember the route's URL patterns, just the name to generate URL. Useful for large application with many end points.
- Easy to change URL patterns, just in the "constant" definition.
FeaturesFeatures
- Define route as natural as Express' way.
- Mount submodule routes using
usemethod, and get the whole route names respect the module - submodule structure by namespaces.
- You still can apply middlewares in multiple lines flexibly.
- Get the route table and you can decide what to do with it: pass to front end, finding route name based on pattern, etc.
How to useHow to use
InstallingInstalling
npm install --save route-label
Registering RoutesRegistering Routes
BasicBasic
In the top level express app, wrap the express or express.Router instance with this library:
var app = ;var router = app;
Then you can define any routing with this signature:
router;
name is optional. If provided, this route will be registered in the route table and you can generate its URL using
urlFor.
It may contain alphanumeric, dot, dashes, and underscore.
METHOD is the router's method, such as
get,
put,
all, or
use.
At the end of your outermost route definitions, call:
router;
This will process all registered route above and store it for future URL generation (
urlFor).
You only need to call it once.
Example:
var router = app;routerall'/*' middleware;router;router;router;
Mounting SubmoduleMounting Submodule
If you mount another "submodule" with
use keyword, the given name will become prefix for all routes inside that submodule.
Without giving name, the nested routes inside the submodule won't be registered as named route.
Prefixes will be concatenated with dot ('.') character. It is also possible to have subsubmodule and subsubsubmodule.
Example, in your
/routes/index.js:
var app = ;var router = app;router;
In
/path/to/module/article/index.js:
var appRouter = ; // Use express.Router() instead of express()var router = appRouter;router;router;moduleexports = appRouter; // Return the express.Router() instance
Now you get 'article.list' and 'article.detail' routes defined.
If you provide empty string as names, they will be ignored in the prefix. For example, if you did this:
router;
We get 'list' and 'detail' routes defined, instead of '.list' and '.detail'
Generate URLGenerate URL
.urlFor.urlFor
To generate URL, it is not necessary for route-label to wrap app instance.
var router = ; // No need to wrap `app` here
Then you can call
urlFor with this signature:
Where
paramObj is object containing values to be plugged to the URL, and
queryObj is object which will be serialized as query string.
Example:
/*Consider this route definitions:'article.list' => '/articles''article.detail' => '/articles/:title'*/// Returns /articles/cool-guyrouter;// Returns /articles/cool-guy?mode=showrouter;// Returns /articles/cool-guy?mode=show&tag=man&tag=people&tag=moneyrouter;// Returns /articles?order=ascrouter;// Throw error, missing `title`router;router;
.absoluteUrlFor.absoluteUrlFor
To generate absolute URL, set the
baseUrl with:
router;
This works globally, so you only need to set it once. In the main routing file perhaps?
After that you can call
absoluteUrlFor anywhere.
Example:
router;// Returns
.getRouteTable.getRouteTable
After
buildRouteTable, you can call this anywhere using route-label (with or without wrapping app).
/*Consider this route definitions:'article.list' => '/articles''article.detail' => '/articles/:title'*/router;
Will return:
'article.list': '/articles''article.detail': '/articles/:title'
FAQFAQ
Has anyone used this on production server?
Yes, the birthplace of this library, Cermati, and our other projects using Node.js. We have this on production server running since October 2015.
Why bother creating this library?
We reviewed other libraries for named route, but none of them suites our needs, especially for submodule routing. So we decided to build our own solution. Battle tested in production, we proceed to release this as open source.
How does it work internally?
It wraps Express' routing, attaching name in the routes before calling actual Express' routing function. When
.buildRouteTableis called, the attached names are traversed in pre-order fashion. The result is stored in table and used for future URL generation.
Can it be used as template helper?
You can, if the template engine allow creation of custom helper. For example in Handlebars.js, you can define custom helper which calls
urlFor.
LicenseLicense
MIT | https://www.npmjs.com/package/route-label | CC-MAIN-2022-21 | refinedweb | 781 | 52.15 |
Would it be possible capturing camera on mobile devices (ios and android)?WaterCode Oct 25, 2015 8:07 PM
Sir,
I have no frind and support ,But I have a issue in ios and android ,to need me save the video By
Adobe Flash Profession.I understand We can design code for Andriod and IOS, and compiling ,packaging
in Flash Apps, But my issue is Would it be possible (input) capturing camera on mobile devices and ouput a H.264 files.
I have friend, In this world, Can you Let me know ,I am not alone ,I need to fight for my faith the mobile phone isn't trouble maker....@.
1. Re: Would it be possible capturing camera on mobile devices (ios and android)?kglad Oct 26, 2015 6:18 AM (in response to WaterCode)
you can access data in the media library using the cameraroll class.
2. Re: Would it be possible capturing camera on mobile devices (ios and android)?WaterCode Oct 26, 2015 8:01 PM (in response to WaterCode)
Sir,(kglad.com):I am sorry...
I am not an expert, And I lose my job in this morning,
Could you give me some code suggestions or code hints;
I just know that I should used ActionScript 3.0 or class has a function inside
Is it passible save recording file to the Google map? or Apple map? Because I lose my life map again,
Such accidents should not be happen again.
3. Re: Would it be possible capturing camera on mobile devices (ios and android)?WaterCode Oct 27, 2015 1:53 AM (in response to WaterCode)
Something like this code,, and nothing really happens.@@
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MediaEvent;
import flash.media.CameraRoll;
import flash.media.MediaPromise;
public class main extends Sprite
{
public var imgLoader:Loader;
public var cam:CameraRoll;
public var promise:MediaPromise;
public function main()
{
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
cam = new CameraRoll();
cam.browseForImage();
cam.addEventListener(MediaEvent.SELECT,onSelect);
}
public function onSelect(e:MediaEvent):void{
promise = e.data as MediaPromise
addToStage();
}
public function addToStage():void {
imgLoader = new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,drawBitmap);
imgLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandlerIOErrorEventHandler);
imgLoader.loadFilePromise(promise);
}
protected function errorHandlerIOErrorEventHandler(event:Event):void
{
trace("here");
}
public function drawBitmap(e:Event):void{
var myBitmapData:BitmapData = new BitmapData(200,200);
var image:Bitmap = new Bitmap(myBitmapData);
image.bitmapData = Bitmap(e.currentTarget.content).bitmapData
image.width = image.height = 200
image.x = image.y = 50
addChild(image);
}
}
}
4. Re: Would it be possible capturing camera on mobile devices (ios and android)?kglad Oct 27, 2015 5:25 AM (in response to WaterCode)
is that your document class?
5. Re: Would it be possible capturing camera on mobile devices (ios and android)?WaterCode Oct 27, 2015 7:15 AM (in response to kglad)
Sir ,,
No, It's I google in keyword "cameraroll class",,
The truth is ,I have no idea. Just try to work hard at this issue.
6. Re: Would it be possible capturing camera on mobile devices (ios and android)?kglad Oct 27, 2015 7:55 AM (in response to WaterCode)
if you don't understand the basics of actionscript it's going to be difficult for you to do this.
if main is your document class, that code will (try to) compile. | https://forums.adobe.com/thread/1988829 | CC-MAIN-2018-30 | refinedweb | 578 | 51.34 |
The:
- Creating a SOAP connection
- Creating a SOAP message
- Populating the message
- Sending the message
- Retrieving the reply
SAAJ is available as part of the Java Web Services Developer Pack 1.2 (see Resources). This package also includes a copy of the Tomcat Web server (so you can host your own service) and sample applications.
Setting up the Java Web Services Developer Pack 1.2 is easy -- as long as you send your messages through the included Tomcat Web server. To send messages through a standalone application, as I do here, you need to take the following steps:
- Download the JWSDP 1.2 from.
- Install it according to the directions.
- If you're using Java 1.4, you need to override the XML-related classes provided with it. Create the following directory:
<JAVA_HOME>/jre/lib/endorsed
and copy the files from:
<JWSDP_HOME>/jaxp/lib/endorsed
into it. (
JAVA_HOMEand
JWSDP_HOMErefer to your Java installation and your JWSDP installation, respectively.)
- Add the following files to your classpath:
- <JWSDP_HOME>/saaj/lib/saaj-api.jar
- <JWSDP_HOME>/saaj/lib/saaj-impl.jar
- <JWSDP_HOME>/jwsdp-shared/lib/commons-logging.jar
- <JWSDP_HOME>/jwsdp-shared/lib/mail.jar
- <JWSDP_HOME>/jwsdp-shared/lib/activation.jar
- <JWSDP_HOME>/jaxp/lib/endorsed/dom.jar
- <JWSDP_HOME>/jaxp/lib/endorsed/xercesImpl.jar
- <JWSDP_HOME>/jaxp/lib/endorsed/sax.jar
- <JWSDP_HOME>/jaxp/lib/endorsed/xalan.jar
Now you should be able to send a message from anywhere on your system using a standalone program.
The structure of a SOAP message
I'll start by showing you the structure of the message itself. A basic SOAP message consists of an envelope with two main parts: the header and the body. The application determines how these parts are used, but the overall message must follow a specific XML structure, such as:
Listing 1. A sample SOAP message
Here, the header is empty and the body contains the payload, or the message to be delivered. In this case, it's a message requesting the price of a book.
Notice the structure of the message. The
Envelope contains
the
Header and
Body elements, and
all three are part of the namespace.
The application sends the message using a
SOAPConnection.
Creating the connection and the message
The first step is to create the overall class and the connection:
Listing 2. Create the connection
The application can send SOAP messages directly using a
SOAPConnection, which is now part of the SAAJ package,
or indirectly using a messaging provider, which remains in the JAXM package.
In this case, the application
creates the
SOAPConnection object using a factory.
A factory also creates the message itself:
Listing 3. Creating the message object
First, you create the message itself by using the
MessageFactory.
This message already contains empty versions of the basic parts, such as
the
envelope and
header. The
SOAPPart contains the
envelope, and the
envelope contains the body. Create references to the needed
objects, such as the
SOAPBody.
Next, populate the
SOAPBody:
Listing 4. Populating the body
The body of the SOAP message is just like any other XML element in that
you can add a child element, such as
getPrice.
You can then add the
isbn element and its text node just
as you might with a typical DOM element.
With SAAJ you also have the opportunity to directly create
the
SOAPPart of the message using an external file. For
example, the file
prepped.msg contains the XML structure
in the first listing, and can be called in lieu of building the
document manually:
Listing 5. Creating the message from an external file
The
StreamSource class is typically used as
part of an XSL Transformation, but here you can use it simply to obtain the
FileInputStream. The result is a SOAP message that's ready to send.
With a synchronous message, sending the SOAP message and receiving a reply take place in a single step:
Listing 6. Sending the message
The actual message is sent using the
call() method, which
takes the message itself and a destination as arguments and returns a
second
SOAPMessage as a reply. In earlier versions of
JAXM, the destination had to be an
Endpoint object or a
URLEndpoint,
but now it simply has to be an object.
This example uses the "Book price checker" Web service hosted by XMethods, which
returns the price of the book whose ISBN is listed in the request.
The
call() method blocks until it receives the returned
SOAPMessage.
The returned
SOAPMessage,
reply, is a SOAP message
in the same form as the message sent, and as such can be manipulated just
like any other XML message. SOAP allows you to transform the reply
directly using XSLT:
Listing 7. Reading the response
Create the
Transformer object as you would in any XSLT application.
In this case, you just want to output the content, so there's no stylesheet.
Here, the content itself is the entire SOAP part of the message (as
opposed to the SOAP message itself, which might include attachments). You
could also extract the envelope and body before processing. The result in
this case is simply
System.out, but can be any choice
normally available to a transformation. Transform as usual.
Figure 1. SOAP request and response
This simple application.
- Check out the status of various recommendations related to Web services at the W3C.
- Try SAAJ, available as part of the Java Web Services Developer Pack 1.2.
- Get IBM WebSphere Studio Application Developer, an easy-to-use, integrated development environment for building, testing, and deploying Web services.
- Find more resources on the developerWorks XML and Web Services zones. For a complete list of XML tips to date, check out the tips summary page.
- Find out how you can become an IBM Certified Developer in XML and related technologies.
N Site Dynamics Interactive Communications in Clearwater, Florida, USA, and is the author of four books on Web development, including XML Primer Plus (Sams). He loves to hear from readers and can be reached at nicholas@nicholaschase.com. | http://www.ibm.com/developerworks/xml/library/x-jaxmsoap/ | crawl-002 | refinedweb | 995 | 55.84 |
Understanding Android API levels
Xamarin.Android has several Android API level settings that determine your app's compatibility with multiple versions of Android. This guide explains what these settings mean, how to configure them, and what effect they have on your app at run time.
Quick start
Xamarin.Android exposes three Android API level project settings:
Target Framework – Specifies which framework to use in building your application. This API level is used at compile time by Xamarin.Android.
Minimum Android Version – Specifies the oldest Android version that you want your app to support. This API level is used at run time by Android.
Target Android Version – Specifies the version of Android that your app is intended to run on. This API level is used at run time by Android.
Before you can configure an API level for your project, you must install the SDK platform components for that API level. For more information about downloading and installing Android SDK components, see Android SDK Setup.
Note
Beginning in August 2018, the Google Play Console will require that new apps target API level 26 (Android 8.0) or higher. Existing apps will be required to target API level 26 or higher beginning in November 2018. For more information, see Improving app security and performance on Google Play for years to come. - Nougat):
On the Android Manifest page, set the Minimum Android version to Use Compile using SDK version and set the Target Android version to the same value as the Target Framework version (in the following screenshot, the Target Android Framework is set to Android 7.1 (Nougat)):
If you want to maintain backward compatibility with an earlier version of Android, set Minimum Android version to target to the oldest version of Android that you want your app to support. (Note that API Level 14 is the minimum API level required for Google Play services and Firebase support.) The following example configuration supports Android versions from API Level 14 through API level 25:.
Android versions and API levels
As the Android platform evolves and new Android versions are released, each Android version is assigned a unique integer identifier, called the API Level. Therefore, each Android version corresponds to a single Android API Level. Because users install apps on older as well as the most recent versions of Android, real-world Android apps must be designed to work with multiple Android API levels.
Android versions
Each release of Android goes by multiple names:
- The Android version, such as Android 9.0
- A code (or dessert) name, such as Pie
- A corresponding API level, such as API level 28
An Android code name may correspond to multiple versions and API levels (as seen in the table below), but each Android version corresponds to exactly one API level.
In addition, Xamarin.Android defines build version codes that map to
the currently known Android API levels. The following table can help
you translate between API level, Android version, code name, and
Xamarin.Android build version code (build version codes are defined in
the
Android.OS namespace):
As this table indicates, new Android versions are released frequently – sometimes more than one release per year. As a result, the universe of Android devices that might run your app includes of a wide variety of older and newer Android versions. How can you guarantee that your app will run consistently and reliably on so many different versions of Android? Android's API levels can help you manage this problem.
Android API levels
Each Android device runs at exactly one API level – this API level is guaranteed to be unique per Android platform version. The API level precisely identifies the version of the API set that your app can call into; it identifies the combination of manifest elements, permissions, etc. that you code against as a developer. Android's system of API levels helps Android determine whether an application is compatible with an Android system image prior to installing the application on a device.
When an application is built, it contains the following API level information:
The target API level of Android that the app is built to run on.
The minimum Android API level that an Android device must have to run your app.
These settings are used to ensure that the functionality needed to run the app correctly is available on the Android device at installation time. If not, the app is blocked from running on that device. For example, if the API level of an Android device is lower than the minimum API level that you specify for your app, the Android device will prevent the user from installing your app.
Project API level settings
The following sections explain how to use the SDK Manager to prepare your development environment for the API levels you want to target, followed by detailed explanations of how to configure Target Framework, Minimum Android version, and Target Android version settings in Xamarin.Android.
Android SDK platforms
Before you can select a Target or Minimum API level in Xamarin.Android, you must install the Android SDK platform version that corresponds to that API level. The range of available choices for Target Framework, Minimum Android version, and Target Android version is limited to the range of Android SDK versions that you have installed. You can use the SDK Manager to verify that the required Android SDK versions are installed, and you can use it to add any new API levels that you need for your app. If you are not familiar with how to install API levels, see Android SDK Setup.
Target Framework
The Target Framework (also known as
compileSdkVersion) is the
specific Android framework version (API level) that your app is
compiled for at build time. This setting specifies what APIs your
app expects to use when it runs, but it has no effect on which APIs
are actually available to your app when it is installed. As a result,
changing the Target Framework setting does not change runtime behavior.
The Target Framework identifies which library versions your application
is linked against – this setting determines which APIs you can use in
your app. For example, if you want to use the
NotificationBuilder.SetCategory
method that was introduced in Android 5.0 Lollipop, you must set the
Target Framework to API Level 21 (Lollipop) or later. If you set
your project's Target Framework to an API level such as API Level 19
(KitKat) and try to call the
SetCategory method in your code, you
will get a compile error.
We recommend that you always compile with the latest available Target Framework version. Doing so provides you with helpful warning messages for any deprecated APIs that might be called by your code. Using the latest Target Framework version is especially important when you use the latest support library releases – each library expects your app to be compiled at that support library's minimum API level or greater.
To access the Target Framework setting in Visual Studio, open the project properties in Solution Explorer and select the Application page:
Set the Target Framework by selecting an API level in the drop-down menu under Compile using Android version as shown above.
Minimum Android Version
The Minimum Android version (also known as
minSdkVersion) is the
oldest version of the Android OS (i.e., the lowest API level) that can
install and run your application. By default, an app can only be
installed on devices matching the Target Framework setting or higher;
if the Minimum Android version setting is lower than the Target
Framework setting, your app can also run on earlier versions of
Android. For example, if you set the Target Framework to Android 7.1
(Nougat) and set the Minimum Android version to Android 4.0.3 (Ice
Cream Sandwich), your app can be installed on any platform from API
level 15 to API level 25, inclusive.
Although your app may successfully build and install on this range of platforms, this does not guarantee that it will successfully run on all of these platforms. For example, if your app is installed on Android 5.0 (Lollipop) and your code calls an API that is available only in Android 7.1 (Nougat) and newer, your app will get a runtime error and possibly crash. Therefore, your code must ensure – at runtime – that it calls only those APIs that are supported by the Android device that it is running on. In other words, your code must include explicit runtime checks to ensure that your app uses newer APIs only on devices that are recent enough to support them. Runtime Checks for Android Versions, later in this guide, explains how to add these runtime checks to your code.
To access the Minimum Android version setting in Visual Studio, open the project properties in Solution Explorer and select the Android Manifest page. In the drop-down menu under Minimum Android version you can select the Minimum Android version for your application:
If you select Use Compile using SDK version, the Minimum Android version will be the same as the Target Framework setting.
Target Android Version
The Target Android Version (also known as
targetSdkVersion) is the
API level of the Android device where the app expects to run. Android
uses this setting to determine whether to enable any compatibility
behaviors – this ensures that your app continues to work the way
you expect. Android uses the Target Android version setting of your app
to figure out which behavior changes can be applied to your app without
breaking it (this is how Android provides forward compatibility).
The Target Framework and the Target Android version, while having very similar names, are not the same thing. The Target Framework setting communicates target API level information to Xamarin.Android for use at compile time, while the Target Android version communicates target API level information to Android for use at run time (when the app is installed and running on a device).
To access this setting in Visual Studio, open the project properties in Solution Explorer and select the Android Manifest page. In the drop-down menu under Target Android version you can select the Target Android version for your application:
We recommend that you explicitly set the Target Android version to the latest version of Android that you use to test your app. Ideally, it should be set to the latest Android SDK version – this allows you to use new APIs prior to working through the behavior changes. For most developers, we do not recommend setting the Target Android version to Use Compile using SDK version.
In general, the Target Android Version should be bounded by the Minimum Android Version and the Target Framework. That is:
Minimum Android Version <= Target Android Version <= Target Framework
For more information about SDK levels, see the Android Developer uses-sdk documentation.
Runtime checks for Android versions
As each new version of Android is released, the framework API is updated to provide new or replacement functionality. With few exceptions, API functionality from earlier Android versions is carried forward into newer Android versions without modifications. As a result, if your app runs on a particular Android API level, it will typically be able to run on a later Android API level without modifications. But what if you also want to run your app on earlier versions of Android?
If you select a Minimum Android version that is lower than your
Target Framework setting, some APIs may not be available to your app at
runtime. However, your app can still run on an earlier device, but with
reduced functionality. For each API that is not available on Android
platforms corresponding to your Minimum Android version setting, your
code must explicitly check the value of the
Android.OS.Build.VERSION.SdkInt property to determine the API level
of the platform the app is running on. If the API level is lower than
the Minimum Android version that supports the API you want to call,
then your code has to find a way to function properly without making
this API call.
For example, let's suppose that we want to use the
NotificationBuilder.SetCategory
method to categorize a notification when running on Android 5.0
Lollipop (and later), but we still want our app to run on earlier
versions of Android such as Android 4.1 Jelly Bean (where
SetCategory is not available). Referring to the Android version table
at the beginning of this guide, we see that the build version code for
Android 5.0 Lollipop is
Android.OS.BuildVersionCodes.Lollipop. To
support older versions of Android where
SetCategory is not available,
our code can detect the API level at runtime and conditionally call
SetCategory only when the API level is greater than or equal to the
Lollipop build version code:
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { builder.SetCategory(Notification.CategoryEmail); }
In this example, our app's Target Framework is set to Android 5.0
(API Level 21) and its Minimum Android version is set to Android
4.1 (API Level 16). Because
SetCategory is available in API level
Android.OS.BuildVersionCodes.Lollipop and later, this example code
will call
SetCategory only when it is actually available – it
will not attempt to call
SetCategory when the API level
is 16, 17, 18, 19, or 20. The functionality is reduced on these earlier
Android versions only to the extent that notifications are not sorted properly
(because they are not categorized by type), yet the notifications are
still published to alert the user. Our app still works, but its
functionality is slightly diminished.
In general, the build version check helps your code decide at runtime between doing something the new way versus the old way. For example:
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) { // Do things the Lollipop way } else { // Do things the pre-Lollipop way }
There's no fast and simple rule that explains how to reduce or modify
your app's functionality when it runs on older Android versions that
are lacking one or more APIs. In some cases (such as in the
SetCategory example above), it's sufficient to omit the API
call when it's not available. However, in other cases, you may need to
implement alternate functionality for when
Android.OS.Build.VERSION.SdkInt is detected to be less than the API
level that your app needs to present its optimum experience.
API levels and libraries
When you create a Xamarin.Android library project (such as a class library or a bindings library), you can configure only the Target Framework setting – the Minimum Android version and the Target Android version settings are not available. That is because there is no Android Manifest page:
The Minimum Android version and Target Android version settings are not available because the resulting library is not a stand-alone app – the library could be run on any Android version, depending on the app that it is packaged with. You can specify how the library is to be compiled, but you can't predict which platform API level the library will be run on. With this in mind, the following best practices should be observed when consuming or creating libraries:
When consuming an Android library – If you are consuming an Android library in your application, be sure to set your app's Target Framework setting to an API level that is at least as high as the Target Framework setting of the library.
When creating an Android library – If you are creating an Android library for use by other applications, be sure to set its Target Framework setting to the minimum API level that it needs in order to compile.
These best practices are recommended to help prevent the situation where a library attempts to call an API that is not available at runtime (which can cause the app to crash). If you are a library developer, you should strive to restrict your usage of API calls to a small and well-established subset of the total API surface area. Doing so helps to ensure that your library can be used safely across a wider range of Android versions.
Summary
This guide explained how Android API levels are used to manage app compatibility across different versions of Android. It provided detailed steps for configuring the Xamarin.Android Target Framework, Minimum Android version, and Target Android version project settings. It provided instructions for using the Android SDK Manager to install SDK packages, included examples of how to write code to deal with different API levels at runtime, and explained how to manage API levels when creating or consuming Android libraries. It also provided a comprehensive list that relates API levels to Android version numbers (such as Android 4.4), Android version names (such as Kitkat), and Xamarin.Android build version codes.
Related Links
Feedback | https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/android-api-levels?tabs=windows | CC-MAIN-2019-43 | refinedweb | 2,805 | 50.67 |
Tutorial 1b: Crash Course (without GUI)
The following series of tutorials picks up where the crash course left you, answers more questions and unlocks all advanced options.
Note
We recommend using the GUI only as the very first step. It is designed to be filled in a linear sequence, step by step building up on your inputs. Once you went through all GUI steps, do not go backwards and change things within the GUI. Tuning selected settings or parameters is much easier by editing the created files manually in your text editor.
Setting things up
allesfitter expects a folder with
- data files (e.g. Leonardo.csv)
- settings file (settings.csv)
- parameters file (params.csv)
- stellar parameters file (params_star.csv; optional)
The GUI creates those for you in one go, but you can always amend these yourself in a text editor afterwards. The GUI hides all this from you, so let’s have a look behind the scenes.
Example setup
Open the tutorials/01_crash_course folder. You will see the following (folder and script names are arbitrary):
- a folder allesfit
- data files (e.g. Leonardo.csv)
- settings file (settings.csv)
- parameters file (params.csv)
- stellar parameters file (params_star.csv; optional)
- a file run.py
- a file simulate_data.py (this was just used to simulate data and be ignored)
Data files
The folder allesfit is an example working directory for fitting one simple data set: Leonardo.csv (discovery photometry). Time, flux and flux error are given in a comma-separated .csv file. The file name has to match the telescope name.
settings.csv
Open it, and you will see that its minimal content are the planet letter (“b”) and instrument (“Leonardo”). All of these must match the entries in params.csv and the names of any data .csv, here we only have Leonardo.csv files. To speed up the example, we also set the “fast_fit” option and run on “all” cores. There are dozens of other possible settings to give the user all freedom (see the following tutorials).
params.csv
Open it, and you will see the parameters describing the model. There are dozens of possible parameters to freeze and fit (see the following tutorials).
params_star.csv
This will be introduced in the next tutorials. This file is optional and, if given, contains the stellar parameters to calculate some derived parameters (e.g. the planet radius or equilibrium temperature).
run.py
This file just contains the simple 2-4 lines you need to execute to run any allesfit. For example, using Nested Sampling:
import allesfitter
allesfitter.show_initial_guess('allesfit')
allesfitter.ns_fit('allesfit')
allesfitter.ns_output('allesfit')
Or, if you’re the MCMC kind of person:
import allesfitter
allesfitter.show_initial_guess('allesfit')
allesfitter.mcmc_fit('allesfit')
allesfitter.mcmc_output('allesfit')
Results folder
allesfitter creates the subfolder results, containing log files, result tables, LaTex tables, plots of the inital guess and final fit, corner plots, trace plots (for Nested Sampling), chain plots (for MCMC) and an internal save file. Have a look!
When you’re ready, let’s move onto the next tutorials. | https://www.allesfitter.com/tutorials/tutorial-1b-crash-course-without-gui | CC-MAIN-2020-40 | refinedweb | 503 | 59.4 |
Problem
Write a C++ function to copy an existing string. Do not use built in functions.
Solution
This is a straight forward question and to my surprise I was asked this question in a site interview. If you are not prepared you might stumble on the easy ones. The idea is to allocate memory for the new string then copy characters one by one from source to destination.
Code
Here is the code in C++
#include <iostream> //Function takes input string //and return an output string char* CopyStr(char* input) { int n = 0; //Calculate input string length while (input[n] != '\0') n++; //Allocate memory for new string char* out = new char[n]; //Copy characters from source to destination for (int i = 0; i < n; i++) out[i] = input[i]; return out; } void main() { //Sample input char* input = "How are you"; //Call function char* out = CopyStr(input); //Print output std::cout << out << std::endl; } | http://www.8bitavenue.com/2010/12/copy-string-c/ | CC-MAIN-2017-17 | refinedweb | 153 | 67.38 |
Table of Contents:
NPM utility for building CommonJS module bundles (and optionally making them jenkins-js-modules compatible).
See jenkins-js-modules.
The following diagram illustrates the basic flow (and components used) in the process of building a CommonJS module bundle. It uses a number of popular JavaScript and maven tools (CommonJS/node.js, Browserify, Gulp, frontend-maven-plugin and more).
The responsibilities of the components in the above diagram can be summarized as follows:
requiresyntax synonymous with node.js (for module loading) e.g.
var mathUtil = require('../util/mathUtil');. This allows us to tap into the huge NPM JavaScript ecosystem.
requirecalls (see above) resolve properly to the correct module within the bundle.
jenkins-js-builder does a number of things:
bundletask below). The bundle file is typically placed somewhere on the filesystem that allows a higher level Maven build to pick it up and include it in e.g. a Jenkins plugin HPI file (so it can be loaded by the browser at runtime).
.hbs) and include them in the bundle file (see 2 above).
.cssfile that can be picked up by the top level Maven build and included in the e.g. a Jenkins plugin HPI file. See the
bundletask below.
import- see jenkins-js-modules), making the bundle a lot lighter by allowing it to use a shared instance of the Framework lib Vs it being included in the bundle. This can easily reduce the size of a bundle from e.g. 1Mb to 50Kb or less, as Framework libs are often the most weighty components. See the
bundletask below.
export(see jenkins-js-modules) the bundles "main" CommonJS module (see 2 above) so as to allow other bundles
importit i.e. effectively making the bundle a Framework lib (see 5 above). See the
bundletask below.
npm install --save-dev jenkins-js-builder
This assumes you have node.js v4.0.0 (minimum) installed on your local development environment.
Note this is only required if you intend developing jenkins-js-modules compatible module bundles. Plugins using this should automatically handle all build aspects via maven (see later) i.e. simple building of a plugin should require no machine level setup.
Add a
gulpfile.js (see Gulp) in the same folder as the
package.json. Then use
jenkins-js-builder as follows:
var builder = ;builder;builder;
Notes:
defineTasks" section for details of the available tasks.
bundle" section for details of the
bundlecommand.
defineTasks
jenkins-js-builder makes it possible to easily define a number of tasks. No tasks are turned on by default,
so you can also just define your own tasks. To use the tasks defined in
jenkins-js-builder, simply call
the
defineTasks function:
builder;
See next section.
The following sections describe the available predefined Gulp tasks. The
bundle and
test tasks are
auto-installed as the default tasks.
Run all Jasmine style tests. The default location for tests is the
spec folder. The file names need to match the
pattern "*-spec.js". The default location can be overridden by calling
builder.tests(<new-path>).
See jenkins-js-test for more on testing.
Run the 'bundle' task. See detail on this in the dedicated section titled "Bundling" (below).
Watch module source files (
index.js,
./lib/**/*.js and
./lib/**/*.hbs) for change, auto-running the
bundle task whenever changes are detected.
Note that this task will not be run by default, so you need to specify it explicitly on the gulp command in order to run it e.g.
gulp rebundle
As stated in the "Features" section above, much of the usefulness of
jenkins-js-builder lies in how it
helps with the bundling of the different JavaScript and CSS components:
.cssfile.
hbs) into the JavaScript bundle.
It also helps with jenkins-js-modules compatibility i.e. handling
imports and
exports so as to allow
slimming down of your "app" bundle.
Most of the bundling options are configured on the "Bundle Spec", which is an object returned from
a call to the
bundle function on the
builder:
var bundleSpec = builder;
path-to-main-module: The path to the "main" CommonJS module, from which Browserify will start the bundling process (see Browserify for more details). E.g.
'js/bootstrap3.js'.
bundle-name(Optional): The name of the bundle to be generated. If not specified, the "main" module name will be used.
jenkins-js-builder lets you configure where the generated bundle is output to. There are 3 possible
options for this.
Option 1: Bundle as a jenkins-js-modules "resource", which means it will be placed in the
./src/main/webapp/jsmodulesfolder, from where it can be
imported at runtime. This option should be used in conjunction with
bundleSpec.export()(see below).
bundleSpec;
Option 2: Bundle in a specified directory/folder.
bundleSpec;
Option 3: Bundle as an "adjunct", which means the bundle is put into a package in
./target/generated-adjuncts/. If using this option, make sure the project's
pom.xmlhas the appropriate build
<resource>configuration (see below).
Of course, you can also just use the
bundleSpec.inDiroption (num 2 above) if you'd prefer to handle adjuncts differently i.e. use
bundleSpec.inDirto generate the bundle into a dir that gets picked up by your maven build, placing the bundle in the correct place on the Java classpath.
bundleSpec;
An example of how to configure the build
<resource> in your
pom.xml
file (if using
inAdjunctPackage), allowing the adjunct to be referenced from a Jelly file.
src/main/resourcestarget/generated-adjuncts
Specify a LESS file for pre-processing to CSS:
bundleSpec;
The output location for the generated
.css file depends on the output location chosen for the bundle. See Step 2 above.
Some of the NPM packages used by your "app" bundle will be common Framework libs that, for performance reasons, you do not want bundled in every "app" bundle. Instead, you would prefer all "app" bundles to share an instance of these common Framework libs.
That said, you would generally prefer to code your application's CommonJS modules as normal, using the more
simple/intuitive CommonJS style
require syntax (synch), and forget about performance optimizations until
later (build time). When doing it this way, your CommonJS module code should just
require the NPM packages it
needs and just use them as normal e.g.
var moment = ;;
The above code will work fine as is (without performing any mappings), but the downside is that your app bundle will be more bloated as it will
include the
moment NPM module. To lighten your bundle for the browser (by using a shared instance of the
moment
NPM module), we tell the
builder (via the
bundleSpec) to "map" (transform) all synchronous
require calls for
moment to async
imports of the
momentjs:momentjs2 Framework lib bundle
(see the momentjs framwork lib bundle).
bundleSpec;
Of course your "app" bundle may depend on a number of weighty Framework libs that you would prefer not to
include in your bundle. If so, simply call
withExternalModuleMapping for each.
since: 0.0.34
Externalizing commons Framework libs (see Step 4) is important in terms of producing a JavaScript bundle that can be used in production (is lighter etc), but can make things a bit trickier when it comes to Integration Testing your bundle because your test (and test environment) will now need to accommodate the fact that your bundle no longer contains all the Framework libs it depends on.
For that reason,
jenkins-js-builder supports the
generateNoImportsBundle option, which tells the builder to also generate
a bundle that includes all of it's dependency Framework libs i.e. a bundle which does not apply imports (hence "no_imports").
bundleSpec;
Note that this is an additional bundle i.e. not instead of the "main" bundle (in which "imports" are applied).
With this option set, the "no_imports" bundle is generated into a sub-folder named "no_imports", inside the same folder in which the "main" bundle is generated.
For an example of how to use the
generateNoImportsBundleoption, see the "step-08-zombie-tests" Integration Test sample plugin.
Exporting the "main" module (allowing other bundle modules to
import it) from the bundle is easy:
bundleSpec;
The
builder will use the plugin's
artifactId from the
pom.xml (which becomes the plugin ID), as well as the
bundle name (normalised from the bundle name specified during Step 1) to determine the
export bundle ID for
the module.
For example, if the plugin's
artifactId is "acmeplugin" and the bundle name specified is "acme.js", then the
module would be exported as
acmeplugin:acme. The package associated with the "acme.js" module should also be
"published" to NPM so as to allow "app" bundles that might use it to add a
dev dependency on it (so tests
etc can run).
So how would an "app" bundle in another plugin use this later?
It would need to:
devdependency on the package associated with the "acme.js" module i.e.
npm install --save-dev acme. This allows the next step will work (and tests to run etc).
requireand use the
acmemodule e.g.
var acme = require('acme');.
gulpfile.js, add a
withExternalModuleMappinge.g.
bundleSpec.withExternalModuleMapping('acme', 'acmeplugin:acme');.
See Step 4 above.
since: 0.0.35
This can be done by calling
minify on
jenkins-js-builder:
bundleSpec;
Or, by passing
--minify on the command line. This will result in the minification of all generated bundles.
$ gulp --minify
The default paths depend on whether or not running in a maven project.
For a maven project, the default source and test/spec paths are:
./src/main/jsand
./src/main/less(used primarily by the
rebundletask, watching these folders for source changes)
./src/test/js(used by the
testtask)
Otherwise, they are:
./jsand
./less(used primarily by the
rebundletask, watching these folders for source changes)
./spec(used by the
testtask)
Changing these defaults is done through the
builder instance e.g.:
var builder = ;builder;builder;
You can also specify an array of
src folders e.g.
builder;
A number of
jenkins-js-builder options can be specified on the command line.
--minify
since: 0.0.35
Passing
--minify on the command line will result in the minification of all generated bundles.
$ gulp --minify
--test
since: 0.0.35
Run a single test.
$ gulp --test configeditor
The above example would run test specs matching the
**/configeditor*-spec.js pattern (in the test source directory).
Hooking a Gulp based build into a Maven build involves adding a few Maven
<profile>s to the
Maven project's
pom.xml.
We have extracted these into a sample_extract_pom.xml from which they can be copied.
NOTE: We hope to put these
<profile>definitions into one of the top level Jenkins parent POMs. Once that's done and your project has that parent POM as a parent, then none of this will be required.
With these
<profiles>s installed, Maven will run Gulp as part of the build.
- runs
npm installduring the
initializephase,
- runs
gulp bundleduring the
generate-sourcesphase and
- runs
gulp testduring the
testphase).
You can also execute:
mvn clean -DcleanNode: Cleans out the local node and NPM artifacts and resource (including the
node_modulesfolder). | https://www.npmjs.com/package/jenkins-js-builder | CC-MAIN-2017-34 | refinedweb | 1,854 | 57.67 |
Brand new to Ext JS 4.0 is a class Loader system that makes use of the new dependency system. These two powerful new features allow you to create extensive applications that allow the browser to download digest code as necessary.
Today, we’ll be looking at creating a small application that makes use of this new class Loader system, exercising the dependency management system. Along the way, we’ll discuss various configuration options for the Ext Loader system.
Learn the latest about Ext JS and HTML5/JavaScript for three intensive days with 60+ sessions, 3+ parties and more at SenchaCon 2013. Register today!
Before we begin, we will fast forward into the future and peek at the results. Doing so will allow us to identify classes that we’ll need to extend.
Our simple app will contain two-way binding to a grid Panel and form Panels, respectively called UserGridPanel and UserFormPanel. The UserGridPanel will require the creation of a Model and a Store to support its operations. The UserGridPanel and UserFormPanel will be rendered in and managed by an extension to the Ext JS Window class known as UserEditorWindow. All of these classes will be under a namespace called MyApp.
Before we can begin with code, we’ll have to layout the directory structure. Here’s what the folder, organized by namespace, looks like.
As you can see with the illustration above, we have MyApp split according to namespace groupings or “packages.” In the end, our entire application will have an inter-dependency model that will function like the following illustration.
We’ll begin by filling out the contents of the index.html file, which sits at the root of our application and includes all that we’ll need to bootstrap our application.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""> <html> <head> <title>Ext 4 Loader</title> <link rel="stylesheet" type="text/css" href="js/ext-4.0.1/resources/css/ext-all.css" /> <script type="text/javascript" src="js/ext-4.0.1/ext-debug.js"></script> <script type="text/javascript" src="js/MyApp/app.js"></script> </head> <body> </body> </html>
The index.html file contains the necessary link tag for the CSS file for Ext JS 4. This you’ve seen many times, but the inclusion of the ext-debug.js javascript file is something that might raise an eyebrow, as you’re probably used to including ext-all-debug.js for development and ext-all.js for production.
There are a few choices that Ext JS gives you out of the box, each with their own distinct advantages or disadvantages..
Our index.html file made use of ext-debug.js, which is the bare minimum to get dynamic loading working. Later on, we’ll show you how you can use ext-all versions of the framework, allowing you to get the best of both worlds..
Since the UserGridPanel class requires a Model and data Store, we’ll have to develop those supporting classes first. We’ll begin by creating the Model and Store.
Ext.define('MyApp.models.UserModel', { extend : 'Ext.data.Model', fields : [ 'firstName', 'lastName', 'dob', 'userName' ] });
The above example contains code to extend Ext.data.Model, creating our UserModel class. By virtue of extending the data.Model class, Ext JS will dynamically load it for us and then create the UserModel class after it and the dependencies for data.Model have loaded.
Next, we’ll create the UserStore class, an extension to Ext.data.Store.
Ext.define('MyApp.stores.UserStore', { extend : 'Ext.data.Store', singleton : true, requires : ['MyApp.models.UserModel'], model : 'MyApp.models.UserModel', constructor : function() { this.callParent(arguments); this.loadData([ { firstName : 'Louis', lastName : 'Dobbs', dob : '12/21/34', userName : 'ldobbs' }, { firstName : 'Sam', lastName : 'Hart', dob : '03/23/54', userName : 'shart' }, { firstName : 'Nancy', lastName : 'Garcia', dob : '01/18/24', userName : 'ngarcia' } ]); } });
When creating our singleton UserStore class, we add a new requires key to the UserStore prototype. The requires key is a list that instructs Ext JS to fetch any required classes before our class is instantiated. In this case, we list our UserModel class as a required class.
By virtue of our UserModel class being defined in our store’s model property, Ext JS will load it automatically. It is my opinion that listing the class in the requires key allows your code to be self-documenting, reminding you that the UserModel class is required.
OK. We have our foundation classes created for the views.UserGridPanel, which means we can move on and create the UserGridPanel itself.
Ext.define('MyApp.views.UsersGridPanel', { extend : 'Ext.grid.Panel', alias : 'widget.UsersGridPanel', requires : ['MyApp.stores.UserStore'], initComponent : function() { this.store = MyApp.stores.UserStore; this.columns = this.buildColumns(); this.callParent(); }, buildColumns : function() { return [ { header : 'First Name', dataIndex : 'firstName', width : 70 }, { header : 'Last Name', dataIndex : 'lastName', width : 70 }, { header : 'DOB', dataIndex : 'dob', width : 70 }, { header : 'Login', dataIndex : 'userName', width : 70 } ]; } });
When looking at the above code, keep a keen eye on the requires key. Notice how we added the UserStore as a required class. We just configured a direct dependency relationship between our grid Panel extension and our own data Store extension.
Next, we’ll create the form Panel extension.
Ext.define('MyApp.views.UserFormPanel', { extend : 'Ext.form.Panel', alias : 'widget.UserFormPanel', bodyStyle : 'padding: 10px; background-color: #DCE5F0;' + ' border-left: none;', defaultType : 'textfield', defaults : { anchor : '-10', labelWidth : 70 }, initComponent : function() { this.items = this.buildItems(); this.callParent(); }, buildItems : function() { return [ { fieldLabel : 'First Name', name : 'firstName' }, { fieldLabel : 'Last Name', name : 'lastName' }, { fieldLabel : 'DOB', name : 'dob' }, { fieldLabel : 'User Name', name : 'userName' } ]; } });
Because our UserForm class does not technically require any of the classes we’ve developed thus far, we don’t need to add a requires directive.
We’re almost done. We need to create the UserEditorWindow class and then apps.js, which will launch our application. The code for the UserEditorWindow class is below. The class is pretty lengthy because it contains the code for the grid to form panel binding, so please bear with me on this.
Ext.define('MyApp.views.UserEditorWindow', { extend : 'Ext.Window', requires : ['MyApp.views.UsersGridPanel','MyApp.views.UserFormPanel'], height : 200, width : 550, border : false, layout : { type : 'hbox', align : 'stretch' }, initComponent : function() { this.items = this.buildItems(); this.buttons = this.buildButtons(); this.callParent(); this.on('afterrender', this.onAfterRenderLoadForm, this); }, buildItems : function() { return [ { xtype : 'UsersGridPanel', width : 280, itemId : 'userGrid', listeners : { scope : this, itemclick : this.onGridItemClick } }, { xtype : 'UserFormPanel', itemId : 'userForm', flex : 1 } ]; }, buildButtons : function() { return [ { text : 'Save', scope : this, handler : this.onSaveBtn }, { text : 'New', scope : this, handler : this.onNewBtn } ]; }, onGridItemClick : function(view, record) { var formPanel = this.getComponent('userForm'); formPanel.loadRecord(record) }, onSaveBtn : function() { var gridPanel = this.getComponent('userGrid'), gridStore = gridPanel.getStore(), formPanel = this.getComponent('userForm'), basicForm = formPanel.getForm(), currentRec = basicForm.getRecord(), formData = basicForm.getValues(), storeIndex = gridStore.indexOf(currentRec), key; //loop through the record and set values currentRec.beginEdit(); for (key in formData) { currentRec.set(key, formData[key]); } currentRec.endEdit(); currentRec.commit(); // Add and select if (storeIndex == -1) { gridStore.add(currentRec); gridPanel.getSelectionModel().select(currentRec) } }, onNewBtn : function() { var gridPanel = this.getComponent('userGrid'), formPanel = this.getComponent('userForm'), newModel = Ext.ModelManager.create({}, 'MyApp.models.UserModel'); gridPanel.getSelectionModel().clearSelections(); formPanel.getForm().loadRecord(newModel) }, onAfterRenderLoadForm : function() { this.onNewBtn(); } });
The code for our UserEditorWindow contains a lot of stuff to manage the full binding lifecycle of the UserGridPanel and UserFormPanel classes. In order to instruct Ext JS to load the two classes we created earlier, we have to list them in the requires list.
We’re now ready to tie this all together in the app.js file. To maximize our learning, we’ll be making three passes at this. We’ll begin with the simplest configuration first, and add more as we progress.
Ext.Loader.setPath('MyApp', 'js/MyApp'); Ext.onReady(function() { Ext.create('MyApp.views.UserEditorWindow').show(); });
Initially, our app.js file instructs Ext JS to add a path for the MyApp namespace. We do this via the Ext.loader.setPath call, passing in the namespace as the first argument, and the relative path to the page being loaded.
Next, we call Ext.onReady, passing in an anonymous function, which contains a call to Ext.create. Ext.create is responsible for lazy instantiating classes with Ext JS 4.0. We pass in the String representation of our UserEditorWindow class to be instantiated. Since we don’t need a reference to the instance of our class and want to show it immediately, we chain a show method call.
If we view this in our page (), we see that the UI renders, but it’s pretty slow and we get a warning message inside of FireBug from Ext JS!
Ext JS barks at us because we’re not using the Loader system in the most optimized way. We’ll revisit this issue in a second. However, this is a great learning opportunity that we should capitalize on!
I’ve configured my FireBug instance to display XHR requests inside of the console, which allows me to see all such requests without having to switch to the Net tab. This gives us chance to filter though all of the Ext JS classes loaded, to watch the class dependency system work, as we’ve instructed it to do!
Simply type in “User” in the FireBug console filter and you’ll see how it all comes together.
As we can see, the UserEditorWindow class is first loaded, which requires the UserGridPanel. The UserGridPanel requires the UserStore and UserModel classes. Lastly, the UserFormPanel class is loaded.
I mentioned earlier that Ext JS barked because we’re not using the Loader system in the most optimized way. This is because dependencies identified after Ext.onReady has fired are loaded via synchronous XHR, which is not the most efficient way and is not easy to debug at all.
To remedy this issue, we’ll have to modify app.js to instruct Ext JS to load our classes in a way that is both performant and easier to debug
Ext.Loader.setPath('MyApp', 'js/MyApp'); Ext.require('MyApp.views.UserEditorWindow'); Ext.onReady(function() { Ext.create('MyApp.views.UserEditorWindow').show(); });
To enable faster loading of our classes and afford a better debugging experience, we simply have to add a call to Ext.require above our Ext.onReady, instructing Ext JS to require our UserEditorWindow class. Doing this allows Ext JS to inject script tags to the HEAD of the document, allowing resources to load before Ext.onReady fires.
Visit to see this working. After loading the page, you’ll notice that Ext JS will no longer fire warning messages to the console.
What we’ve done is enable lazy loading of Ext JS framework and our application classes. While this is the best for debugging, the page render times can be very painful for rapid debugging sessions. Why – you ask?
The simple answer is that the number of resources loaded is immense. In our example, Ext JS makes 193 total requests to the web server for JavaScript resources, most of which are cached.
We created six JavaScript files (five classes and app.js). That means that to load the required Ext JS files, the browser had to make 187 requests. This solution is viable but not ideal for many and works best when you’re developing in a local dev environment.
To remedy this issue, we can create a hybrid situation, where we load the entire framework via ext-all-debug and then load our classes dynamically. To do this, we’ll need to modify two files.
First, we’ll need to modify our index.html to include ext-all-debug.js instead of ext-debug.js
<script type="text/javascript" src="js/ext-4.0.1/ext-all-debug.js"></script>
Next, we’ll need to modify app.js to enable Ext Loader.
(function() { Ext.Loader.setConfig({ enabled : true, paths : { MyApp : 'js/MyApp' } }); Ext.require('MyApp.views.UserEditorWindow'); Ext.onReady(function() { Ext.create('MyApp.views.UserEditorWindow').show(); }); })();
We enable Ext Loader by calling Loader.setConfig, passing in an anonymous object, which has its enabled property set to true and our namespace set to path mapping.
By modifying our app.js file, we allowed our application to load and render in just over a second in a local dev environment
And there you have it! We created a simple application allowing us to use the new Ext JS class dependency system as well as Loader. You may download these lab files via.
Great explanation of Ext.Loader tweaks. Thanks a lot, Jay.
Thanks hay, that explains a lot…
Keep up te good work!
Err jay i mean…
Stupid spanish dictionary hehe…
The Ext Loader functionality is indeed very useful. I use it in a larger MVC application. However, there are some caveats. One of which is that you do not only want to load Controllers, Views, Models and Stores, but you also would like to load small components or widgets that can be reused throughout your application. I find it difficult to figure out how to implement that and fit in the overall application architecture.
A second (small) detail is, that if you use controllers and you have a model named UserModel, the controller will create a getter getUserModelModel, likewise a UserStore becomes a getUserStoreStore. Small but annoying detail.
I still am looking forward to learn from a ‘real’ application with multiple controllers (possibly a HMVC structure), reusable widgets and components that can be used in multiple views, a strict separation of concerns between control logic, view logic, query logic (I mean the proxy) and model logic.
So, I am looking forward to your Ext Js 4.0 in Action.
Excellent article!! I’ve yet to really start playing with ExtJS4 but I am so looking forward to it.
You know, that was actually pretty well-written and easy to understand. That class loader system is something I would’ve killed to have had years ago.
thank you, this explains a lot,…..
Echoing what halcwb said about taking this to a larger App context. Why not go the user guide way and call app.launch() – and include controllers… I think examples like these will confuse many users who need to learn Best Practices of building a full blown app. If all they need is a modal window they should just use JQuery or some microjs framework.
Also did you notice it takes 7 seconds to load your page? It’s cause every class is loaded separately in 203 Requests! An SDK builder is required here, or just go the ext-all option, it will be faster.
@DB and @halcwb This article was written with the novice in mind and is over ten pages printed! There was no way I was going to mix MVC in the mix. The purpose was to show how to use Ext.Loader with custom classes. I believe it paves the way for future articles that describe what you’re looking for. That is, if Sencha will have me do it :)
I can see the usefulness of this approach when the number of files is small or when working in a development mode, but does JSBuilder (if Ext’s still using that to build) read these Ext.require() statements to build a single JS bundle for production deployments?
@Trung,
I believe it’s a missing piece to Ext Loader. Something that I’ve talked about since #ExtJS 4.0’s launch.
I know this is a post on the Class Loader, not really Ext application architecture, but how would you go about using an App.js file when you have a multi-page site. That is, you have a /users page and a /products page and each essentially has its own Ext.onReady – obviously you can’t include two calls to Ext.onReady in App.js and it seems hacky to do a conditional check based on the URL to determine what Ext.onReady to fire. Would the recommended best practice solution to treat each page (i.e. each /users and /products) as its own App (i.e. UsersApp.js and ProductsApp.js) which could then be merged into an App.js for performance?
Why do you need to use initComponent to set the items of the form panel? Can’t you just use the items config option?
What about ext-dev.js and ext-all-dev.js that were added in 4.0.2?
Very very good article man, I learned EXT JS 3.0 but now I want to learn the 4 version as soon as possible jajaja
Greatings from Chihuahua
Love this tutorial but wanna see more like this tutorials.
One thing that is missing is how to use the “package” files. That is, using package-grid.js instead of all the files separately that make up the grid. It is the cross between ext-all and individual files. They used to make these files for us in the Ext3 days, but Ext4’s loader is the way to actually do it…
Can the Loader resolve multipart namespaces? Eg, if you specify:
Ext.Loader.setConfig({
paths: ‘top: ‘src/top’
}
Will it be able to load the class ‘top.middle.Bottom’ from ‘src/top/middle/Bottom.js’ ?
I guess I could try, but I’m lazy :p
@bigfish, i think : paths : { ‘myNamespace’ : ‘src/mynamespace’, ‘othernamespace’ : ‘src/othernamespace’ }
>>> I believe it’s a missing piece to Ext Loader. Something that I’ve talked about since #ExtJS 4.0’s launch.
Jay,
Can you explore this some more with your friends at Sencha? When are they planning to add the ability to combine the Ext-loaded files into a single file? This is a must have feature for larger apps.
The Sencha command-line tool in the SDK builds a Jsb and creates a single js file of all the required classes.
I use that when going from dev to deploy.
In object oriented terms the example code is declaring derived class types when instances of the core ExtJS class would be sufficient. Does the class loader mandate this form of OO design?
Great stuff !! Too bad there isn’t more of this .. :-(
Cant wait for Ext4 In Action ;-)
Jay,
First, I greatly appreciate your post. This is the most useful tutorial I have found on any aspect of Ext JS 4 to date. Thank you so much for providing it.
” I believe it paves the way for future articles that describe what you’re looking for. That is, if Sencha will have me do it ” : They’d better!
“@DB and @halcwb This article was written with the novice in mind and is over ten pages printed! There was no way I was going to mix MVC in the mix. The purpose was to show how to use Ext.Loader with custom classes. ”
I completely appreciate your perspective here. However, I feel that ALL that’s been published to date is mini-examples that describe little scenarios. There are literally tons of them in the docs, the guides, the samples, this blog etc. There are so many that describe just one little aspect without a view on the whole. THESE are what are confusing us. Each one is in a silo, configs objects differently (see quote below), introduces concepts never seen elsewhere with little explanation, etc.
“Why do you need to use initComponent to set the items of the form panel? Can’t you just use the items config option?”
Sencha has done a very poor job of introducing us all the Ext JS 4. I for one am quite disappointed. I convinced my management team that Ext was the way to go for our future development needs. Now, I am struggling to complete a complex app because of the lack of a single coherent example more complex than editing a user in a grid via a form.
Sencha needs to step up and provide a well documented single MVC example that incorporates and explains all best practicies.
Another blog could be about:
currentRec.beginEdit();
currentRec.endEdit();
currentRec.commit();
basicForm.updateRecord(currentRec);
It’s hard to find a good explanation about these.
@JustinNoel is on the money, as soon as I step outside of the example and into the real world, shit does not stack up at all :(
The desktop app is nice, the feed viewer app is nice too. Even doing the Google music beta interface () in extjs is fairly straight forward as each one of these things are straight forward due to their single use/purpose.
Real business apps are not single use/purpose, they have all sorts of data that interact all over the place depending on a ton of criteria (our app, attempting to capture who has access to what is convulted as there is more than one thing happening)
I’d like to see an example app that has different data going on, different views depending on different situations, even a standard shopping site with front and back ends is simple/straight forward.
I guess the issue is real world examples are only going to exist in real world contexts and as such are probably not going to be opened up as examples to follow as they actually solve business needs, which are not for general public consumption… This is very much the case with out app. I know exactly how I want to work and which extjs bits to use, I’m just struggling to structure this app so it is not a hodge podge of fail…
@Nicholas Orr @Justin Noel It seems like you guys have grasped the basics of ExtJS but not the basics of JavaScript…. All ExtJS is, is JavaScript….if you are unsure of how to create new Elements or Widgets via JS/ExtJS then maybe you should be looking for more of a JavaScript course.
Creating a large application just adds more widgets and lines of code, this is done by creating objects/methods via JavaScript and calling those via Events/handlers. Sure along with a large application comes much more code to manage and how do you manage that? Well that comes with experience and guidance.
@Donald – I never suggested I was having trouble creating widgets or elements, nor am I a complete noob to JavaScript. Ext JS 4 is a very complex framework, has a completely new MVC structure, etc. That is slightly beyond “looking for more of a JavaScript course”
So, if CakePHP, RoR, or any other framework came out with a complete rewrite and did not provide a working example that covered MOST aspects in a single coherent example, should the confused programmer simply “look for a PHP course” or “look for a Ruby course”?
There is no doubt that much more experienced developers are well on their way to productivity with Ext JS. However, the less experienced (to Ext) are baffled. Look in the forums for people begging for a complete CRUD example, a better MVC example. Should we all be taking “JavaScript for Dummies” instead? Sencha has certainly not provided enough truly useful examples to encourage people to adopt Ext JS.
@Justin Noel Maybe this hasnt been mentioned anywhere but you dont have to follow their MVC pattern…You can still use ExtJS as you would with version 3 or 2……
@Donald except Ext doesn’t come across as vanilla JS… the devs have put a fair amount of thought into how to structure things and with that in mind the came up ExtJS. The bite sized examples work really well as long as you use the example stand alone. I can put together a grid with a json store that when a row is clicked it loads up a form and save the data to and from the server. This is a one pager, single function.
Going from that to an App that has lots of stuff going on needs some sort of structure and this isn’t really clear how best to do this in ExtJS… Maybe I haven’t read enough.
I get that we don’t have to use the MVC deal. It doesn’t really fit what I want to do anyways, same as how the RoR MVC way didn’t fit what I wanted to do either…
@Justin Noel. Thank you for spelling it out. This is exactly the reason why I have trouble to adopt ExtJS for my purposes. My gut feeling tells me that ExtJS is the way to go. I have no trouble incorporating individual pieces, but simply cannot jump that final, but crucial hurdle. One less paying customer (that would be me) for Sencha until I can see a best practice example of a proper ‘real world app’ as Justin described. It doesn’t have to be huge or complicated, but it should contain ALL the parts required to do it and hints regarding how it can be extended.
It very slow.
Is it possible that it is necessary to have a subfolder like
js/
->MyApp/
->views/
->controller/
….
to realize namespaces?
Cause tried something like this
Ext.Loader.setPath(‘incbszdb’, ‘static/js’);
js/
->views/
->controller/
….
and the app said “Namespace not found…”
I don’t quite understand why I would want the loader involved in much of anything. If we are wanting to load our app and then just swap data back and forth – then why not load it all at once?…..if the loader wasn’t so slow….well maybe…..but….damn……it’s……s…..lo…….w……..
I absolutely agree about the need for more MVC examples. I chuckle when I see guys who can’t provide an MVC example belittle someone who is simply asking for an example. I mean…..what’s all the hype about the latest greatest MVC pattern to be used with extjs4 if not even the wizards can provide a working example?
Look at the above link for a full CRUD/mvc example with code that works. It’s basic….and it looks like the guy just finished the unfinished non-working example from the API docs…..but it works……..and it’s rails specific…..for those of us from a rails background.
I’ve been trying to adapt his pattern to a dual-grid example where a child grid loads records based on parent record chosen in parent grid. As soon as I’ve got it working I’ll put in on github and post it back to the forums.
Wish there were more examples out there……..but I guess examples will have to be provided by the community.
Can the Loader System load user css files? If it can, would you please give some sample code?
Thanks and Best Regards!
I complained above about the lack of an MVC CRUD example. I’ve know posted my own example. It might not be any good, but it is at least a starting point.
I’d love feedback on it.
HI,
Its giving weird results when it is integrate ExtJs 4 with share point webpart.How to over come from these problem?
2.How to overide Extjs4 CSS to Sharepoint CSS dynamically? please help
ext.js: is this really a minified version of ext-debug or ext-all?
Hi Jay or anyone that may know,
When I read this post, I feel everything was cristal clear — excellent work. So I decided to use the codes here and try to make it loaded by the EXT demo portal. In other words, I tried to make your ‘UserEditorWindow’ show as a portlet on the EXT JS 4 demo portal.
After I put everything together, and changed the demo portal’s “portlet-3″ to load content as
items: [Ext.create(‘MyApp.views.UserEditorWindow’)],
The portlet bar was shown on the portal, but had no content,
Could you please let me know if this should work with portal as well, and if so, how?
Thanks | http://www.sencha.com/blog/using-ext-loader-for-your-application/ | CC-MAIN-2015-22 | refinedweb | 4,626 | 66.33 |
SOLVED Deleting all handles unexpectedly deletes entire contour
When I option-select all off-curve points in a contour to delete them, it sometimes results in a complete deletion of the contour. Expected result would be a leftover curveless contour.
See screen recording for what I'm talking about
probably a bug… @frederik
here’s another way of converting all curve segments to straight lines, using a pen:
from fontTools.pens.basePen import BasePen class LinePen(BasePen): def __init__(self, otherPen): BasePen.__init__(self, {}) self.otherPen = otherPen self.currentPt = None self.firstPt = None def _moveTo(self, pt): self.otherPen.moveTo(pt) self.currentPt = pt self.firstPt = pt def _lineTo(self, pt): self.otherPen.lineTo(pt) self.currentPt = pt def _curveToOne(self, pt1, pt2, pt3): self.otherPen.lineTo(pt3) self.currentPt = pt3 def _closePath(self): self.lineTo(self.firstPt) self.otherPen.closePath() self.currentPt = None def _endPath(self): self.otherPen.endPath() self.currentPt = None def addComponent(self, glyphName, transformation): self.otherPen.addComponent(glyphName, transformation) # get a glyph with curve segments source = CurrentGlyph() # make a new temp glyph for the result result = RGlyph() # get a pen to draw into the result glyph drawPen = result.getPen() # get a pen to convert curves to lines linePen = LinePen(drawPen) # draw the result using the line pen source.draw(linePen) # replace source contours with result source.clearContours() source.appendGlyph(result)
(there are probably simpler ways to do it :)
hope this helps!
I remember the same behavior. Although, when testing it out just now (Version 3.4b (build 1912091618)), I get this:
Okay, maybe this has to do with the combination of
curveTos and
lineTos:
@gferreira Thanks for the code!
@frankrolf Yeah I think it does. Doesn't always reproduce.
create bug!!
RF decided somehow those contours are really bad... and deleted them for you, its a FEATURE!!
fixed in the next update!!! | https://forum.robofont.com/topic/770/deleting-all-handles-unexpectedly-deletes-entire-contour/6?lang=en-US | CC-MAIN-2022-27 | refinedweb | 306 | 52.76 |
Ok, this is a different program and I can't seem to get this program to work. It's the function that wont work.
Can anyone help me out here?Can anyone help me out here?Code:#include <iostream> using namespace std; int Add(int firstNUM, int secondNUM) { cout <<"Tn the function now!" <<endl; cout <<"The number " <<firstNUM << " and the number " <<secondNUM << " will now be added together" <<endl; cout <<firstNUM <<" + " <<secondNUM <<"is the equation." <<endl; return (firstNUM+secondNUM); } int main() { int firstNUM, secondNUM, sumNUM; cout <<"This is a function program, just checking to see how good I know functions." <<endl; cout <<"Enter a number" <<endl; cin >>firstNUM; cout <<"Enter another number" <<endl; cin >>secondNUM; sumNUM = Add(firstNUM,secondNUM); cout <<Add(); system("pause"); return 0; } | http://cboard.cprogramming.com/cplusplus-programming/43360-another-program-more-problems.html | CC-MAIN-2014-35 | refinedweb | 124 | 65.42 |
Executing following line of code:
conn.Update(CashInItem)
throws an exception:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM (line 465 in Contrib
var updated = connection.Execute(sb.ToString(), entityToUpdate, commandTimeout: commandTimeout, transaction: transaction);)
I am testing Dapper.Contrib.
I have a table in SQL Server that has a few
DateTime columns - some of them allow NULL values.
I created an object with properties to match the columns in the table. For the
DateTime columns, the properties are nullable.
Here is an example of one of the properties:
public DateTime? ReconciledOn { get; set; }
I first use
IDbConnection.Query method to get a record from the SQL table. This runs OK and the object mapping is fine. When I check on of the nullable
DateTime values it shows
null.
I then, make a simple change to string parameter and call the following:
static bool Update(CashIn CashInItem) { using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString)) { return conn.Update(CashInItem); //Error on this line } }
How can I fix this issue?
After cleaning up my code it worked.
At first, I was testing just Dapper and then added Dapper.Contrib. I had references to both. I now believe that the reason was that the object was loaded using Dapper.Query which was then used in Dapper.Contrib Update. After cleaning my code looks like that
static void Main(string[] args) { string dump = ""; using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AchieveDB"].ConnectionString)){ conn.Open(); CashIn oCashIn = conn.Get<CashIn>(59458); dump = ObjectDumper.Dump(oCashIn); Console.WriteLine(dump); Console.WriteLine("Updating"); Console.WriteLine("========="); oCashIn.ReconciledOn = DateTime.Now; dump = ObjectDumper.Dump(oCashIn); Console.WriteLine(dump); conn.Update <CashIn>(oCashIn); }
References:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;
using Dapper.Contrib;
using Dapper.Contrib.Extensions;
using ObjectDumping;
The SQL statements Contrib sent to the database:
For the Get
exec sp_executesql N'select * from CashIn where CashInId = @id',N'@id int',@id=59458
For the Update
exec sp_executesql N'update CashIn set [ -- then all Fields = matching param then list of params and values.
You are using SQL datatype
DateTime to store value in SQL Server. The valid range of values for this datatype is:
January 1, 1753, through December 31, 9999
To represent this column in your code, you are using C# datatype
DateTime. The valid range of values for this datatype is:
The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.
Your C# property is nullable; but that is not a problem.
Problem is, somewhere in your code, you are instantiating the property to
new DateTime() which then holds its default value
01-Jan-0001 12:00:00 AM which ultimately is out of the valid range of SQL datatype and hence the exception.
You have not provided enough code in question; so you have to debug this yourself where this assignment is happening. | https://dapper-tutorial.net/knowledge-base/57702754/updating-datetime-to-database-is-throwing-sqltypeexception---sqldatetime-overflow | CC-MAIN-2020-40 | refinedweb | 519 | 51.44 |
the very least, it should demystify the inner working of this extremely useful test. I’ll limit myself to the context of $2\times 2$ contingency tables. Finally, I must admit that I was pleasantly surprised by the performance of this code!
These first functions compute various expressions needed by the non-central hypergeometric distribution. More specifically, they use log-probabilities to avoid manipulating small numbers that would risk producing an underflow.
function lngamm (z) { // Reference: "Lanczos, C. 'A precision approximation // of the gamma function', J. SIAM Numer. Anal., B, 1, 86-96, 1964." // Translation of Alan Miller's FORTRAN-implementation // See var x = 0; x += 0.1659470187408462e-06 / (z + 7); x += 0.9934937113930748e-05 / (z + 6); x -= 0.1385710331296526 / (z + 5); x += 12.50734324009056 / (z + 4); x -= 176.6150291498386 / (z + 3); x += 771.3234287757674 / (z + 2); x -= 1259.139216722289 / (z + 1); x += 676.5203681218835 / (z); x += 0.9999999999995183; return (Math.log (x) - 5.58106146679532777 - z + (z - 0.5) * Math.log (z + 6.5)); }
function lnfact (n) { if (n <= 1) return (0); return (lngamm (n + 1)); } function lnbico (n, k) { return (lnfact (n) - lnfact (k) - lnfact (n - k)); }
The “lnbico” (ln of the binomial coefficient) function returns the log of the number of combinations for choosing $k$ in $n$:
\binom{n}{k} & = & \frac{n!}{k!(n-k)!}\\
\mbox{lnfact}(n) & = & \ln(n!)\\
\mbox{lnbico}(n,k) & = & \ln\binom{n}{k}\\
& = & \mbox{lnfact}(n) – (\mbox{lnfact}(k) + \mbox{lnfact}(n – k))
\end{eqnarray*}
The probability distribution of the non-central hypergeometric is as follows (with $\omega$ being the odds ratio threshold):
\[
\frac{\binom{m_1}{x} \binom{m_2}{n-x} \omega^x}{
\sum_{y=x_{\min}}^{x_{\max}} \binom{m_1}{y} \binom{m_2}{n – y} \omega^y
}\]
Where,
\[\begin{eqnarray*}
x_{\min} & = & \max(0, n – m_2)\\
x_{\max} & = & \min(n, m_1)
\end{eqnarray*}\]
Notation used in the code for contingency matrix and marginals:
\[\begin{array}{|cc||c}\hline
\bf n_{11} & \bf n_{12} & n \\
\bf n_{21} & \bf n_{22} & \\\hline\hline
m_1 & m_2 & \\
\end{array}\]
For computing the test’s p-value, counts must be rearranged and I’ve used the following notation:
\[\begin{array}{|cc||c}\hline
x & ? & n \\
? & ? & \\\hline\hline
m_1 & m_2 & \\
\end{array}\]
Here, deciding on an $x$ allows to fill the table using the sums. The p-value of Fisher’s exact test is then computed by adding the probabilities for scenarios where $x$ is greater than the observed $n_{11}$. This is stored as “den_sum” and computed by the last “for” loop of the function. Notice that all sums are done using scaled probabilities (- max_l in log-space), this avoids summing over very small numbers and risking an underflow. Since the final p-value is the result of a ratio, the scaling factor cancels itself out in Math.exp (den_sum – sum_l). Finally, “w” is used to pass the odds ratio threshold ($\omega$) required.
function exact_nc (n11, n12, n21, n22, w) { var x = n11; var m1 = n11 + n21; var m2 = n12 + n22; var n = n11 + n12; var x_min = Math.max (0, n - m2); var x_max = Math.min (n, m1); var l = []; for (var y = x_min; y <= x_max; y++) { l[y - x_min] = (lnbico (m1, y) + lnbico (m2, n - y) + y * Math.log (w)); } var max_l = Math.max.apply (Math, l); var sum_l = l.map (function (x) { return Math.exp (x - max_l); }).reduce (function (a, b) { return a + b; }, 0); sum_l = Math.log (sum_l); var den_sum = 0; for (var y = x; y <= x_max; y++) { den_sum += Math.exp (l[y - x_min] - max_l); } den_sum = Math.log (den_sum); return Math.exp (den_sum - sum_l); };
Please be advised that this code has been only very lightly tested. I confirmed that it returns identical results to the R implementation (fisher.exact) on a limited number of non-trivial test cases. If you find any issue, I’d be happy to investigate! | http://bioinfo.iric.ca/a-javascript-implementation-of-the-non-central-version-of-fishers-exact-test/ | CC-MAIN-2017-17 | refinedweb | 637 | 59.6 |
A Crash Course
Let's jump right into it! Let's learn Vue Test Utils (VTU) by building a simple Todo app and writing tests as we go. This guide will cover how to:
- Mount components
- Find elements
- Fill out forms
- Trigger events
Getting Started
We will start off with a simple
TodoApp component with a single todo:
<template> <div></div> </template> <script> export default { name: 'TodoApp', data() { return { todos: [ { id: 1, text: 'Learn Vue.js 3', completed: false } ] } } } </script>
The first test - a todo is rendered
The first test we will write verifies a todo is rendered. Let's see the test first, then discuss each part:
import { mount } from '@vue/test-utils' import TodoApp from './TodoApp.vue' test('renders a todo', () => { const wrapper = mount(TodoApp) const todo = wrapper.get('[data-test="todo"]') expect(todo.text()).toBe('Learn Vue.js 3') })
We start off by importing
mount - this is the main way to render a component in VTU. You declare a test by using the
test function with a short description of the test. The
test and
expect functions are globally available in most test runners (this example uses Jest). If
test and
expect look confusing, the Jest documentation has a more simple example of how to use them and how they work.
Next, we call
mount and pass the component as the first argument - this is something almost every test you write will do. By convention, we assign the result to a variable called
wrapper, since
mount provides a simple "wrapper" around the app with some convenient methods for testing.
Finally, we use another global function common to many tests runner - Jest included -
expect. The idea is we are asserting, or expecting, the actual output to match what we think it should be. In this case, we are finding an element with the selector
data-test="todo" - in the DOM, this will look like
<div data-...</div>. We then call the
text method to get the content, which we expect to be
'Learn Vue.js 3'.
Using
data-testselectors is not required, but it can make your tests less brittle. classes and ids tend to change or move around as an application grows - by using
data-test, it's clear to other developers which elements are used in tests, and should not be changed.
Making the test pass
If we run this test now, it fails with the following error message:
Unable to get [data-test="todo"]. That's because we aren't rendering any todo item, so the
get() call is failing to return a wrapper (remember, VTU wraps all components, and DOM elements, in a "wrapper" with some convenient methods). Let's update
<template> in
TodoApp.vue to render the
todos array:
<template> <div> <div v- {{ todo.text }} </div> </div> </template>
With this change, the test is passing. Congratulations! You wrote your first component test.
Adding a new todo
The next feature we will be adding is for the user to be able to create a new todo. To do so, we need a form with an input for the user to type some text. When the user submits the form, we expect the new todo to be rendered. Let's take a look at the test:
import { mount } from '@vue/test-utils' import TodoApp from './TodoApp.vue' test('creates a todo', () => { const wrapper = mount(TodoApp) expect(wrapper.findAll('[data-test="todo"]')).toHaveLength(1) wrapper.get('[data-test="new-todo"]').setValue('New todo') wrapper.get('[data-test="form"]').trigger('submit') expect(wrapper.findAll('[data-test="todo"]')).toHaveLength(2) })
As usual, we start of by using
mount to render the element. We are also asserting that only 1 todo is rendered - this makes it clear that we are adding an additional todo, as the final line of the test suggests.
To update the
<input>, we use
setValue - this allows us to set the input's value.
After updating the
<input>, we use the
trigger method to simulate the user submitting the form. Finally, we assert the number of todo items has increased from 1 to 2.
If we run this test, it will obviously fail. Let's update
TodoApp.vue to have the
<form> and
<input> elements and make the test pass:
<template> <div> <div v- {{ todo.text }} </div> <form data- <input data- </form> </div> </template> <script> export default { name: 'TodoApp', data() { return { newTodo: '', todos: [ { id: 1, text: 'Learn Vue.js 3', completed: false } ] } }, methods: { createTodo() { this.todos.push({ id: 2, text: this.newTodo, completed: false }) } } } </script>
We are using
v-model to bind to the
<input> and
@submit to listen for the form submission. When the form is submitted,
createTodo is called and inserts a new todo into the
todos array.
While this looks good, running the test shows an error:
expect(received).toHaveLength(expected) Expected length: 2 Received length: 1 Received array: [{"element": <div data-Learn Vue.js 3</div>}]
The number of todos has not increased. The problem is that Jest executes tests in a synchronous manner, ending the test as soon as the final function is called. Vue, however, updates the DOM asynchronously. We need to mark the test
async, and call
await on any methods that might cause the DOM to change.
trigger is one such methods, and so is
setValue - we can simply prepend
await and the test should work as expected:) })
Now the test is finally passing!
Completing a todo
Now that we can create todos, let's give the user the ability to mark a todo item as completed/uncompleted with a checkbox. As previously, let's start with the failing test:
import { mount } from '@vue/test-utils' import TodoApp from './TodoApp.vue' test('completes a todo', async () => { const wrapper = mount(TodoApp) await wrapper.get('[data-test="todo-checkbox"]').setValue(true) expect(wrapper.get('[data-test="todo"]').classes()).toContain('completed') })
This test is similar to the previous two; we find an element and interact with it in same way (we use
setValue again, since we are interacting with a
<input>).
Lastly, we make an assertion. We will be applying a
completed class to completed todos - we can then use this to add some styling to visually indicate the status of a todo.
We can get this test to pass by updating the
<template> to include the
<input type="checkbox"> and a class binding on the todo element:
<template> <div> <div v- {{ todo.text }} <input type="checkbox" v- </div> <form data- <input data- </form> </div> </template>
Congratulations! You wrote your first component tests.
Arrange, Act, Assert
You may have noticed some new lines between the code in each of the tests. Let's look at the second test again, in detail:) })
The test is split into three distinct stages, separated by new lines. The three stages represent the three phases of a test: arrange, act and assert.
In the arrange phase, we are setting up the scenario for the test. A more complex example may require creating a Vuex store, or populating a database.
In the act phase, we act out the scenario, simulating how a user would interact with the component or application.
In the assert phase, we make assertions about how we expect the current state of the component to be.
Almost all test will follow these three phases. You don't need to separate them with new lines like this guide does, but it is good to keep these three phases in mind as you write your tests.
Conclusion
- Use
mount()to render a component.
- Use
get()and
findAll()to query the DOM.
trigger()and
setValue()are helpers to simulate user input.
- Updating the DOM is an async operation, so make sure to use
asyncand
await.
- Testing usually consists of 3 phases; arrange, act and assert. | https://test-utils.vuejs.org/guide/essentials/a-crash-course | CC-MAIN-2022-40 | refinedweb | 1,289 | 63.59 |
.
Read Managing Audio Content in Plone 3.3 here.
(For more resources on Plone, see here.)
Audio enhancements with p4a.ploneaudio
One of the most advanced products to boost the audio features of Plone is p4a.ploneaudio. Like its image sister p4a.ploneimage it doesn't bring a content type on its own, but expands existing ones. As you might have guessed already, the File content type and the folderish ones (Folder, Large Folder, and Collection) are chosen for the enhancement.
To install it, add the following code to the buildout of our instance:
[buildout]
...
[instance]
...
eggs =
${buildout:eggs}
Plone
p4a.ploneaudio
zcml =
p4a.ploneaudio
After running the buildout and restarting the instance, we need to install the product as an add-on product. We find it with the product name Plone4Artists Audio (p4a.ploneaudio).
Enhancing files
Installing the p4a.ploneaudio product enables the enhancement of the File content type of ATContentTypes. Unlike with the image enhancement, not all files are automatically enhanced with additional audio features. p4a.ploneaudio comes with a MIME type filter. If we upload a file with one of the meta types such as audio/MPEG or application/Ogg, the file will automatically be audio enhanced. All other files (such as ZIP files, EXE files, and so on) stay untouched.
Technically speaking, this works via a named adapter.
The first thing we see is the modified default view for audio-enhanced files:
On the right side we see some technical information about the audio file itself. We find the size, the format (MP3 or Ogg), the bitrate, the frequency, and the length of the track there. As with any other content type, we have the title and the description at the top of the content area. For the audio-enhanced content, the description has changed from a simple text field to a rich text field. We find four buttons after the usual CMS bar (the belowcontenttitle slot) containing the author and the modification date of the file. Each of these buttons retrieves the audio file in a different way:
We find a long list of additional information on the audio track below the player and streaming buttons. This information is the metadata stored with the audio file and is gathered during the enhancing process. It can be changed and written back to the file.
Let's take a closer look on the enhancement process.
One important step here is marking the content object with two interfaces:
- One is p4a.subtyper.interfaces.ISubtyped. This interface marks the content as subtyped.
- The other interface is p4a.audio.interfaces.IAudioEnhanced. This interface describes the type of enhancement, which is audio content in this case.
All other views and components available with the enhanced version bind to the p4a.audio.interfaces.IAudioEnhanced interface.
Additionally, p4a.ploneaudio tries to extract as much of the metadata information from the file as possible.
The title is retrieved from the metadata and changed.
Let's see what happens when a file is added in detail:
It is possible to write custom audio enhancers if needed. The enhancers are queried as named adapters by the MIME type on the IAudioDataAccessor interface.
Enhancing containers
With p4a.ploneaudio, we can turn any Plone folder into an audio-enhanced folder by choosing Audio container from the Subtype menu. Two marker interfaces are attached to the container:
p4a.subtyper.interfaces.ISubtyped
p4a.audio.interfaces.IAudioContainerEnhanced
The default view of the container is changed utilizing the IAudioContainerEnhanced interface. The new default view is audio-container.html, which comes with the p4a.ploneaudio product.
In the View option we see one box for each track. For each track, the title and the cover artwork is shown. There is also an embedded Flash player to play each track directly.
There are some other container views that come with the product as follows:
- audio-album.html (album view)
- audiocd-popup.html (pop-up view)
- cd_playlist.xspf
And the default edit view for IAudioContainerEnhaced-marked folders is overridden.
The audio-album.html view presents the audio content of the container in a slightly different way. The single tracks are arranged in a table. Two variants of this view are exposed in the Display menu of the container—Album view and Album view with no track numbers. Both these views are more compact than the default audio container view and have the same layout, except that the second one omits the column with the track numbers. As for the other audio container views, there is a player for each track. Moreover, there are two buttons on the top of the page. One is the commonly used RSS icon
and the other one is the familiar pop-up player button
.
By clicking on the RSS icon, we get to the stream (or podcast of the folder). This may not be too interesting for a standard static Folder, but can be for a Collection where the content changes more dynamically.
The pop-up player for a folder looks and operates slightly differently as the file standalone variant. It contains all tracks that are part of the audio container as a playlist.
Lastly, there is the cd_playlist.xspf view. This view is not exposed via a display or as an action. It provides the audio data as a XSPF stream.
The XML Shareable Playlist Format: XSPF
The XML Shareable Playlist Format (XSPF) is an XML file format for storing playlists of digital audio. The audio can be located locally or online. Last.fm uses XSPF for providing its playlists. An example playlist looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="">
<trackList>
<track>
<location>example.mp3</location>
<creator>Tom</creator>
<album>Thriller</album>
<annotation>A comment</annotation>
</track>
<track>
<location>another.mp3</location>
<creator>Tom</creator>
</track>
</trackList>
</playlist>
There is a list of applications supporting the XSPF format on the XSPF () website. The default XSPF view of p4a.ploneaudio does not include all possible information. It provides the following attributes:
- location: This is the required location (URL) of the song.
- image: The album artwork that may be included with each track.
- annotation: p4a.ploneaudio collects information about the title, artist, album, and year in this field.
It is easy to write a custom implementation of an XSPF view. Look at the available fields at the XSPF home page and the XSPF implementation of p4a.audio. We find the template named cd_playlist.xspf.pt in the p4a.audio.browser module.
p4a.ploneaudio and the Plone catalog
Besides the customized default views and the additional views, p4a.ploneaudio comes with a number of other changes. One very important change is the disclosure of some audio metadata fields to the portal catalog. This allows us to use them in catalog queries in general and smart folders in particular.
The following indexes are added:
- Artist
- Genre
- Track
- Format
The Artist attribute is exposed as metadata information in the catalog. Also, the genre and the artist name are added to the full text index SearchableText.
The values for the genre field are hardcoded. The ID3 tag genre list is used together with the Winamp extensions. They are stored as a vocabulary. The term titles are resolved for Searchable Text, but not for the index and the Collection field.
Accessing audio metadata in Collections
To access catalog information in collections, it needs to be exposed to the collections tool. This can either be done by a product or TTW in the Plone configuration panel. p4a.ploneaudio comes with a modification of the fields:
- Artist (Artist name)
- Genre (Genre)
- Format (MIME Types)
Let's say we want a collection of all our MP3 files. All we have to do is add a MIME Types criterion to our collection and set audio/mpeg as the value:
ATAudio migration
If you have an older Plone site (2.5), you probably have ATAudio installed to deal with audio content.ATAudio has features similar to p4a.ploneaudio. This is not surprising as p4a.ploneaudio was derived from ATAudio. The main difference is that ATAudio provides a content type, while p4a.ploneaudio reuses an existing one. If you want to switch from ATAudio to p4a.ploneaudio for one or the other reason, p4a.ploneaudio comes with a migration routine. One reason for switching might be that ATAudio is not actively developed any more and probably doesn't work with recent versions of Plone. For migrating, you need to call migrate-ataudioconfiglet.html and follow the instructions there.
The migration view is available only if ATAudio is installed. There is a little bit of a catch-22 situation because p4a.ploneaudio doesn't run on Plone 2.5 and ATAudio doesn't run on Plone 3. This means there is no good starting point for the migration. At least, there is a version of ATAudio that does install in Plone 3 in the collective repository:- plone3migration/.
Extracting metadata with AudioDataAccessors
The IAudioDataAccessor interface is used for extracting metadata from binary audio content. If uploading a file, Plone tries to acquire a named adapter for the interface with the MIME type as the key. It has the following layout:
class IAudioDataAccessor(interface.Interface):
"""Audio implementation accessor (ie MP3, ogg, etc).
"""
audio_type = schema.TextLine(title=_(u'Audio Type'),
required=True,
readonly=True)
def load(filename):
"""Load from filename"""
def store(filename):
"""Store to filename"""
The audio_type field contains a human-readable description of the audio type. In the case of MP3, the Unicode string "MPEG-1 Audio Layer 3" is used. The load and store methods are used for reading/writing the metadata from/to the audio file.
The definition for the MP3 adapter looks like this:
<adapter
for="p4a.audio.interfaces.IPossibleAudio"
factory="._audiodata.MP3AudioDataAccessor"
provides="p4a.audio.interfaces.IAudioDataAccessor"
name="audio/mpeg"
/>
The component is registered for the p4a.audio.interfaces.IPossibleAudio interface. All classes marked with this interface are capable of getting converted to an audio-enhanced object. The standard product marks the File content type with this interface. The adapter provides the p4a.audio.interfaces.IAudioDataAccessor interface, which is the marker for the lookup. The name attribute of adapter is the key for the lookup and needs to be set to the MIME type of the audio file that should be processed. Now, the factory does the actual work of loading and storing the metadata from the audio file.
p4a.ploneaudio and FLAC
For the moment, p4a.ploneaudio only supports MP3 and Ogg Vorbis. This is a reasonable choice. Both formats are streamable and were made for good audio quality with small file sizes. We want to add FLAC support. We use mutagen for metadata extraction. Mutagen is an audio metadata extractor written in Python. It is capable of reading and writing many audio metadata formats including:
- FLAC
- M4A
- Monkey's Audio
- MP3
- Musepack
- Ogg Vorbis
- True Audio
- WavPack
- OptimFROG
Let's remember the flow chart of the audio adding process. We recall that we need a metadata extractor for our FLAC MIME type.
First, we need to register a named adapter for this purpose. This is very similar to the MP3 adapter we saw before:
<adapter
for="p4a.audio.interfaces.IPossibleAudio"
factory=".flac._audiodata.FlacAudioDataAccessor"
provides="p4a.audio.interfaces.IAudioDataAccessor"
name="application/x-flac"
/>
The adapter is used for objects implementing the p4a.audio.interfaces.IPossibleAudio interface. The factory does the work of extracting the metadata. The adapter provides the p4a.audio.interfaces.IAudioDataAccessor interface. This is what the adapter is made for and the name is application/x-flac, which is the MIME type of FLAC audio files.
Next, we define the metadata accessor:
from mutagen.flac import Open as openaudio
...
from p4a.audio.ogg._audiodata import _safe
First, we need some third-party imports. For the metadata extraction, we use the FLAC accessor of the mutagen library. _safe is a helper method. It returns the first element if the given parameter is a list or a tuple, or the element itself.
class FlacAudioDataAccessor(object):
"""An AudioDataAccessor for FLAC"""
implements(IAudioDataAccessor)
def __init__(self, context):
self._filecontent = context
The first lines are the boilerplate part. The adapter class implements the interface the adapter provides. In the constructor, we get the context of the adapter and save it in the _filecontent variable of the instance.
@property
def audio_type(self):
return 'FLAC'
@property
def _audio(self):
return IAudio(self._filecontent)
@property
def _audio_data(self):
annotations = IAnnotations(self._filecontent)
return annotations.get(self._audio.ANNO_KEY, None)
The audio_type property is just for information purposes and required by the interface. It is displayed in the audio view. The _audio property is a shortcut for accessing the IAudio adapter for the context. The audio_data property is a shortcut for accessing the metadata annotated to the context.
def load(self, filename):
flacfile = openaudio(filename)
self._audio_data['title'] = _safe(flacfile.get('title', ''))
self._audio_data['artist'] = _safe(flacfile.get('artist', ''))
self._audio_data['album'] = _safe(flacfile.get('album', ''))
self._audio_data['year'] = _safe(flacfile.get('date', ''))
self._audio_data['idtrack'] = _safe(flacfile.
get('tracknumber', ''))
self._audio_data['genre'] = _safe(flacfile.get('genre', ''))
self._audio_data['comment'] = _safe(flacfile.
get('description', ''))
self._audio_data['bit_rate'] = long(flacfile.info.
bits_per_sample)
self._audio_data['length'] = long(flacfile.info.length)
self._audio_data['frequency'] = long(flacfile.info.
sample_rate)
The load method is required by the IAudioDataAccessor interface. It fetches the metadata using the mutagen method from the audio file and stores it as an annotation on the context.
def store(self, filename):
flacfile = openaudio(filename)
flacfile['title'] = self._audio.title or u''
flacfile['artist'] = self._audio.artist or u''
flacfile['album'] = self._audio.album or u''
flacfile['date'] = self._audio.year or u''
flacfile['tracknumber'] = self._audio.idtrack or u''
flacfile.save()
The store method is required by the IAudioDataAccessor interface as well and its purpose is to write the metadata from the context annotation back to the audio file.
We have covered the following in this article series:
-
>> Continue Reading: Using Flowplayer in Plone 3.]
About the Author :
Tom Gross.
Post new comment | https://www.packtpub.com/article/audio-enhancements-p4aploneaudio-plone-33 | CC-MAIN-2014-15 | refinedweb | 2,324 | 50.73 |
A simple scrollbar that can be detached from the container it is scrolling
Vue Detached Scrollbar
This is a simple scrollbar that you can detach from the element that you want to scroll in. It comes with a minimal HTML structure.
Live Demo
Installation
Simply type
npm install --save vue-detached-scrollbar
You'll need Vue.js to run it.
The components, Gallery and ScrollBar communicate with each other via scrollBus.
You'll need to import and register it as data.
import {scrollBus} from 'vue-detached-scrollbar' const app = new Vue({ data: { scrollBus, }, }
Inside the components where you want to use Gallery and Scrollbar, you simply register them as components
import {ScrollBar} from 'vue-detached-scrollbar'; export default { components: { ScrollBar, }, }
You can customize the scrollbar using the css classes .scrollbar, .scrollbar-slider, and .scrollbar-wrapper. .scrollbar refers to the bar itself whereas .scrollbar-slider is the slider in it.
import {Gallery} from 'vue-detached-scrollbar'; export default { components: { Gallery, }, }
You can put whatever content you want to use between the tags
<gallery> <div id="gallery" class="gallery"> <div class="gallery-item" v- <img : </div> </div> </gallery>
It's important to keep the id 'gallery'. The package uses the id to select it.
Due to the nature of the mouse event listener, you should put a onmouseup="document.onmousemove = null" on the main body of the document.
To-do
- Write tests
Development
Want to contribute? I can only work on this project on my free time, so any help is welcome.
Please refer to Contributing.md.
GitHub
Scroll
Vue 2 directive for custom scrollbar that uses native scroll behavior
Vuebar Vue 2 directive for custom scrollbar that uses native scroll behavior. Lightweight, performant, customizable and without dependencies. Used successfully in production on GGather.com. The first Vue 2 custom scrollbar library that | https://vuejsexamples.com/a-simple-scrollbar-that-can-be-detached-from-the-container-it-is-scrolling/ | CC-MAIN-2019-18 | refinedweb | 301 | 57.37 |
- Advertisement
deadlydogMember
Content Count446
Joined
Last visited
Community Reputation170 Neutral
About deadlydog
- RankMember
Can't See Any Smoke Using Dynamic Particle System Framework (DPSF)
deadlydog replied to CoOlDud3's topic in General and Gameplay ProgrammingI have posted a response to your question at.
Recommended particle engine?
deadlydog replied to DvDmanDT's topic in Graphics and GPU ProgrammingCheck out DPSF (Dynamic Particle System Framework). It's free, actively maintained, has great help docs and support, tutorials, and is super easy to integrate into any XNA project. Also, it supports both 2D and 3D particles, and works on Windows, Xbox 360, Windows Phone, and the Zune.
C# [NonSerializable] and Formatters namespace cannot be found [SOLVED]
deadlydog replied to deadlydog's topic in General and Gameplay ProgrammingHmmmm, yes, I tried creating a new test XNA 3.1 Game project, and it compiled and serialized fine. So the problem does seem to be specific to my one project. ....aahhhh, I just figured it out. I didn't notice, but in the compiler warning it says it is for the XBox 360 project. I have the compiler set to mixed mode, so it builds both the Windows and XBox 360 copy of the project, and it is only the XBox 360 copy the rejects the serializable attribute. I'm not sure why they wouldn't define the NonSerialized attribute and Formatters namespace for the XBox 360 assemblies, as I'm sure they could be used to transfer data to XBox Live and whatnot, but that was my problem. If I just do a Windows build then everything works perfectly. Thanks.
C# [NonSerializable] and Formatters namespace cannot be found [SOLVED]
deadlydog posted a topic in General and Gameplay ProgrammingHi there, I'm having 2 problems trying to get serialization working in C#, both of which are compile time errors: 1 - The first problem I'm having is I'm trying to make my C# class serializable. I have put the [Serializable] attribute in front of my public class declarations, and in front of all the classes/enumerations defined within them. If I do this alone, everything compiles fine. However, I store a handle to an XNA graphics device which I do not want serialized, so I have put the [NonSerialized] attribute in front of it, but when I compile it says "The type or namespace name 'NonSerialized' could not be found (are you missing a using directive or an assembly reference?)" and "The type or namespace name 'NonSerializedAttribute' could not be found (are you missing a using directive or an assembly reference?)". I have tried using [NonSerialized], [NonSerialized()], and [NonSerializedAttribute], but they all give me the same error. Here is a sample code snippet: using System; using System.Collections.Generic; using System.Diagnostics; // Used for Conditional Attributes using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using System.IO; using System.Runtime.Serialization; namespace MyNamespace { ... [Serializable] public class MyClass : MyInterface { ... [NonSerialized] private GraphicsDevice mcGraphicsDevice = null; // Handle to the Graphics Device to draw to ... } } I have also included the System.Runtime.Serialization and System.Runtime.Serialization.Formatters.SOAP .dlls in my project, but it does not seem to make any difference. Also, I'm not sure if it makes a difference or not, but I'm compiling this project into a .dll, not an executable. 2 - My second problem is that when I try to test out serializing and deserializing, the compiler complains that it cannot find the System.Runtime.Serialization.Formatters namespace, it just gives me the error "The type or namespace name 'Formatters' does not exist in the namespace 'System.Runtime.Serialization' (are you missing an assembly reference?)". I get this error whether I try and include System.Runtime.Serialization.Formatters.SOAP or .Binary in the using statements at the top of the file, or if I declare the full namespace path when declaring my variables. Again, I have included the System.Runtime.Serialization and System.Runtime.Serialization.Formatters.SOAP .dlls in my project but it doesn't seems to make a difference. Here's a sample code snippet of this problem: DPSF; using DPSF.ParticleSystems; using System.IO; using System.Runtime.Serialization; //using System.Runtime.Serialization.Formatters; //using System.Runtime.Serialization.Formatters.Binary; //using System.Runtime.Serialization.Formatters.Soap; namespace TestNamespace { public class Game1 : Microsoft.Xna.Framework.Game { ... protected override void Initialize() { // TODO: Add your initialization logic here mcParticleSystem = new DefaultPointSpriteParticleSystemTemplate(null); mcParticleSystem.AutoInitialize(this.GraphicsDevice, this.Content); base.Initialize(); Stream stream = File.Open("ExplosionFlash.dat", FileMode.Create); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bformatter.Serialize(stream, mcParticleSystem); stream.Close(); mcParticleSystem = null; stream = File.Open("ExplosionFlash.dat", FileMode.Open); bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); mcParticleSystem = (DefaultPointSpriteParticleSystemTemplate)bformatter.Deserialize(stream); stream.Close(); } } } Any help or suggestions would be greatly appreciated. Thanks in advance. [Edited by - deadlydog on March 7, 2010 3:32:53 PM]
[.net] Particle Systems in C#. (Optimizations)
deadlydog replied to Jmelgaard's topic in General and Gameplay ProgrammingI know this topic is pretty old, but if you're looking for a particle system framework to use instead of creating your own, check out DPSF (Dynamic Particle System Framework) at. It's for creating particle systems in C# and XNA.
XNA Redistribution / Packaging
deadlydog replied to Andy474's topic in Graphics and GPU ProgrammingIf you want to put the game on your laptop (not the source code), then you can package your game into a self-installing package that will also install the XNA redistributables if required. To do this, from Visual Studio go into the Build menu and select Publish [application name]. This will create a folder, an .applicationdata file, and a .exe file in the destination you specify. Just zip those up, copy them to your laptop, and then run the .exe file and it will install your game for you. Not sure about your question 2. I haven't heard anything before about being able to run XNA apps on the web. You might have more luck posting your XNA questions on the XNA Creators Club Forums.
Allocating particles in memory at run-time not slow?
deadlydog replied to deadlydog's topic in General and Gameplay ProgrammingQuote:Original post by Adam_42 Quote:So as the particle system simulation runs you can notice that particles suddenly jump to the front of the array and are drawn on top of other particles. The standard way of making particles look right regardless of rendering order is to use additive blending instead of standard alpha blending. How well this works depends on what the particles look like. It's best for bright particles on a dark background. If you don't do that you probably need to depth sort, because when the camera moves round the particle system it will usually make the draw order look wrong. Yeah, I'm designing a general purpose particle system framework so I would like it to be able to display both alpha-blended and non-alpha-blended particles correctly. Turning on depth sorting (i.e. RenderState.DepthBufferWriteEnable = true) fixes the problem for opaque particles, but introduces a new problem for semi-transparent ones; the world is shown through the transparent part of the particles, instead of showing the other particles behind it. See a screenshot of the problem here. And this is what it should look like (depth sorting disabled) (still has original problem of particles being suddenly drawn overtop of other particles though). I don't think this problem is related to my issue of the particles being moved around in the array and hence being drawn in a different order (since we have depth sorting enabled here), but I'm not sure what is going on. I'm hoping it's something simple like an additional renderstate property needs to be set or something. If anybody has any ideas why this is happening or how to fix it I would appreciate any suggestions. Thanks Original post by Antheus Quote: Quote: Original post by deadlydog Can anyone think of a simple solution to this problem? For rendering optimizations, read this. Thanks for the tips. nice article. [Edited by - deadlydog on May 7, 2009 10:28:29 AM]
Allocating particles in memory at run-time not slow?
deadlydog replied to deadlydog's topic in General and Gameplay ProgrammingQuote:Original post by deadlydog But now that I've implemented method 4 it seems to be the all around winner, winning with both static and random lifetimes for all active particle amounts almost every time. Number 4 is definitely wins when it comes to performance, but after actually implementing it in a real particle system I've realized one thing that I overlooked with this approach. When a particle dies it gets moved to the end of the list and the position in the array where that particle was gets replaced with the last active particle in the list, and the total number of Active particles is decremented. When the particles are copied into the vertex buffer, I loop over all of the active particles, starting from the end of the Active Particles section of the array to the start of the array (newest particles are drawn first so that older particles are drawn over top of them). Also, most particle systems have the RenderState.DepthWriteEnabled set to false to avoid sorting thousands of particles by depth, saving on execution time and increasing performance. The problem is that since depth sorting is not enabled, the particles are drawn in the order that they appear in the vertex buffer. So when a particle dies it's position in the array is replaced by the newest particle added to the particle system (since new particles are added to the end of the Active particles list). When this happens that new particle which used to be behind most of the other particles is suddenly drawn on top of all of the particles, since its position in the array moved from the end to (possibly) near the start of the array. So as the particle system simulation runs you can notice that particles suddenly jump to the front of the array and are drawn on top of other particles. Can anyone think of a simple solution to this problem? One approach would be to resort the active particles based on age after each update. However this would kill performance and I would be better off just using approach number 8, which gave the 2nd best average performance. Any ideas on how to solve this problem easily would be appreciated. If I can't find any I will likely end up sticking with approach number 8. Thanks.
Allocating particles in memory at run-time not slow?
deadlydog replied to deadlydog's topic in General and Gameplay ProgrammingQuote:Original post by KulSeran Have an array of MAX particles. When you need a particle grab par_array[count]. Increment count. When a particle dies decrement count, swap the particle with par_array[count]. Update only count particles. Yup, I actually just implemented this method last night and it seems to give the best performance all around on average, for both static and random lifetimes. In total I implemented 8 different methods. 1 - Active Linked List with no pre-allocated memory. Just add particles to the linked list when they are needed, and delete them when they die. 2 - Array with linear search for inactive particles. Process entire array. 3 - Array with circular search for inactive particles. Process entire array. 4 - Array with swapping dead particles to the end of the active particles (method mentioned by KulSeran). Process only active particles. 5 - Array with an inactive queue to hold the inactive particle indexes. Process entire array. 6 - Array with an inactive queue and active list. Process only active particles. 7 - active LinkedList and inactive LinkedList holding the particle instances (no array, but memory is still pre-allocated since the linked list nodes are never "deleted", they are just moved back and forth between the linked lists). Process only active particles. 8 - Array with an active LinkedList and inactive LinkedList, where the linked lists hold pointers to the particles in the array. Process only active particles. Before implementing method 4 last night, method 8 performed best with static lifetimes (but not very well with random lifetimes), method 1 with random lifetimes, and method 5 for both static and random lifetimes (but only when the number of active particles = the number of particles allocated in memory). Approach 1 was the best happy medium, however, like it was mentioned since my program isn't allocating / deallocating memory for other application resources at run-time, as would happen in a real application, this methods memory was staying sequential, where in a real application it would likely become fragmented and not perform as well. But now that I've implemented method 4 it seems to be the all around winner, winning with both static and random lifetimes for all active particle amounts almost every time. Quote:Original post by raigan I might be really confused, but in C# don't structs become read-only when you store them in an array/list? For instance the following code doesn't actually do anything to the ith particle: particles.x = 20; The value of particles.x will remain unchanged, because indexing into a list of structs returns the value and not a reference to the object that's in the list. Yup, you're right; which is why I use a Particle class, not a struct. If you used a struct you would need to do something like: Particle sTempParticleStruct = particles; // Copy values into a new struct sTempParticleStruct.x = 20; // Update values particles = sTempParticleStruct; // Replace old particle with updated one
Allocating particles in memory at run-time not slow?
deadlydog replied to deadlydog's topic in General and Gameplay ProgrammingQuote:Original post by Antheus The reason for your results sounds like you're using classes, in which case there would be no difference Yes, my Particle objects are classes, not structs
Allocating particles in memory at run-time not slow?
deadlydog posted a topic in General and Gameplay ProgrammingI'm doing some performance tests on different particle system memory management techniques in C#. I've created a particle simulation (no rendering though) to see how many times each different approach is able to update all of the particles. Three of the approaches I'm using are: 1 - Use a linked list to hold the active particles. When a new particle is required I create a new instance of the Particle class (allocates memory at run-time) and add it to the linked list. When a particle dies remove the particle from the linked list (de-allocated from memory). To update the active particles just update all of the particles in the linked list. 2 - Create a pool of particles in memory using an array of Particle instances and store the inactive particle indexes in an inactive queue. When a new particle is needed grab the next index from the inactive queue, and when it dies return it to the inactive queue. When updating particles loop through the entire particle pool array and update the active particles. 3 - Create a pool of particles in memory using an array of Particle instances and use both an inactive queue and active particle list. When a new particle is needed grab the next index from the inactive queue and add it to the active list, and when it dies remove it from the active list and return it to the inactive queue. To update the active particles just update all of the particles in the active particle list. I test the approaches both with static particle lifetimes (all particles have the same lifetime) and with random lifetimes. I do two tests, the first where 10,000 particles are allocated in memory (for approach 2 and 3) and I test with 10, 100, 1000, 5000, and 10000 active particles. For the second test I allocate 100,000 particles in memory, and test with 10, 100, 1000, 5000, 10000, 50000, and 100000 active particles. Also, I run these tests 5 times and then take the average of the results. I implemented approach #1 just as a simple baseline for comparison (100%). I thought it would be the slowest since it allocates and de-allocates memory at run-time, which I've always heard is expensive and a no-no in particle systems. However, it turns out that this approach gives the best results in the average case (static and random lifetimes, and when some particles are active, and many particles are active). Approach #2, which seems to be the most popular from the particle systems I've downloaded, gives the best performance (~150%) when all of the allocated particles are active, but gives the worst performance when less than half of the particles are active (10% - 50%). Approach #3, which I thought would be the fastest, gives about 90% - 100% performance on average using static particle lifetimes, but around 60% - 70% using random particle lifetimes. So if you know how many particles your effect will require (and allocate only that much memory), and that number remains constant through out the entire effect (which is not always the case), then approach #2 is the best. However, approach #1 seems to give the best performance in the average case. I tested this with a small Particle class (6 floats and 5 ints) and with a large particle class (36 floats and 5 ints), but it did not make much of a difference. So is there something I am missing here? How come approach #1 isn't horribly slow like most people say it should be? My only guess is that it's because I'm using C# and it must be handling the memory management like a champ hehe. Any thoughts?
What is a casual game
deadlydog replied to roychr's topic in Game Design and TheoryTo me a casual game should be one that players don't have to commit to for long periods of time. Players should be able to pick it up and play for only 5 or 10 minutes if they want, and have their progress saved. So if your game requires users to play for half an hour or an hour before reaching the next "save" point, I wouldn't consider it a casual game.
GDI + XNA
deadlydog replied to Sambori's topic in Graphics and GPU ProgrammingDo you just want to draw text to the screen, or are you trying to draw text onto a texture wrapped around a 3D object? If you are just trying to draw text to the screen it is pretty easy in XNA,and there are lots of tutorials. Basically you will create a new SpriteFont and draw it using a SpriteBatch. Here is the MSDN tutorial of how to do it.
calculating Framesper seconds
deadlydog replied to tnutty's topic in For Beginners's ForumIf you want you can use fraps to display the frames per second of your game. Just open up fraps and then run your game and it will display the FPS in your game screen.
Order of frame progression in animation
deadlydog replied to Mybowlcut's topic in General and Gameplay ProgrammingWhy choose; Why not offer both of them. Just have a boolean/enumeration indicating what should happen when the last frame is reached (i.e. wrap, reverse, etc.). The more flexible your classes are the better in my opinion. I like your second suggestion as well. I can't believe I never thought to include that in my animation class :)
- Advertisement | https://www.gamedev.net/profile/29587-deadlydog/ | CC-MAIN-2018-43 | refinedweb | 3,280 | 54.12 |
Usually when a method returns a collection and the method has no result to return, we have two options:
Return null: This results in breakage of client code if it doesn't check for that null.
public List<Order> getOrders() { //.. } . . List<Order> orders = getOrders(); for(Order order : orders) { //NullPointerException here if getOrders returned null! System.out.println(order); }
So the client will be forced to write:
if(orders != null) { //guard for(Order order : orders) { //NullPointerException here if getOrders returned null! System.out.println(order); } }
Return an empty list: Client code will not break and no need to introduce a guard! Much cleaner code! So the below code will suffice:
List<Order> orders = getOrders(); for(Order order : orders) { System.out.println(order); }
EDIT :
Best way to return an empty list is to return one that is immutable by returning
Collections.emptyList() from the concerned function.
Note: The above example dealt with lists but you can extend this discussion to anything that is a Collection/Iterables.
Returning null for that method is deceiving and perhaps equivalent to breaking a promise. By looking at the method signature, calling code assumes that it is going to return List<Order> but when it encounters null, it wasn't really prepared to handle that. If a method is supposed to return null as things may go wrong, the signature should be Option<List<Order>> instead. Same goes true for exception(and for any side effects). Instead of throwing an exception and altering control flow, it should be wrapped in an error so calling application can decide how best to handle the situation. The return type in that case would be Either<Error, List<Order>>. With this signature, possibility of returning an error is explicit and visible to clients of this code.
@bool2 In cases involving exceptions, advertising that the method raises an exception (checked exception) would be better design. That way the client code can keep the error handling code separate (in a catch block) instead of having to unwrap/parse from <Error, List<Order>>.
@soumyadeep2007 Checked exceptions are certainly more expressive and explicit than the code block arbitrarily throwing unhandled exceptions. The point of wrapping value into a context(Monad) is to later use it with combinators without unwrapping it. For instance your example above can be written as
orders.map(order -> System,out.printn(order)).
It works whether the list is null or not. The value needs to be unwrapped when code wants to transform to a different value when value is different.
@soumyadeep2007 said in Don't return null for functions returning collections/iterables:
Best way to return an empty list is to return one that is immutable by returning
Collections.emptyList()from the concerned function.
How would you use that to make for example this function better?
private static List<Integer> range(int start, int stop, int step) { List<Integer> result = new ArrayList(); for (int i = start; i < stop; i += step) result.add(i); return result; }
private static List<Integer> range(int start, int stop, int step) { List<Integer> result = new ArrayList(); for (int i = start; i < stop; i += step) result.add(i); return result.size() == 0 ? Collections.emptyList() : result; }
This simply enhances code readability a little, compared to your solution. Only for scenarios in which the list returned has to be modified, we can't use the above approach, as Collections.emptyList() returns an immutable. Your solution is perfectly fine of course as it guarantees an empty list instead of null.
@soumyadeep2007 Hmm... how is that supposed to enhance readability? It requires extra reading and extra thinking, and it's unnatural.
Besides readability, it's also worse because making the empty list immutable when every other result is mutable is again creating a special case. Similar to returning
null. If the caller wants to modify the list, they now need add extra code for it, similar to the extra code for
null.
P.S. Why
result.size() == 0 instead of
result.isEmpty()?
@StefanPochmann Yes I see your reasoning. We should not be creating special cases. And my bad, I should be using isEmpty. If we want to return an immutable list, we would simply do:
private static List<Integer> range(int start, int stop, int step) { List<Integer> result = new ArrayList(); for (int i = start; i < stop; i += step) result.add(i); return Collections.unmodifiableList(result); }
I will update my post. Thanks for your insight!
@soumyadeep2007 Yeah, if you for some reason do want immutability, then I guess that's a reasonable way. Just some further thoughts:
- It's only shallow immutability. The list's elements can still be mutable (demo). Not the case in my example with Integers, of course.
- Apparently not even
Collections::unmodifiableListbothers to check for emptiness and using
Collections::emptyListwhen it could. Not sure why, I guess the authors don't think it's worth it.
- Its documentation talks about a use case: "allows modules to provide users with "read-only" access to internal lists". And really that's the only real reason I can imagine. That it's the producer of the list who's interested in immutability. If it were the caller who's interested in immutability, they should probably call it themselves instead. But I can't imagine why a caller would want immutability.
- Overall the only use case I see for
Collections::emptyListis when a producer wants to return an immutable list and its "regular" code can't handle some cases where the result will be empty. Then it might be good to start with something like
if (..specialcase..) return Collections.emptyList();. Could also be done for optimization, i.e., if the "regular" code can handle the special case and would return an empty list in the end anyway, but we can detect this early on and just return an empty list right away. Though I really dislike that. I've seen many people do that and I'm not sure I ever thought it wasn't bad. Because it adds code, suggests that the "regular" code can't handle the case, and only makes one or few special cases faster while making all other cases slower. So usually it's more code, misleading, and achieves the opposite of the intended optimization.
@StefanPochmann hey thanks again for your eye-opener!
- Coudn't agree more with your first point. Indeed it is shallow immutability. Here's an example to supplement yours.
class MyClass { int a; @Override public String toString() { return a + ""; } } public class Solution { public static void main (String[] args) { List<MyClass> list = new ArrayList<>(); MyClass obj = new MyClass(); obj.a = 5; list.add(obj); List<MyClass> unmodList = Collections.unmodifiableList(list); obj.a = 7; System.out.println(list); //O/P : [7] System.out.println(unmodList); // O/P : [7] } }
- I completely subscribe to the view that code should not be littered with sanity checks. However, I could form somewhat an argument to your last point for a certain use case : What about base cases in recursive functions? Isnt it better or even convention to put up a base case at the beginning with a conditional check and a return?
As for all other cases, your are spot on: benefits of such optimization are often overestimated:
few special cases faster while making all other cases slower.
@soumyadeep2007 said in Don't return null for functions returning collections/iterables:
What about base cases in recursive functions? Isnt it better or even convention to put up a base case at the beginning with a conditional check and a return?
Maybe. Can you show an example?
@StefanPochmann For example this is a nice convention from the book : The Algorithm Design Manual that I follow for backtracking problems:
Backtrack-DFS(A, k) if A = (a1, a2, ..., ak) is a solution, report it. else k = k + 1 compute Sk while Sk != null do ak = an element in Sk Sk = Sk − ak Backtrack-DFS(A, k)
An example:
public class Solution { public List<List<Integer>> permute(int[] nums) { Set<Integer> numSet = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>()); for(int num : nums) { numSet.add(num); } List<List<Integer>> result = new ArrayList<>(); List<Integer> solutionVector = new ArrayList<>(); permute(numSet, solutionVector, result); return result; }); } } private boolean isSolutionFound(Set<Integer> numSet) { return numSet.isEmpty(); } private void processSolution(List<Integer> solutionVector, List<List<Integer>> result) { List<Integer> permutation = new ArrayList<>(); for(Integer choice : solutionVector) { permutation.add(choice); } result.add(permutation); } private void makeMove(Set<Integer> numSet, Integer choice, List<Integer> solutionVector) { numSet.remove(choice); solutionVector.add(choice); } private void undoMove(Set<Integer> numSet, Integer choice, List<Integer> solutionVector) { numSet.add(choice); solutionVector.remove(solutionVector.size() - 1); } }
@soumyadeep2007 Hmm, I don't see what your example has to do with my last point or even with your argument you mentioned. You're not using
Collections::emptyList and you don't have code for base cases returning early.
@StefanPochmann Ok I see that there has been sort of a miscommunication. I thought you were talking generically with respect to the if special case.. construct. Now I understand that you were talking about the specific case.
@soumyadeep2007 Well, I'd say I did have a more general situation in mind, but I still don't think we disagree. I guess you mean the
if-part here, right?); } }
That then rather falls in the ""regular" code can't handle" category, as the "regular" code (the
for-loop) doesn't do what the
if-part does (processing the solution). So then you actually have less special treatment than I talked about, because I said to return (with the appropriate result, though in this case the appropriate side-effect). You don't return there. You still run into the loop. Which loops over nothing, so does nothing, so it's ok. That's how you stop the recursion. Not with extra code. So in a sense, you just gave an example of not having extra code for the special case :-)
@StefanPochmann I see what you are saying with respect to special treatment and returns. Thanks again!
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/95845/don-t-return-null-for-functions-returning-collections-iterables/18 | CC-MAIN-2017-39 | refinedweb | 1,679 | 57.27 |
MagLev Ruby VM Now Available, Brings GemStone's Persistence to Ruby
Mag?
Re: MagLev Ruby VM Now Available, Brings GemStone's Persistence to Ruby
by
Conrad Taylor
replace
Maglev.persistent do
Maglev::PERSISTENT_ROOT[:stuff] = ["hello world"]
end
Maglev.commit_transaction
with
Maglev::PERSISTENT_ROOT[:stuff] = ["hello world"]
Maglev.commit_transaction:
module MaglevModel
# these methods will be defined as class methods of the class that
# includes this module.
module ClassMethods
# returns an array of all the posts
def all
# set the values including its state to current for all persistent objects.
# i.e. give me the current state of the last commit.
Maglev.abort_transaction
# retrieve all the Post instance as a collection hash.
Maglev::PERSISTENT_ROOT[self].values
end
end
# save current Post instance to the set of persisted objects.
def save
# store the current Post instance as a child of the Post class.
Maglev::PERSISTENT_ROOT[self.class][self.__id__] = self
# save the current state back to the repository.
Maglev.commit_transaction
end
def self.included( klass )
# create a space in the PERSISTENT_ROOT to hold persistent Post objects.
# note: the statement below refreshing our repository each time it's ran
# but it's cool for something simple that's used for instructional purposes.
Maglev::PERSISTENT_ROOT[ klass ] = Hash.new
# stage the Post class for persistence.
klass.maglev_persistable = true
# stage the MaglevModel module for persistence.
self.maglev_persistable = true
# extend the Post class with the ClassMethods (i.e. after this statement is executed, the methods within
# ClassMethods module become class methods on our Post class.)
klass.extend ClassMethods
end
end
Now, let's create the Post model and this will be a snap because we have done most of the work by
creating a reusable module, MaglevModel, for enabling persistence within the Post class:
post.rb:
require 'maglev_model'
class Post
# let's include our MaglevModel for enabling persistence within the Post class.
include MaglevModel
# let's create some accessors for the
attr_accessor :title, :description
# initialize the Post instance.
# note: this instance method is called indirectly when the new class method is invoked.
def initialize( params = {} )
@title = params[:title]
@description = params[:description]
end
# output a string representation of this Post instance.
def to_s
"title => #{@title}\ndescription => #{@description}\n"
end
end
Maglev.commit_transaction
# let's create and save a couple of posts.
post_one = Post.new( :title => "This is post 1", :description => "This is post 1 description." )
post_one.save
post_two = Post.new( :title => "This is post 2", :description => "This is post 2 description." )
post_two.save
# let's output all the persistent Post instances from the repository.
Now, if we were to run the above code, one should see the following:
$ maglev-ruby post.rb
And I agree - it's great to see MagLev available to | http://www.infoq.com/news/2009/11/maglev-public-alpha | CC-MAIN-2014-15 | refinedweb | 443 | 50.53 |
#include <deal.II/base/parsed_function.h>
Friendly interface to the FunctionParser class. This class is meant as a wrapper for the FunctionParser class. It is used in the step-34 tutorial program.
It provides two methods to declare and parse a ParameterHandler object and creates the Function object declared in the parameter file. This class is derived from the AutoDerivativeFunction class, so you don't need to specify derivatives. An example of usage of this class is as follows:
And here is an example of how the input parameter could look like (see the documentation of the FunctionParser class for a detailed description of the syntax of the function definition):
Definition at line 79 of file parsed_function.h.
Construct a vector function. The vector function which is generated has
n_components components (defaults to 1). The parameter
h is used to initialize the AutoDerivativeFunction class from which this class is derived.
Definition at line 26 of file parsed_function.cc.
Declare parameters needed by this class. The additional parameter
n_components is used to generate the right code according to the number of components of the function that will parse this ParameterHandler. If the number of components which is parsed does not match the number of components of this object, an assertion is thrown and the program is aborted. The default behavior for this class is to declare the following entries:
Definition at line 36 of file parsed_function.cc.
Parse parameters needed by this class. If the number of components which is parsed does not match the number of components of this object, an assertion is thrown and the program is aborted. In order for the class to function properly, we follow the same conventions declared in the FunctionParser class (look there for a detailed description of the syntax for function declarations).
The three variables that can be parsed from a parameter file are the following:
Function constants is a collection of pairs in the form name=value, separated by commas, for example:
These constants can be used in the declaration of the function expression, which follows the convention of the FunctionParser class. In order to specify vector functions, semicolons have to be used to separate the different components, e.g.:
The variable names entry can be used to customize the name of the variables used in the Function. It defaults to
for one dimensional problems,
for two dimensional problems and
for three dimensional problems.
The time variable can be set according to specifications in the FunctionTime base class.
Definition at line 105 of file parsed_function.cc.
Return all components of a vector-valued function at the given point
p.
Reimplemented from Function< dim >.
Definition at line 155 of file parsed_function 164 of file parsed_function.cc.
Set the time to a specific value for time-dependent functions.
We need to overwrite this to set the time also in the accessor FunctionParser<dim>.
Definition at line 173 of file parsed_function.cc.
The object with which we do computations.
Definition at line 210 of file parsed_function.h. | http://www.dealii.org/developer/doxygen/deal.II/classFunctions_1_1ParsedFunction.html | CC-MAIN-2017-43 | refinedweb | 502 | 55.64 |
Mar 29, 2012 08:15 PM|selarom|LINK
I have an MVC site that has actions that accept two parameters, something like this:
public ActionResult ListResults(string City, string State)
What I want is to be able to intercept the request and verify the parameters BEFORE it gets to this action. This validation would perform the following:
Right now I'm doing this inside the Action as it loads before I do any processing, redirecting as needed.
This feels like it should happen before the request, but I don't know how. Can someone tell me a) if indeed this can (and should) be extracted out and executed before the action, and b) how to do it
Many thanks!
mvc validation
All-Star
19558 Points
ASPInsiders
MVP
Mar 29, 2012 08:17 PM|BrockAllen|LINK
Checkout ActionFilters in MVC. They allow for generic preprocessing of action methods.
Mar 29, 2012 08:21 PM|CodeHobo|LINK
You can create a custom action filter to do this
Look into inheriting from the ActionFilterAttribute and overriding OnActionExecuting. This fires before the action and you can simply tag the action method with the attribute. In the attribute you can have access to route parameters, querystring parameters etc.
However, with that said, instead of doing it this, I would recommend creating a model with both city and state. Then create a custom data annonation validation on that model. That way you don't have to decorate any action method and the validation is then in the model , close to the data. This will also work better with the model binder and allow you to easily return those validation errors back tot he client without having to write a lot of boilerplate code yourself.
So basically you can do it both ways. The second takes advantage of the existing framework and validation scheme, the first requires you to write a lot of boilerplate code. Personally I would go with the second.
mvc validation
Mar 29, 2012 08:24 PM|selarom|LINK
@CodeHobo, can you tell me more about this second option? What is a custom data annotation validation and how do I use it?
Mar 29, 2012 09:04 PM|CodeHobo|LINK
Data annotation validation is a way to decorate your model with validation attributes. For example:
public class Product{ public int ProductId {get;set;} [Required] public string Name{get;set;} }
In this example the Name property is required and asp.net mvc will run validation on it for you. In fact, it will even set up client side validation in javascript automatically. There are a few built in validators, required, stringlength.
You can read more about data annotation validation here.
In addition to the built in annotations, you can also add your own custom annotation and use that in your model.
Take a look at this post on custom data annotation validation attributes.
Mar 29, 2012 09:09 PM|selarom|LINK
hmm that is interesting but I'm not so much validating the input as much as I need to compare the input to a database to ensure that it exists and was spelled with correct casing.
That means I have to do a database call, so I don't think data annotations would be the best way to do this, would it?
An action filter seems like the better option, would you all agree?
Mar 29, 2012 09:18 PM|CodeHobo|LINK
From a performance point of view both would identical. In my opinion the gain would be the ability to easily integrate error messages back into the view. But you should look at both and pick whichever one works best for your particular style and which you think will be easier to maintain in the long run.
Mar 31, 2012 07:10 PM|selarom|LINK
the action filter worked masterfully. I was able to both validate the input paramaters aganst the database and even return the instantiated object via the RouteData so it is available to the action.
Pretty good stuff, thanks for your input everyone!
7 replies
Last post Mar 31, 2012 07:10 PM by selarom | http://forums.asp.net/p/1786984/4907073.aspx?Validating+parameters+before+executing+Action+ | CC-MAIN-2015-11 | refinedweb | 685 | 61.67 |
Although these two technologies are the most commonly used, they are by no means the only ones in existence. Language
bindings exist for Python, PHP and a host of other languages, including C/C++ (from now on referred to as C, for brevity.) This
article will focus on using SOAP in a C environment.
Why would you want to write web services in C when there are alternatives that are better suited to the task?
There are couple of reasons. First, there are very few web services that exist for their own sake, and as
a developer, you are more likely to use them as just another part of a bigger application or project. This means that your language or environment
is dictated by the greater need of the application, not just by the web services aspect of it. The second reason is that there is
an enormous amount of code available as C source or shared libraries, and you may be interested in making some of this available as a web service..
Installation and Configuration
Step 1: Download the software. For most uses, and certainly for a learning exercise, installing the binary versions is more than
enough. The current stable version of Axis-C++ is 1.4, and the file is available from the
Apache file repository.
The file you should download is
axis-c-linux-current-bin.tar.gz. You will also need version 2.2.0 of the
Xerces XML Parser, part of the Apache XML project. The file you need
is probably called
xerces-c2_2_0-linux8.0gcc32.tar.gz, but if not, choose the one most appropriate for your operating system and architecture.
For the code generation tools to work, you will also need to install a Java SDK. Any recent version of Sun's J2SDK
will work correctly, though you can try using any other version you may have installed.
Although you can use the standalone server included with Axis, this article will explain how to integrate Axis with the Apache2 webserver.
The installation of Httpd falls outside the scope of this article, so it is assumed that there is already a version installed and working.
Usually the version packaged with your distribution will work fine.
Step 2: Unpack and copy files. First, you'll need to unpack the Axis archive, using the standard
tar -xzvf. Move the
unpacked directory to
/usr/local and rename it to
axiscpp_deploy. The renaming isn't strictly necessary, but all the
configuration files refer to this location, so changing it means modifying more files.
Next, decompress the Xerces parser. You only need one file from this, and it is
lib/libxerces-c.so.22.0 inside the directory created
when you unpack the tar file. Copy this file to the
/usr/local/axiscpp_deploy/lib, and change to this directory. Create a soft link to
the file using the command
$ ln -s libxerces-c.so.22.0 libxerces-c.so.22
If the directory doesn't contain a file named
libaxis_xmlparser.so, or if this file exists but is not a copy of the file
libaxis_xercesc.so.0.0.0, then copy the second file over the first using the command
$ cp libaxis_xercesc.so.0.0.0 libaxis_xmlparser.so
This ensures that Axis will use Xerces as its XML parser. The alternative, Expat, is currently unsupported.
Finally, you need to configure Axis. The configuration files are in the
/etc directory of your Axis installation and are all
suffixed with the string
_linux. For the time being, simply rename the files by removing the suffix from the filename. The main Axis configuration
is in
axiscpp.conf, and the file describing the services deployed by an instance is called
server.wsdd.
We'll cover the contents of the latter file in a little more detail later.
With the basic Axis server installation complete, you can test it by trying to run the included standalone server. The commands
for this are the following:
$ cd /usr/local/axiscpp_deploy/bin $ export AXISCPP_HOME=/usr/local/axiscpp_deploy $ export AXISCPP_DEPLOY=$AXISCPP_HOME $ export LD_LIBRARY_PATH=$AXISCPP_DEPLOY/lib $ ./simple_axis_server 9090
Note that the argument to the server can be any port that is currently not in use. When everything has been installed correctly, the server will not
return and
netstat -npl will show your chosen port as accepting connections. If this is not the case, go back and make sure you've followed
every instruction carefully.
Step 3: Configuring Apache. Now that Axis is working, we can get started on the tricky part, which is hooking Axis up with
a pre-compiled Apache Httpd. This is not as straightforward as it could be because Axis requires a number of environment variables to be set in order to
run correctly, so to use your Axis installation as-is you have to edit your Apache startup scripts. Editing scripts is inconvenient
for a number of reasons, the foremost of which is that it can cause problems when you upgrade your Apache installation. There is an alternative, but
unfortunately, it requires tweaking your machine by modifying your default system configuration. For this reason, we'll look at both ways of getting the
Apache module working properly, and you can choose which method suits your needs best. Remember, you will need to have root privileges for some of the steps
detailed below.
The first way is simply to edit your Apache startup script, probably somewhere in
/etc/init.d, and add the following two lines
near the beginning of the script to ensure that all the necessary files can be found:
AXISCPP_DEPLOY=/usr/local/axiscpp_deploy LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$AXISCPP_DEPLOY/lib
The alternative procedure consists of two steps. The first thing to do is add the line
/usr/local/axiscpp_deploy/lib
to your
/etc/ld.so.conf file. Run
ldconfig, and don't worry about the warnings. This will ensure that Apache can
find all the necessary libraries when it runs. Next, copy the file
/usr/local/axiscpp_deploy/etc/axiscpp.conf to
/etc and make sure
all the paths inside the file are correct (they should all point to various places inside
/usr/local/axiscpp_deploy.)
After carrying out one of the previous steps, copy the file
/usr/local/axiscpp_deploy/lib/libaxiscpp_mod2.so to your Apache modules directory and
add the lines
LoadModule axis_module modules/libaxiscpp_mod2.so <Location /axis> SetHandler axis </Location>
to your Apache configuration file. Note that the path given in the
LoadModule line should point to the same directory as the rest of the modules
in your installation.
This will deploy all the SOAP services you wish to export under the
/axis directory of your web server. Note
that this assumes a single server instance. If you have a virtual hosts set up, be careful under which host you make the services available. In case you change
the installation host, substitute it's Hostname wherever you see
localhost in URLs from now on.
Step 4: Test your installation. With the configuration done, restart your Apache server. Change into the
bin directory of
the Axis installation and make sure you still have the three previously mentioned environment variables set. To see if the installation has worked, we're
going to try the bundled calculator application. Run the following command:
$ ./Calculator mul 4 5
This command executes a multiplication operation with operands 4 and 5. If the installation of everything has been successful, the result should look
like:
Using service at Ret:20 20
If the example does not return this, then the type of failure must be examined. If the program refuses to run, then the problem is likely with the
environment variables mentioned above. If there is a problem contacting the Axis server, then the calculator will either fail and tell you the reason was
due to network errors, or else it will just sit there and not do anything. If you installed axis to a virtual host other than localhost, then the calculator
requires an additional argument, the URL of the web service, before any of the others. This will be something like.
If execution returns a correct answer, congratulations! You have a perfectly functional Axis-C++ installation. The next thing to do is to attempt to
write our own web service.
Implementing a Service
The rest of this article focuses on how to create and deploy your very own web service. The sample service will take a string as input
and return the MD5 hash of the given string as output. For this, we'll implement a wrapper to the
MD5() function available in the
libssl library, which is part of the OpenSSL project. The service will accept a string in plain text
and will return the string representation of the hexadecimal MD5 hash for the input string. Remember that you might need to install the OpenSSL headers, if
you don't already have them.
SOAP services normally begin their life as a description of what they do. This description is in the form of a Web Services Definition Language (WSDL) file, which
is an XML file that contains information on what the service is called, how to invoke it (URL), what parameters it takes, what it returns and what the types of
all the inputs and outputs are. Because this information is structured, it can be used to generate much of the code needed to deploy and use a web service, and so
it follows that the first step in creating our service is to write the corresponding WSDL description.
Explaining the workings of WSDL lies beyond the scope of this article, but we'll need a description of our service before moving on to the next step.
The simplest possible sample of a WSDL file for the service we're going to implement is as follows:
<?xml version="1.0" encoding="UTF-8"?> <wsdl:definitions <!-- Message types: define input and output types --> <wsdl:message <wsdl:part </wsdl:message> <wsdl:message <wsdl:part </wsdl:message> <!-- Port type: define a SOAP operations --> <wsdl:portType <wsdl:operation <wsdl:input <wsdl:output </wsdl:operation> </wsdl:portType> <!-- Binding: Bind a location in this service to an name: define the name and URL of this service --> <wsdl:service <wsdl:port <wsdlsoap:address </wsdl:port> </wsdl:service> </wsdl:definitions>
This may look complicated, but all it does is define a call with the name GetMD5 which accepts a single input string, called Cleartext,
and returns another string called MD5Hash. This call is available with the name MD5Service#GetMD5 and the entire service is deployed at the URL. Save this file as
MD5.wsdl in a new directory.
Now that the service is defined, we can use some tools provided by Axis to generate most of the code that we're going to need, and this is where
Java comes into play. Assuming it is correctly installed, you will need to have the
JAVA_HOME environment variable set to the appropriate
path, and have the Java executable somewhere in your
PATH. You'll need to set the Java Classpath using a set of commands like the following:
$ export TMP=$AXISCPP_DEPLOY/lib/axisjava $ export CLASSPATH=$AXISCPP_DEPLOY/lib/axis/wsdl2ws.jar:\ $TMP/axis-ant.jar:\ $TMP/axis.jar:\ $TMP/commons-discovery.jar:\ $TMP/commons-logging.jar:\ $TMP/jaxrpc.jar:\ $TMP/log4j-1.2.8.jar:\ $TMP/saaj.jar:\ $TMP/wsdl4j.jar:\ $TMP/xml-apis.jar $ unset TMP
Now, executing the command
$ java org.apache.axis.wsdl.wsdl2ws.WSDL2Ws
should print the WSDL2Ws help blurb. If you get any other output, then go through the above steps again and make sure you have followed each step correctly.
The next step is to generate the server-side stubs for the service. The WSDL2Ws tool is very handy because it generates all the code you need to implement
your web service, leaving you with an empty class where you just fill in the blanks. To generate the stubs, change into the directory that holds the WSDL file
created previously, create a subdirectory called server to hold the generated server-side code and execute the following command:
$ java org.apache.axis.wsdl.wsdl2ws.WSDL2Ws -lc++ -sserver -oserver ./MD5.wsdl
All this command does is generate C++ server-side code from the description in
MD5.wsdl and place the resulting code into the
server directory. Once the command has executed, change into the
server directory and examine it's contents. The only file
that you need to modify is
MD5Service.cpp, which implements the MD5 class. This class will contain the logic of your service.
For now, the only method that you need to implement is
MD5::GetMD5(), although for more complex services, you may need to write constructors and
destructors for your class or fill in some of the other generated methods for error handling and the like.
Both the parameter and return types are
xsd__string, which is basically a
typedef for a
char *, so the only code that
has to be written for this example is as follows:
xsd__string MD5Service::GetMD5(xsd__string Value0) { unsigned char * r; char * returnValue = (char *)calloc(1, 33); r = MD5((unsigned char *)Value0, strlen(Value0), 0); snprintf(returnValue, 32, "%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]); return returnValue; }
The code isn't the prettiest, but it does the job. The parameter and return types for numeric values in the WSDL file map to native C++ types such as
int and
long, so if your call returns a number, then you don't have to allocate memory for the return value. However, in this
case the memory must be allocated. Also, remember to
#include <openssl/md5.h> at the beginning of the file.
A service is contained in a standard .so file, which will then be dynamically loaded by Axis at runtime. The command for compiling the code and generating
the library is:
$ gcc -shared -o libmd5.so *.cpp -lssl -I. -I$AXISCPP_DEPLOY/include -L$AXISCPP_DEPLOY/lib
To deploy the library, you should copy the new file
libmd5.so to
$AXISCPP_DEPLOY/lib and then modify the Web Service Deployment Definition
(WSDD) file with the information that Axis needs to know in order to deploy your web service.
The file to edit is called
$AXISCPP_DEPLOY/etc/server.wsdd. Like almost everything to do with SOAP, it is an XML file, and so is fairly easy to
read and understand. To deploy a service, you need to include the following snippet inside the
<deployment> tag:
<service name="MD5Service" provider="CPP:RPC" description="Simple MD5 Service"> <parameter name="allowedMethods" value="GetMD5 "/> <parameter name="className" value="/usr/local/axiscpp_deploy/lib/libmd5.so" /> </service>
All this does is tell Axis that it should deploy a service called MD5Service, and accept calls for a method called GetMD5.
This call exists implemented as a function of the same name in the library
/usr/local/axiscpp_deploy/lib/libmd5.so. Note that you can install
the library anywhere you want, since the location is an absolute path. We have installed it where it is for convenience. Now, a simple restart of Apache
will deploy the new service.
The next and final step is to test that the service is correctly deployed and working as expected. The easiest way of doing this is by going back to the
directory that holds the original WSDL file and creating some client code using the same tool as before. Again, start by creating a directory called
client to hold the code. Then, run the command:
$ java org.apache.axis.wsdl.wsdl2ws.WSDL2Ws -lc++ -sclient -oclient ./MD5.wsdl
The generated client-side code is even easier to use than the server code, because absolutely everything to do with the service is encapsulated inside a
class and each call contained in the service is implemented as a method of the class. Therefore, the only code that has to be written is a new file that
contains a
main() method where an instance of the class is created and the method to test is called. For this example, the following code in
a new file called
main.cpp within the
client subdirectory will suffice:
#include "MD5Service.hpp" #include <iostream> using namespace std; int main(void) { MD5Service srv; char * testString = "Test String"; cout << "MD5 of '" << testString << "' is: " << srv.GetMD5(testString) << endl; return 0; }
As you can see, the generated class implements a single method for each call contained within the WSDL file, and creates it with the same name, to remain
coherent. To compile the test, change into the
client subdirectory and execute the command:
$ gcc -o md5test *.cpp -I. -laxiscpp_client -L$AXISCPP_DEPLOY/lib -I$AXISCPP_DEPLOY/include -ldl
Now, all that's left is to execute the test and check the output. A successful test will produce output like this:
$ ./md5test MD5 of 'Test String' is: bd8ba3c982eaad768602536fb8e1184
And that's it! A working SOAP server and it's corresponding client, all without leaving C/C++. Again, if you have any problems make sure you have followed
all the steps above to the letter.
Conclusion
Unfortunately, setting up and using Axis is not as easy as this article makes it seem. Axis is very picky about how it is set up, and getting even a simple
service like the one above working can require a lot of patience, trial and error, and extensive use of debuggers and packet sniffers to determine the nature
of problems because Axis doesn't return much useful information when something goes wrong. Knowing where to look for problems is a skill that comes with time.
Also, whereas the example presented above has been engineered to work correctly with the available tools as-is, any production-level code must be examined in
detail for correctness. There are still some bugs in the code-generation tools.
However, being able to adapt to new technological trends when management demands it while still being able to use existing know-how can prove invaluable,
especially when time is of the essence. In short, Axis in its C++ version has a limited scope for use, but under the right circumstances, it can save a
lot of time and effort. | https://www.linux.com/news/creating-web-services-using-apache-axis-c | CC-MAIN-2018-34 | refinedweb | 3,039 | 53.81 |
Custom Geometry¶
In this tutorial, we’re going to create the oh-so-simple
box() geometry from scratch. It’s not
particularly interesting on it’s own, but it does demonstrate a lot of useful tools.
We start by listing the corners of a box in order:
import numpy as np corners = np.array([ [0, 0], [0, 1], [1, 1], [1, 0]])
These corners give a 1m box, which is a bit too small for our purposes. We can scale it up by multiplying by the width we want. It’s also a good idea to shift it 1m up and to the right, as lots of machinery in megastep assumes that everything happens in the top-right quadrant (ie, above and to the right of the origin). There’s no fundamental reason for this, it just simplifes some stuff internally.
corners = 5*corners + 1
Then to get the walls, we take all sequential pairs of corners and stack them:
from megastep import geometry walls = np.stack(geometry.cyclic_pairs(corners))
You can check that these walls are what we think they are by putting them in a dotdict and using
display():
geometry.display(dotdict.dotdict( walls=walls))
With the walls in place, the other thing to deal with is rooms. There’s no strict definition of a room; they’re just small, generic regions. The usual use of them is to make it easy to spawn multiple agents near eachother.
In this case, our room is going to just be the corners we had before. That’s a list of corners though, while our geometry wants a mask. Fortunately there’s already a function to turn one into the other:
masks = geometry.masks(walls, [corners])
Again, we can plot it to check how it looks:
g = dotdict.dotdict( walls=walls, masks=masks, res=geometry.RES) geometry.display(g)
As well as adding the masks themselves to the dict, we’ve also added the resolution of the mask. In this case, it’s
the resolution
masks() uses by default. The result is this:
This
masks array has a -1 where there’s a wall, a 0 where there’s free space, and a 1 where our room is.
Now that we’ve got both walls and masks, we just need to add the location of lights:
from rebar import dotdict g = dotdict.dotdict( walls=walls, masks=masks, lights=np.array([[3.5, 3.5]]), res=geometry.RES) geometry.display(g)
And we’re done! This is all that’s needed to create scenery for your environments.
It’s mentioned in the geometry section but worth re-mentioning here: geometries are dicts rather than classes because as you develop your own environments, scene and geometries you’ll likely find you have different ideas about what information a geometry needs to carry around. A dotdict is much easier to modify in that case than a class. | https://andyljones.com/megastep/tutorials/geometry/index.html | CC-MAIN-2022-33 | refinedweb | 483 | 71.65 |
Analyzing my Spotify Music Library With Jupyter And a Bit of Pandas
Or the quest to cleanup my saved songs to play everything on random.
Are you a Spotify user? By now, that’s the way I consume most of my music.
Recently, I have been developing a web app which uses the Spotify API in part for a series of posts about developing a small real-life application and web development in general. The app is written in Python and Flask for displaying full-sized album art for the songs which are playing on a user’s Spotify account.
While playing around with the Spotify web API, and building a login flow in the app, it was pretty easy to get an access token for my account with all kinds of permissions for access to my data. Among others, it’s good for everything needed to analyze the heck out of your whole music library - information about songs and albums in particular.
The Motive
My music library on Spotify is quite big. What I like to do, is just put all of my “saved” songs, and put the on shuffle play. I’m not sure the library is meant for such use - it’s a bit in the way of when songs are “saved”.
To listen to songs in offline mode, you can “download” them on a particular device. Doing so also “saves” them, thus adding the complete album to your music library. You can get around that with playlists, but that’s a few more clicks.
As I’m in the habit of giving complete albums a listen every once in a while, and forgetting about the stuff I download-saved, my music library is now a bit messy. This leads to song playing which are not as enjoyable without the album context. Oh the pain.
The Cure
Having the amazing data crunching powers of the forementioned TOKEN, I thought it’d be cool to take a look at what albums I have in my library. And maybe clean up obvious mis-saves, but also to see what stuff I really seem to like. Here’s the plan:
- Get data on all songs in my library (especially which album they belong to)
- Get data for each album referenced (total number of songs, how many of those are in my library)
- Do something with the information (aka cleanup)
There are further possible stuff one could do with the data, for example to handcraft an own simple artist/album recommendation script, but that’s for anonther time.
Before we Proceed
A word of caution:
The code below was never meant to be reliable or presentable. It doesn’t mean it’s bad in general. I wrote it to satisfy my own curiosity, and with one person in mind who would ever see it: yours truly. The samples are not as polished as other specimen you will find elsewhere, and might not be the best learning resource regarding best practices.
That said, it works, does what it’s supposed to do given the context and priorities of and probably looks very similar to many real-world projects, where results and time constraints are significant factors.
The whole code is integrated in the article, but if you want to get a copy of the jupyter notebook (sans secrets and my data), just drop me your email in the form at the bottom of the page, and let me know that you’d like to have it by responding to the mail :)
Alright! Let’s jump into it!
The Setup Step by Step
Here’s what I usually do when starting an exploratory data project with Python.
When tinkering with data years ago, I used to rely on running tiny Python scripts and saving intermediate results. Then I got introduced to ipython notebooks and never looked back. By now, jupyter notebooks are what you should use. It’s the perfect tool for working with Python and data when you’re trying stuff out and playing with an early-stage data project.
With Python projects, I like setting up a virtual environments for each one. This makes it easy to isolate dependencies, install EXACTLY what is needed in the version which is needed and make sure that the code runs out of the box.
So I went ahead and created a new virtual environment using virtualenv wrapper. It’s really convenient, if you don’t know it and like Python, check it out! In the following, code blocks starting with $ is what happens in a terminal, while everything else is Python code.
$ mkvirtualenv spotify
Jupyter is a python module, and can be installed using pip:
$ pip install jupyter
For data-tastic Python fun, I usually install a few modules by default, to make sure I can do basic data crunching, plotting and http requests without much effort. Here is my choice of tools for all of the above:
- requests - A great library for talking to web apis and fetching single web pages.
- furl - For creating urls and requests in general with parameters for GET / POST stuff.
- pandas - Makes python feel a bit like R, namely able to work with data frames and crunch data without getting too verbose about it.
- matplotlib - To give pandas plotting-superpowers.
Here’s how you’d install it all:
$ pip install pandas matplotlib requests furl
In this investigation, I did not really use much pandas, nor matplotlib apart from a tiny diversion. Don’t be discouraged by them appearing to be of little value, they shine when the data handling gets more challenging.
Once everything was installed, I went into a new directory created for the project and started the Jupyter notebook server with:
$ jupyter notebook
Which also opens the Jupyter web interface in a new tab in your browser. Everything that was left to do at this point, was to create a new notebook, give it a name and start the fun.
Hello API
The code samples below, are what I typed into the Jupyter notebook cells. They are depending on each other, use previous variables as you would in a single script, but can be re-executed as needed. It’s perfect to experiment and get things to work without enduring unnecessary waiting time.
But anyway, to access the Spotify Web API, we need the API access token. You could use the big album art project in development mode. You’ll need a private Spotify app, insert the tokens as environment variables, add a “print” statement in the home view, run the app localy and you’ll be set. Don’t forget to adjust the permission request (see a few lines below).
Otherwise, I will write about the application in a later article as it’s a whole different topic. If you’d like to be notified when it’s published, just drop me your email adress in the form below :)
The permission scopes we’ll need are:
"user-read-private user-read-email user-read-playback-state user-read-currently-playing user-library-read"
I just made the app print the token value, and copied it into the first cell of the notebook. The token expires after a while, so you might need to refresh it when working on the code.
TOKEN = "???"
I like to put constants in the beginning of a project and write the name in UPPER_CASE_NOTATION. We will need a few Python modules for convenience - the ones we installed previously. Let’s import them:
import json import requests from furl import furl from math import ceil # to save some typing import pandas as pd import matplotlib # to display plots in the notebook %matplotlib inline import matplotlib.pyplot as plt
The code above also makes it possible for plots to appear inline in the notebook, which looks nice. We’re ready to get the data!
The First Request
Now that we have the token and tools in place, it’s really simple to get the first bit of information.
As we want to get the tracks of our user, we’ll go ahead and take a peek at how many there are. The API is well documented, and can be browsed here. The tracks endpoint is what we need. The response is paginated, but for the field we need this does not matter. The total number of songs is available under the “total” key.
url = "" headers = {'Authorization': "Bearer {}".format(TOKEN)} r = requests.get(url, headers=headers) parsed = json.loads(r.text) count_songs = parsed["total"] print "Total number of songs: {}".format(count_songs)
We make the request using requests, add a header with the authentication info (as described in the docs), parse the response into json and - without checking for errors - take the data field into a var. If the request goes wrong for some reason, we will get an exception in the notebook and should be able to fix it /rerun the thing. So no fancy edgecase handling is needed.
Apparently I have 2416 songs in the library.
Getting Track Data
User libraries can be quite large. Thousands of songs. It would be unnecessary and at some point impractical to return all songs on every single request to the tracks endpoint. That’s why it is paginated. We need all of those of course.
We got the number of songs, and the first “page” of songs in the user library. The maximum amount of songs returned per request is 50 if you specify it. So all we need is the total number and a for loop.
Once again, as this code is pretty unlikely to fail, and can be reexecuted if needed we don’t care about crashing if everything goes wrong.
# paginate over all tracks all_songs = [] for i in range(int(ceil(count_songs/50.0))): offset = 50*i url = "{}".format(offset) headers = {'Authorization': "Bearer {}".format(TOKEN)} r = requests.get(url, headers=headers) parsed = json.loads(r.text) all_songs.extend(parsed["items"]) print "Number of gathered songs: {}".format(len(all_songs))
The printed number equals the one above. Neato. If the responses would fail, we’d notice. Now we have the complete user library of songs. Imagine the possibilities.
How Many Albums Are Referenced?
Staying on track. We’d like to get the albums which are referenced by the songs. The track data does not have everything we need unfortunately - there’s only the album id and a bit of other info. We’ll need to get detailed data on each relevant album, especially the number of tracks each has in total
Using a Python set, we can get a unique list of all album ids which we will need.
album_ids = set() for song in all_songs: album_id = song["track"]["album"]["id"] album_ids.add(album_id) print "Number of albums: {}".format(len(album_ids))
For me that prints 1307 as the number of albums. Roughly half of my library song count. Huh. Who would have thought.
Lots of Requests Later
With the album ids at hand, we can proceed. I usually get the raw data and produce derived datasets in later steps. This way we can go back and use fields which we ignored at first. This also suits the iterative superpowers of Jupyter - single computation steps can be reexecuted in isolation, not requiring the previous ones to run again.
This part is anything but elegant. In fact it’s a bit rude. We could request multiple album ids and only use 1/20th of the current requests. Also, it would be faster if we watched the rate limits and the Retry-After header. Once the waiting times are long enough, or when there would be multiple users I’d reconsider being more polite and less lazy.
Running this takes a few minutes.
# gather information on all albums album_info_by_id = {} from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry # silly solution, but good enough # could handle the header entry 'Retry-After' for better manners # s = requests.Session() retries = Retry(total=3000, backoff_factor=1, status_forcelist=[ 502, 503, 504, 429 ]) s.mount('https://', HTTPAdapter(max_retries=retries)) for album_id in album_ids: url = "{}".format(album_id) headers = {'Authorization': "Bearer {}".format(TOKEN)} r = s.get(url, headers=headers) #TODO: check for error apart from dumb retries? parsed = json.loads(r.text) album_info = parsed #TODO: sanity checks? try: a = album_info["tracks"] except: print "Entry seems wrong. Fix it:" print album_info break album_info_by_id[album_id] = album_info
In this step, we actually care about the data quality, as mistakes might be more subtle than in previous steps. We want to get a snapshot of the album data, and really can’t have the data be incomplete or wrong for some reason. By trying to access the “tracks” field in each item we are making sure that the data is not formatted in a way we don’t expect. If unexpected stuff happen, we prefer to crash instead of quietly saving garbage.
API-related rate limits could be handled more graceful, but in our case it’s still relatively small and silly retries on expected errors are what we roll with. The total number of retries is limited to a still-large-but-not-huge number. Just in case.
Obviously, we really don’t want to be so lazy for really large requests or with many users.
Putting it All Together
After the previous chunk of code ran through without complaining, we have everything we need in our notebook for more elaborate tinkering. No more API requests are needed and we can work with the data we have. Neat-o!
This is a nice time to create a checkpoint :)
How do we handle the raw data? I really like to put convenient wrapper classes around the data entries. This way, we can perform basic tasks without giving them too much thought and keep the code readable.
For accessing album data and computing simple derived values, I created an “AlbumBin” class. It will provide information on all of the user’s tracks which are related to an individual album and accessors to raw album metainformation.
You can read up on the data we are working on, in the albums API endpoint docs.
class AlbumBin: def __init__(self, album_id, album_info): self.album_id = album_id self.album_info = album_info self.my_tracks = [] def add(self, song): self.my_tracks.append(song) def my_track_count(self): return len(self.my_tracks) def total_track_count(self): return len(self.album_info["tracks"]["items"]) def get_completeness_ratio(self): return (1.0 * self.my_track_count() / self.total_track_count()) def get_name(self): return self.album_info["name"] def get_artists(self): """ comma separated list of artists for pretty printing""" return ", ".join(map(lambda x: x["name"], self.album_info["artists"]))
So much for the data class. It can help us see how “complete” an album is (what the ratio of songs is, which is saved in the library), and straight-forward ways for getting the name of the album as well as the artists without caring about the underlying raw data structure. Now, we can create a binning of tracks (aka put tracks into album classes).
binning = {} # create album bins for album_id in album_ids: album_info = album_info_by_id[album_id] the_bin = AlbumBin(album_id, album_info) binning[album_id] = the_bin # fill album bins with songs for song in all_songs: album_id = song["track"]["album"]["id"] the_bin = binning.get(album_id) the_bin.add(song)
My naming is on the inconsistent side here - songs and tracks are pretty much interchangeable in my mind it seems.
Printing First Results - Terribly
This first one, is a part I’m not proud of. I could have been way lazier - but chose to copy-paste stuff tweaking the numbers instead of thinking for a bit. Originally I just wanted to get a grasp of the almost-completely-saved album counts, but later got interested in the complete distribution. Bear with me, we will handle this better with pandas. But first, here’s the copypaste bit for you to behold:
album_bins = binning.values() def fi(at_least, at_most): """ at_most is non-inclusive """ return filter(lambda x: at_least <= x.get_completeness_ratio() and at_most > x.get_completeness_ratio(), album_bins) album_count = len(album_bins) albums_100_percent = fi(1.0, 9000.0) albums_90_percent = fi(0.9, 1.0) albums_80_percent = fi(0.8, 0.9) albums_70_percent = fi(0.7, 0.8) albums_60_percent = fi(0.6, 0.7) albums_50_percent = fi(0.5, 0.6) albums_40_percent = fi(0.4, 0.5) albums_30_percent = fi(0.3, 0.4) albums_20_percent = fi(0.2, 0.3) albums_10_percent = fi(0.1, 0.2) albums_0_percent = fi(0.0, 0.1) print "Album count: {}".format(album_count) print "" print "Album count at/over 100%: {}".format(len(albums_100_percent)) print "Album count over 90% but under 100%: {}".format(len(albums_90_percent)) print "Album count over 80% but under 90%: {}".format(len(albums_80_percent)) print "Album count over 70% but under 80%: {}".format(len(albums_70_percent)) print "Album count over 60% but under 70%: {}".format(len(albums_60_percent)) print "Album count over 50% but under 60%: {}".format(len(albums_50_percent)) print "Album count over 40% but under 50%: {}".format(len(albums_40_percent)) print "Album count over 30% but under 40%: {}".format(len(albums_30_percent)) print "Album count over 20% but under 30%: {}".format(len(albums_20_percent)) print "Album count over 10% but under 20%: {}".format(len(albums_10_percent)) print "Album count over 0% but under 10%: {}".format(len(albums_0_percent))
URGH. Research code, right? It did what it was supposed to do, but it’s anything but good. One more function getting a list of arguments would have totally fixed this.
But why. We have a first impression of the “completeness” distribution of saved albums:
Album count: 1307 Album count over 100%: 172 Album count over 90% but under 100%: 5 Album count over 80% but under 90%: 1 Album count over 70% but under 80%: 0 Album count over 60% but under 70%: 2 Album count over 50% but under 60%: 23 Album count over 40% but under 50%: 8 Album count over 30% but under 40%: 25 Album count over 20% but under 30%: 90 Album count over 10% but under 20%: 236 Album count over 0% but under 10%: 745
There are a whopping 172 albums which are at 100%. This can be explained by single-song releases (singles). But I don’t think all of those are. Otherwise, I seem to be a picky listener. The albums at 50% or 30% might be worth revisiting, as they are either well-pruned or have potential to be just my type.
Printing and Visualizing Results - a bit better
Let’s pause for a moment, and look at how we could handle the distribution issue with pandas instead of lots of copy-pasted code.
There are many ways to visualize data in Pandas. For helping us understand the distribution, and maybe tell a story, a histogram would be nice. A box plot would make it very easy to understand the distribution a bit better.
Pandas feels really convenint for common data-crunching tasks. Just as R does. The code might look a bit daunting at first, but if you get into the topic, you’ll be comfortable in reading and writing this flavor of Python.
completeness_ratios = map(lambda x: x.get_completeness_ratio(), album_bins) df = pd.DataFrame(completeness_ratios) df.describe()
Basically, we create a list of “completeness ratios” for each album, and put it into a “data frame”. The ‘describe’ function outputs useful numbers to understand the distribution of the underlying data.
Simple, right? However, that’s not very intuitive and takes time to understand. Plots are better for this, and can be generated without much hassle:
ax = df.plot(kind='hist', title ="Album Completeness Histogram", figsize=(15, 10), legend=False, fontsize=12) ax.set_xlabel("Completenness Percent", fontsize=12) ax.set_ylabel("Album Count", fontsize=12) plt.show() ax = df.plot(kind='box', title ="Album Completeness Distribution Boxplot", figsize=(15, 10), legend=False, fontsize=12) ax.set_xlabel("All tracks in the user library", fontsize=12) ax.set_ylabel("Completeness Percent", fontsize=12) plt.show()
The results are two plots:
To get a bin-overview as in the code above, we can load off a huge chunk onto Pandas.
# originally I used #bins = list(range(0,101,10)) # but I wanted 100 to be a special case, so: bins = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99, 100] bin_labels = [] for i in range(len(bins)-1): bin_labels.append("({}, {}]".format(bins[i], bins[i+1])) bins = map(lambda x: x/100.0, bins) # results in bins (0, 10], so 0 is not included, but 10 is # this is different than our handling above, with [0, 10) # and results in different numbers df["bins"] = pd.cut(df[0], bins, labels=bin_labels) print df["bins"].groupby(df["bins"]).count()
The output looks as you would expect:
Alright, back on track.
List of Albums Which Are Completely Saved - Ready For Pruning
With our list of albums, and easy way to compute completeness ratios, we can just filter the albums for every entry which is
- Not from an one-song album
- Completely saved in the library
With a bit of sorting based on track count, we get the information I was interested in originally:
albs = fi(1.0, 9000.0) albs_big = filter(lambda x: x.total_track_count()!=1, albs) albs_big.sort(key=lambda x: -x.total_track_count()) for a in albs_big: print u"[{tracks_total}] '{name}' - {artists}".format( name=a.get_name(), tracks_total=a.total_track_count(), artists=a.get_artists())
The top part of the results (of 48 non-single-albums):
[32] 'Zirkus Zeitgeist (Deluxe)' - Saltatio Mortis [24] 'Meet The EELS: Essential EELS 1996-2006 Vol. 1' - Eels [23] 'Подмосковные вечера (Имена на все времена)' - Владимир Трошин [21] 'Great Divide (Deluxe Version)' - Twin Atlantic [20] 'Opposites (Deluxe)' - Biffy Clyro [20] 'Holy Wood [International Version (UK)]' - Marilyn Manson [18] 'Come What[ever] May' - Stone Sour
That’s way more than I expected. And in the very first results are some entries I’d rather not keep around in their entirety. Hooray! That’s all the actionable information I needed to begin pruning.
Just How Many Songs From Complete Albums Are in my Library?
Easy to answer. Interesting to know.
count_of_songs_on_albums = sum(map(lambda x: x.my_track_count(), albs_big)) print "Songs from 'complete' albums: {}".format(count_of_songs_on_albums) print "Total number of songs: {}".format(count_songs) percentage = 100.0*count_of_songs_on_albums/count_songs print "Percent: {:.2f}%".format(percentage)
Turns out, it’s quite a lot:
Songs from 'complete' albums: 652 Total number of songs: 2416 Percent: 26.99%
Over one fourth. Alright, that’s why I started noticing. That took a while.
Conclusion
After a bit of coding, I got all the answers I was interested in. My Spotify library can use a bit of cleaning up, and I’m really looking forward to improve my all-random listening enjoyment.
Python spiced with Jupyter and other helpful modules is great to tinkering with data. Requests + Pandas are amazing libraries, which you should add to your arsenal if you’re working with data. Pandas did not really shine here, I think it deserves its own article with a few harder questions to justify its use and demonstrate its full potential. Do you have an idea about an interesting way to look at the data, or a question you’d be interested in answering? Just drop me a mail :) Also, the Spotify API is cool and well documented.
As mentioned in the beginning if you enter your favourite email in the form below, I’ll send you the Jupyter notebook I used (sans secrets and data), so you can plug your own token in, get results for your account and have a good starting point to begin exploring the data. Regarding the token-getting-app-business: working on the article soon, stay tuned for more.
Thanks a lot for reading. I’d be thrilled to hear from you! If you have any questions, remarks or cool projects in mind just write me a mail. | https://vsupalov.com/analyze-spotify-music-library-with-jupyter-pandas/ | CC-MAIN-2017-39 | refinedweb | 3,945 | 65.42 |
The.
CTRL+Q opens the quick launch so you can search an indexed list of every feature available in Visual Studio. For example, If you want to do add a new item, use the quick launch to with that as your search term and receive guidance on how to do that.
In Visual Studio, users can apply Quick Launch to instantly explore and complete activities for IDE as elements like templates, options, and menus. One thing to remember is that users can’t apply Quick Launch to explore for code and figures.
With a lot of nested statements, it can be tough to keep track of opening and closing braces which, if missing, can cause compiler errors. Use CTRL+ ] to find the matching closing brace of a function or class and reduce the chance of falling prey to annoying error messages.
Sometimes making code work comes at the expense of making it look good. Proper indentation and spacing make code readable and that’s how CTRL+K+F works. Just highlight the section you need to format and it cleans up sloppy coding like magic.
For loops and if-then conditions have a standard structure that’s tedious to type over and over. To automate that process, you just need to type the beginning of your condition. For example, type ‘Try,’ hit the TAB key twice, and you get access to the snippets that complete the condition for you down to the braces. All you have to do is modify the parameters and you’re good to go.
This shortcut combines three debugging Visual Studio code commands in one. CTRL+SHIFT+F5 lets you end the debugging session, rebuild it, and create a new debugging session.
Manually adding and removing ‘//’ is tedious especially, if you have a long piece of code you want to deactivate. CTRL+K+C is a quicker way to bulk comment. Just highlight the block and type the Visual Studio shortcuts. When you need to make those lines active again, highlight the block and use CTRL+K+U to uncomment.
You can also use Ctrl+Shift+/ for toggling. The toggling can be used for block comments because Ctrl+/ is a shortcut for toggling line comments and block comments. To execute this, click on the settings and then click ‘Keyboard Shortcuts’. Here you will see a “toggle block.” Now, click and enter your combination.
Having multiple screens open helps you multitask. But if you want to focus on one section, going full screen used to mean losing important panels like the menu bar. ALT+SHIFT+ENTER lets you go full screen, but you retain access to your menu and panels. Another benefit is that you gain access to another four to 10 extra lines of code, depending on your screen resolution.
You’ve got your TRY-CATCH or IF loop structure but still need some code to put inside. Use Ctrl+K+S to open up a contextual menu from which you can choose the snippets you need to populate your condition.
Bookmarks help you keep track of the special markers in your code. For example, if there’s a function that you’re constantly referring to, CTRL+K+K marks that line with a little dot at the left. Additionally, use CTRL+K+N to cycle to the next bookmark in the list and CTRL+K+P for previous bookmarks. Just remember that the bookmark tags the line of the code, not the code itself.
The Clipboard Ring is a Visual Studio feature that allows copying multiple code blocks and pasting them. Users can copy various lines of code and put them in the clipboard. These lines of code can then be pasted when required. This improves development productivity. The copied code is stored in a memory, and users can use them in IDE.
CTRL+C allows you to keep the last 15 copied pieces of content in the clipboard. CTRL+SHIFT+V gives you access to this clipboard ring where you can scroll through the list of copied lines until you find the one you want to paste.
If your code file is too long and you want to make it more manageable, consider minimizing it with CTRL+M+M Visual Studio code shortcut keys. Just select the whole file and use this hotkey to collapse all functions to the most basic view. You can re-expand a specific section to see what you want. You can also use CTRL+M+O to collapse to the definition level, which may be a more useful view.
You have a code block and want to edit an event so that it’s reflected throughout the other lines in the block. Instead of changing each line individually, hold ALT then click and drag to highlight that block. Type the change you want and you’ll see all selected lines change at once.
In Microsoft, visual studio users can choose a block of text by pressing down the Alt key when choosing code and text with the mouse. This is particularly helpful for selecting a string of data or code as opposed to the whole line.
These Microsoft Visual Studio shortcuts are faster alternatives to copy-move-paste. To change the location of a certain block of code, highlight the lines then click ALT+↑(up arrow) to move all lines up at once or ALT+↓ (down arrow) to move all likes down.
In Visual Studio, users can use the Find All References to see where the required code details have referenced the codebase thoroughly. The Find All References is accessible on the context list or just press Shift + F12.
To see the instance of a class, hover over the name and hit F12. To see everywhere you’ve used that class, use SHIFT+F12.
These VS code hotkeys are absolutely necessary. Image, you’ve been scrolling down many lines of code and want to go back to some reference that’s 100 lines away. Instead of scrolling up or down to find that place, use CTRL+-(minus) to step backward through the navigation history, which shows everywhere, you’ve clicked and in the order, you clicked them. To go forward, use CTRL+SHIFT+-.
Check all Visual Studio hotkeys in this video tutorial:
The Build-in Microsoft visual studio means compile and connect only the root files that have been modified since the previous build. The Rebuild feature in Microsoft Visual studio means compile and connect all root files despite whether they changed or not.
CTRL+SHIFT+B is a quicker way to build a solution.
Use these Visual Studio keyboard shortcuts if you want to create a new task, for example. Type the word ‘task’ and use CTRL+. (dot) to see a menu. Press enter and you’ll see the namespace appear. Autocomplete helps with any coding issues, such as maintaining naming conventions.
You do a build and find that you didn’t name a property properly. Instead of hunting for every reference, click on the variable and use CTRL+R+R. This hotkey will not only rename the property but also change the name wherever it’s referenced. When you click Apply, you’ll see all the references it will rename.
These Visual Studio hotkeys can be useful when you’re debugging. If you want to step into a function as far as it can go and not just move to the next line, press F11 to jump into the constructor.
Always remember that it doesn’t work if you are debugging a static constructor. If not, then it works as usual. For this, the constructor is only called the once. So, before the class is accessed for the first time always make sure that the debugger is attached to it.
When you see the light bulb, it means there’s an easier action to take. You can take advantage of the hotkey shortcuts. For example, if you have unused USING statements or if you want to add a clause, ALT+ ENTER will get rid of unnecessary statements as well as add that recommended snippet to your clause.
Visual Studio contains a characteristic that enables users to add a bookmark. This bookmark can be added to a line of code in a solution. As with a regular bookmark that instantly enables users to go back to the last place, the Visual Studio allows users to immediately find a labeled line in the code. Users can generate many bookmarks and they can instantly navigate between them. Now, to remove this bookmark we have a shortcut key Ctrl+K.
These Visual Studio code hotkeys are useful for removing the syntax of the comment from the prevailing line or currently marked lines of code. For example, if you are using the code editor and you want to remove the already written syntax of comments then Ctrl-K comes under the text manipulation Visual Studio keyboard shortcuts.
This key is the part of project-related shortcuts. For example, you are using a Microsoft Visual Studio and you have developed a new project called “MyProject”. Now, if you want to open this project in the code editor then Ctrl+Shift+O can be used. The project Visual Studio code shortcut keys are very useful if you are working on a big project and repositories.
This shortcut key is also the part of project-related Visual Studio shortcut keys. For example, if you want to override base class methods. Now, you want to achieve this in an already derived class when an overridable method is called. To execute this in the Class View pane you can use Ctrl+Alt+Insert key.
This shortcut key is the part of Search and replaces related Visual Studio hotkeys. This hotkey starts an incremental search. After pressing Ctrl+I, the user can insert the text. Once the text has been entered, this key will help in finding the text and the related pattern. The search and replace Visual Studio keyboard shortcuts are useful in finding various codes and comments from the code editor.
This shortcut key is also the part of Search and replaces related Visual Studio code shortcuts. This key is used for selecting or clearing the Regular Expression option. With the help of Alt+F3, R the special characters can be used in the Find and Replace methods.
This key is the part of Debugging related Visual Studio commands. This shortcut key displays the Memory 1 window to observe memory in the method being debugged. This is especially beneficial when you do not have debugging figures ready for the code. It is also important for studying at large buffers.
This key is the part of Object browser-related Microsoft Visual Studio shortcuts. This displays the Object Browser to inspect the classes, attributes, processes, events, and constants specified either in the project or by elements and sample libraries referenced by the project.
In the visual studio, the Tool window is a child window of the integrated development environment. The IDE is used to display various information. Each view includes two tool window collections. These are known as primary, the secondary. In this, only one tool window from each collection or group can be active.
This shortcut key is the part of Tool window related commands. This switches the window inside or out of a method enabling text inside the window to be chosen.
This key is the part of Windows manipulation related Visual Studio code shortcut keys. It allows moving to the next tab in the document or window. For example, if you can switch the HTML editor from its design view to HTML view.
Visual Studio enables users to create cursors. In Visual Studio, users can create a cursor file. This File is a bitmap file with . cur extension. For creating this file, just right click on the selected project and select Add New Item. Now, select Cursor File and this will create a .cur file.
This shortcut key is the part of General Visual Studio code commands. This key moves the cursor to the preceding item, for instance in the TaskList window or Find Results window.
This hotkey displays the Solution Explorer. The solution explorer is responsible for listing the projects and files in the current solution of the project. The solution explorer is a window that allows users to explore and maintain all projects.
This hotkey displays the Toolbox. The toolbox is an important component of VS. It includes controls and other objects that can be moved into editor window and designer windows. Many controls can be easily added to the projects with the help of a toolbox.
This hotkey displays the property pages for the objects and controls currently selected. For instance, one can use Shift+F4 to display a project’s settings and many other such properties. Users can modify and see the configuration by using this hotkey.
This hotkey is used to display the web browser window in the Visual Studio. The Ctrl+Alt+R enables users to view or monitor various web pages on the Internet.
This hotkey is used to display the Macro Explorer window. It lists all available macros. Macros allow users to automate repetitive tasks in the IDE. The Alt+F8 is one of the important hotkeys in Visual Studio.
The Ctrl+Shift+G is used to define the elements to be adjusted by utilizing a hidden grid. The grid spacing can be configured on the Design pane of HTML designer and the grid will automatically adjust itself the next time users open a document.
This Visual Studio hotkey is used to display the bookmark dialog. Users can use bookmarks to identify or point particular code lines to comment on important messages or to quickly return to a particular location. The Ctrl+K shortcut is used to add a bookmark.
The Ctrl+F9 enables or disables the breakpoint. It is used to define the breakpoint on the current line of code. It is one of the handy hotkeys of Visual Studio.
The F5 hotkey is used to debug the application. It is used to run the application in the debugger mode and it displays what the code is doing when it runs. On the other hand, the ctrl + F5 hotkey is used to execute the application without the debugger.
This Visual Studio shortcut comes under window management hotkeys. It is used to open the immediate window. The immediate window enables communication with parameters and variables when the written program is in the debug mode. It allows the modification and inspection of the variables or parameters of the written code.
This hotkey is widely used by developers for checking things. This hotkey allows developers to navigate to the subsequent description, information, or reference of an object. It is accessible in the object browser and Class View window. It is also accessible in source editing windows with the Shift+F12 shortcut.
It is one of the most widely used hotkeys. This hotkey is also used to invoke the View.BrowseNext. It comes under the View section of Visual Studio hotkeys. The hotkey Ctrl+Shift+2 is used to invoke the View.BrowsePrevious. In short, it comes under the View class and also called a navigation shortcut.
This hotkey is used to invoke the CrossAppDomainDelegate. It is used to executes the code in a different application domain that is recognized by the named delegate. It is used in the system namespace and it is a part of mscorlib.dll assembly. This hotkey is also used to invoke the AppDomain.DoCallBack(CrossAppDomainDelegate) method. Every application domain has appdomain variable.
In this, a constructor is launched when an attachment is packed into an application domain, and the destructor is launched when the application domain is relieved. The appdomain variable describes an application domain, which is a private setting where applications perform. This class cannot be derived.
The hotkey “S” is used to invoke Stackalloc. It is used to allocate a block of memory on the stack. A block built through the method execution is implicitly abandoned when that method echoes. Users cannot explicitly release the memory designated with stackalloc. A stack-allocated memory block is not related to garbage collection and doesn’t have to be bound with a fixed statement.
The method of stackalloc implicitly allows buffer overrun discovery characteristics in the typical (common) language runtime (CLR). If a buffer overrun is identified, the method is stopped as promptly as possible to reduce the risk that malicious code is performed.
The A+B hotkey is used to invoke the AccessViolationException. An access violation happens in unmanaged or insecure code when the code tries to write to memory that has not been designated, or to which it does not have a path.
This normally happens because a pointer has the wrong value. Not all writes within wrong pointers point to access infractions, so an access violation normally means that some reads or writes have transpired into bad pointers, and that memory might be damaged. Thus, access violations almost invariably mean severe coding errors. An AccessViolationException explicitly recognizes these grave errors.
This hotkey is used to invoke the Console.WriteLine Method. It is used to write the defined data, supported by the prevailing line terminator, to the regular output stream. It can be used with various parameters. It is also used to write the text descript ion of the defined objects, supported by the prevailing line terminator, to the regular output utilizing the designated format data.
The default line terminator is a line whose purpose is a position return accompanied by a line feed. You can adjust the line terminator by placing the TextWriter.NewLine section of the Out section to a different string. | https://bytescout.com/blog/visual-studio-hot-keys.html | CC-MAIN-2021-10 | refinedweb | 2,951 | 65.01 |
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.
on_change in xml in odoo
how to pass two values in the on_change method in odoo 8 ?
like below
<field name='test' on_change="get_func(test,'string')"/>
You can use the following method for implementing on_change method multiple fields with just one function.The fields must be in the same model.
in xml:
#in xml
<field name='test' on_change="get_func(test,'string')"/>
#and in python use
@api.multi
def get_func(self,value,field):
""here you can compare the field name and exec the desired lines using the if """
Hello Nikhil,
As per odoo 8 api you can directly set on-change method using @api.onchange no need to set into XML.
Example:
@api.onchange('name')
def onchange_name(self):
self.name = 'what you want to save'
This function will execute when name field change.
Hope this helps.
can i pass 2 arguments in this methnod?
Why do you need to pass argument? because all fields of that model access directly in self... like. self.field name
@api.onchange('staff_fname', 'staff_lname')
def funa(self):
if self.staff_fname and self.staff_lname:
s=(self.staff_fname or '') + (self.staff_lname or '')
self.staff_name = s.strip()
In this onchange function is execute when first anem and last anme are specified in your view.
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/on-change-in-xml-in-odoo-104728 | CC-MAIN-2018-47 | refinedweb | 260 | 69.58 |
#include <??>
void qadd<size> (void , int; void qsub<size> (void , int; void qand<size> (void , int; void qxchg<size> (void , int; void qor<size> (void , int; void qbts<size> (void , int; void qinc<size>(void ); void qdec<size>(void ); void qzero<size>(void );
Bit test/set functions return the result of the test.
Quick locks with two parameters -- qaddl(void,long)
Quick locks with one parameter --qincl(void)
Bit test/set locks
These routines use the 80*86 lock prefix instruction to lock the bus during the execution of the instruction. They should be used whenever a simple atomic action is all that is required such as incrementing a counter. They have less impact on performance than other locks.
The qbts family of functions do an atomic test and set of a bit in a field of bits. This is useful for semaphores and similar operations. If more than one bit is specified in the second parameter, the qbts function will test and set the least bit requested and silently ignore any others. Use the qorl family if multiple bits need to be set.
These operations cannot be split by an interrupt because they are executed as a single assembler instruction.
``Atomic locks'' in HDK Technical Reference
qincl(&my_arg); qdecb(&my_arg2);Because a quick lock cannot be split up by an interrupt, the following two code fragments provide equivalent functionality, although the fragment on the right that uses qinc is more efficient:
qaddl(&my_arg, 3); qandb(&my_arg2, 0x40);
s=spl7(); qincl(&i); i++; splx(s);The following example illustrates the use of the qbts functions. This code references a buffer whose header has a bit that indicates whether the buffer is in use. The qbtsl function tests the bit, unconditionally sets it to mark that the buffer is busy, and returns the result of the test. On return, the bit is definitely set; the return value indicates whether this process "owns" the buffer or if someone else had it first.
#define IN_USE 1
int control_word; if (qbtsl(&control_word, IN_USE) ) { /* buffer was in_use, we cannot use it */ } else { /* buffer was free, now marked busy, we can use it */ } | http://osr600doc.xinuos.com/en/man/html.D3oddi/atomic.D3oddi.html | CC-MAIN-2022-21 | refinedweb | 357 | 56.08 |
Phoenix Select Form Helper
The
select form helper allows you to easily add a select input to your forms.
= form_for @changeset, resource_path(@conn, :create), fn f -> = select f, :book_id, @books = submit "Save Post", class: "btn"
Among the types of arguments that the
select helper can accept are two-item tuples. The first item in the tuple is used as the label for the option and the second item is used as the value for the option.
Media.list_books returns a list of structs representing all of the books in the database. We’ll need to get from a list of structs to a list of tuples.
To do that, we’ll pipe the list of
Book structs to
Enum.map and use an anonymous function to generate two-value tuples from those structs.
TweetTweet
def new(conn, _params) ... books = Media.list_books |> Enum.map(&{"#{&1.title} by #{&1.author}", &1.id}) render conn, "new.html", changeset: changeset, books: books end | https://til.hashrocket.com/posts/vikw0jg3hh-phoenix-select-form-helper | CC-MAIN-2019-09 | refinedweb | 159 | 75.1 |
Writing Comet Applications Using Scala and the Atmosphere Framework
Join the DZone community and get the full member experience.Join For Free
Writing Atmosphere's Comet based applications is simple. Imagine using Scala instead of Java...it becomes really simple! No need to learn Lift anymore :-)
Not being an expert with Scala at all, I've decided to re-wrote the Chat based application I've recently used when adding cluster support to Atmosphere. This is really my first ever Scala application so don't jump looking at the code! Instead, tweet me a better implementation. I will not go into the details of how to write an Atmosphere application, so if this is the first time you learn about Atmosphere, start here.
For the chat, I've needed to implement two methods: one that will be invoked when suspending a response (Comet's HTTP streaming technique), and one for sending chat messages to those suspended response (to the other chat member). To do that in Scala, I did:
package org.atmosphere.samples.scala.chat
import javax.ws.rs.{GET, POST, Path, Produces, WebApplicationException, Consumes}
import javax.ws.rs.core.MultivaluedMap
import org.atmosphere.core.annotation.{Broadcast, BroadcastFilter, Suspend}
import org.atmosphere.util.XSSHtmlFilter
@Path("/chat")
class Chat {
var JUNK : String = "<!-- Comet is a programming technique that enables web " +
"servers to send data to the client without having any need " +
"for the client to request it. -->\n"
@Suspend
@GET
@Produces(Array("text/html;charset=ISO-8859-1"))
def suspend() = {
var s = new StringBuilder()
for (i <- 0 to 10){
s.append(JUNK)
}
s.toString()
}
@Broadcast
@Consumes(Array("application/x-www-form-urlencoded"))
@Produces(Array("text/html"))
@BroadcastFilter(Array(classOf[XSSHtmlFilter],classOf[JsonpFilter]))
def publishMessage(form: MultivaluedMap[String, String]) = {
val action = form.getFirst("action")
val name = form.getFirst("name")
val result: String = if ("login".equals(action)) "System Message" + "__" + name + " has joined."
else if ("post".equals(action)) name + "__" + form.getFirst("message")
else throw new WebApplicationException(422)
result
}
}
To suspend the response, I've annotated the suspend() method (line 15) with @Suspend. The returned value of the suspend() method will be written and then the response will be suspended, waiting for server event, e.g messages from other chatter. Now when someone publish a message, method publishMessage() will be invoked. Since the method is annotated with @Broadcast (line 26), the method's returned value will be broadcaster to all suspended response, e.g. all suspended connections will get a chance to write the message. But since I don't want users to publish script or any kind of attack, I've also added the @BroadcastFilter annotation, which will make sure to filter malicious characters. Since my javascript client expect JSONp response, I've decided to write a BroadcastFilter in Scala that transform the message:
package org.atmosphere.samples.scala.chat
import org.atmosphere.cpr.BroadcastFilter
class JsonpFilter extends BroadcastFilter[String] {
val BEGIN_SCRIPT_TAG = "<script type='text/javascript'>\n"
val END_SCRIPT_TAG = "</script>\n"
def filter(m : String) = {
var name = m
var message = ""
if (m.indexOf("__") > 0) {
name = m.substring(0, m.indexOf("__"))
message = m.substring(m.indexOf("__") + 2)
}
val result: String = (BEGIN_SCRIPT_TAG + "window.parent.app.update({ name: \""
+ name + "\", message: \""
+ message + "\" });\n"
+ END_SCRIPT_TAG)
}
}
Then I just pass the name of that class to the @BroadcastFilter annotation:
@BroadcastFilter(Array(classOf[XSSHtmlFilter],classOf[JsonpFilter]))
What amaze me here is one filter is written in Java, the other one in Scala!. That's it. With those two classes, the Atmosphere REST Chat demo works. To complicate the application, I've decided to deploy it into a cluster. This is simple to achieve by annotating the publishMesaage with:
@Cluster(Array(classOf[JGroupsFilter]))
Now my Scala application is Comet-Cluster enabled! That was fun!
For any questions or to download the above sample, go to our main site and use our Nabble forum (no subscription needed) or follow us on Twitter and tweet your questions there!
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/writing-comet-applications | CC-MAIN-2021-43 | refinedweb | 657 | 50.12 |
To develop a scalable, distributed, well-presented, complex, and multi-layered enterprise application is complicated. The development becomes even worse if the developer is not well aware of the software development fundamentals. Instead of looking at a bigger scenario, if we cut it down into parts and later combine them, it becomes easy for understanding as well as for developing. Each technology has some basics which we cannot overlook. Rather, if we overlook them, it will be the biggest mistake; the same is applicable to Java EE. In this article by TejaswiniMandar Jog, author of the book Learning Modular Java Programming, we are going to explore the following:
- Java EE technologies
- Why servlet and JSP?
- Introduction to Spring MVC
- Creating a sample application through Spring MVC
(For more resources related to this topic, see here.)
The enterprise as an application
To withstand the high, competitive, and daily increasing requirements, it's becoming more and more difficult nowadays to develop an enterprise application. The difficulty is due to more than one kind of service, requirement of application to be robust and should support concurrency, security, and many more. Along with these things, enterprise applications should provide an easy user interface but good look and feel for different users.
In the last article, we discussed enterprise applications. The discussion was more over understanding the terminology or the aspect. Let's now discuss it in terms of development, and what developers look forward to:
- The very first thing even before starting the development is: what we are we developing and why? Yes, as a developer we need to understand the requirements or the expectations from the application. Developers have to develop an application which will meet the requirements.
- The application should be efficient and with high quality so as to sustain in the market.
- The application code should be reliable and bug-free to avoid runtime problems.
- No application is perfect; it's a continuous process to update it for new demands. Develop an application in such a way that it is easy to update.
- To meet high expectations, developers write code which becomes complicated to understand as well as to change. Each one of us wants to have a new and different product, different from what is on the market. To achieve this, designers make an over-clumsy design which is not easy to change in the future. Try to avoid over-complexity both in design and business logic.
- When development starts, developers look forward to providing a solution, but they have to give thought to what they are developing and how the code will be organized in terms of easy maintenance and future extension. Yes, we are thinking about modules which are doing a defined task and those which are less dependent. Try to write a module which will be loosely coupled and highly cohesive.
- Today we are using enterprise applications through different browsers, such as Internet Explorer, Mozilla, or Firefox. We are even using mobile browsers for the same task. This demands an application that has been developed to withstand the number of platforms and browsers.
Going through all this discussion, many technologies come to mind. We will go through one such platform which covers the maximum of the above requirements: the Java Enterprise Edition (Java EE) platform. Let's dive in and explore it!!
The Java EE platform
Sun Microsystems released the Java EE platform in 2000, which was formerly known as the J2EE specification. It defines the standards for developing component-based enterprise applications easily. The concrete implementation is provided by application servers such as Weblogic and GlassFish, and servlet containers such as Tomcat. Today we have Java EE 8 on the market.
Features of the Java EE platform
The following are the various features of the Java EE platform:
- Platform independency: Different types of information which the user needs in day-to-day life is spread all over the network on a wide range of platforms. Java EE is well adapted to support, and use this widely spread multiple format information on different platforms easily.
- Modularity: The development of enterprise applications is complex and needs to be well organized. The complexity of the application can be reduced by dividing it into different, small modules which perform individual tasks, which allows for easy maintenance and testing. They can be organized in separate layers or tiers. These modules interact with each other to perform a business logic.
- Reusability: Enterprise applications need frequent updates to match up client requirements. Inheritance, the fundamental aspect of an object-oriented approach, offers reusability of the components with the help of functions. Java EE offers modularity which can be used individually whenever required.
- Scalability: To meet the demands of the growing market, the enterprise application should keep on providing new functionalities to the users. In order to provide these new functionalities, the developers have to change the application. They may add new modules or make changes in already existing ones. Java EE offers well-managed modules which make scalability easy.
The technologies used in Java EE are as follows:
- Java servlet
- Java Server Pages
- Enterprise Java Bean
- Java Messaging API
- XML
- Java Transaction API
- Java Mail
- Web Services
The world of dotcoms
In the 1990s, many people started using computers for a number of reasons. For personal use, it was really good. When it came to enterprise use, it was helpful to speed up the work. But one main drawback was; how to share files, data or information? The computers were in a network but if someone wanted to access the data from any computer then they had to access it personally. Sometimes, they had to learn the programs on that computer, which is not only very time-consuming but also unending.
What if we can use the existing network to share the data remotely?? It was a thought put forward by a British computer scientist, Sir Tim Berners-Lee. He thought of a way to share the data through the network by exploring an emerging technology called hypertext. In October 1990, Tim wrote three technologies to fulfill sharing using Hyper Text Markup Language (HTML), Uniform Resource Identifier (URI), and Hyper Text Transfer Protocol (HTTP):
- HTML is a computer language which is used in website creation. Hypertext facilitates clicking on a link to navigate on the Internet. Markups are HTML tags defining what to do with the text they contain.
- URIs defines a resource by location or name of resource, or both. URIs generally refer to a text document or images.
- HTTP is the set of rules for transferring the files on the Web. HTTP runs on the top of TCP/IP.
He also wrote the first web page browser (World Wide Webapp) and the first web server (HTTP). The web server is where the application is hosted. This opened the doors to the new amazing world of the "dotcom". This was just the beginning and many more technologies have been added to make the Web more realistic. Using HTTP and HTML, people were able to browse files and get content from remote servers. A little bit of user interaction or dynamicity was only possible through JavaScript. People were using the Web but were not satisfied; they needed something more. Something which was able to generate output in a totally dynamic way, maybe displaying the data which had been obtained from the data store. Something which can manipulate user input and accordingly display the results on the browser.
Java developed one technology: Common Gateway Interface (CGI). As CGI was a small Java program, it was capable of manipulating the data at the server side and producing the result. When any user made a request, the server forward the edit to CGI, which was an external program. We got an output but with two drawbacks:
- Each time the CGI script was called, a new process was created. As we were thinking of a huge number of hits to the server, the CGI became a performance hazard.
- Being an external script, CGI was not capable of taking advantage of server abilities.
To add dynamic content which can overcome the above drawbacks and replace CGI, the servletwas developed by Sun in June 1997.
Servlet – the dynamicity
Servlets are Java programs that generate dynamic output which will be displayed in the browser and hosted on the server. These servers are normally called servlet containers or web servers. These containers are responsible for managing the lifecycle of the servlets and they can take advantage of the capabilities of servers. A single instance of a servlet handles multiple requests through multithreading. This enhances the performance of the application. Let's discuss servlets in depth to understand them better.
The servlet is capable of handling the request (input) from the user and generates the response (output) in HTML dynamically. To create a servlet, we have to write a class which will be extended from GenericServlet or HttpServlet. These classes have service() as a method, to handle request and response. The server manages the lifecycle of a servlet as follows:
The servlet will be loaded on arrival of a request by the servers.
The instance will be created.
The init() will be invoked to do the initialization.
The preceding steps will be performed only once in the life cycle of the servlet unless the servlet has not been destroyed.
After initialization, the thread will be created separately for each request by the server, and request and response objects will be passed to the servlet thread.
The server will call the service() function.
The service() function will generate a dynamic page and bind it to the HttpResponse object.
Once the response is sent back to the user, the thread will be deallocated.
From the preceding steps, it is pretty clear that the servlet is responsible for:
- Reading the user input
- Manipulating the received input
- Generating the response
A good developer always keeps a rule of thumb in mind that a module should not have more than one responsibility, but here the servlet is doing much more. So this has addressed the first problem in testing the code, maybe we will find a solution for this. But the second issue is about response generation. We cannot neglect a very significant problem in writing well-designed code to have a nice look and feel for the page from the servlet. That means a programmer has to know or adapt designing skills as well, but, why should a servlet be responsible for presentation?
The basic thought of taking presentation out of the servlet leads to Java Server Page (JSP). JSP solves the issue of using highly designed HTML pages. JSP provides the facility of using all HTML tags as well as writing logical code using Java. The designers can create well-designed pages using HTML, where programmers can add code using scriptlet, expression, declaration, or directives. Even standard actions like useBean can be used to take advantage of Java Beans. These JSP's now get transformed, compiled into the servlet by the servers.
Now we have three components:
- Controller, which handles request and response
- Model, which holds data acquired from handling business logic
- View, which does the presentation
Combining these three we have come across a design pattern—Model-View-Controller (MVC). Using MVC design patterns, we are trying to write modules which have a clear separation of work. These modules can be upgradable for future enhancement. These modules can be easily tested as they are less dependent on other modules. The discussion of MVC is incomplete without knowing two architectural flavors of it:
- MVC I architecture
- MVC II architecture
MVC I architecture
In this model, the web application development is page-centric around JSP pages. In MVC I, JSP performs the functionalities of handling a request and response and manipulating the input, as well as producing the output alone. In such web applications, we find a number of JSP pages, each one of them performing different functionalities. MVC I architecture is good for small web applications where less complexity and maintaining the flow is easy. The JSP performs the dual task of business logic and presentation together, which makes it unsuitable for enterprise applications.
MVC I architecture
MVC II architecture
In MVC II, a more powerful model has been put forward to give a solution to enterprise applications with a clear separation of work. It comprises two components: one is the controller and other the view, as compared to MVC I where view and controller is JSP (view). The servlets are responsible for maintaining the flow (the controller) and JSP to present the data (the view). In MVC II, it's easy for developers to develop business logic- the modules which are reusable. MVC II is more flexible due to responsibility separation.
MVC II architecture
The practical aspect
We have traveled a long way. So, instead of moving ahead, let's first develop a web application to accept data from the user and display that using MVC II architecture. We need to perform the following steps:
Create a dynamic web application using the name Ch02_HelloJavaEE.
Find the servlet-api.jar file from your tomcat/lib folder. Add servlet-api.jar to the lib folder.
Create index.jsp containing the form which will accept data from the user.
Create a servlet with the name HelloWorldServlet in the com.packt.ch02.servlets package.
Declare the method doGet(HttpServletRequestreq,HttpServletResponsers) to perform the following task:
Read the request data using the HttpServletRequest object.
Set the MIME type.
Get an object of PrintWriter.
Perform the business logic.
Bind the result to the session, application or request scope.
Create the view with name hello.jsp under the folder jsps.
Configure the servlet in deployment descriptor (DD) for the URL pattern.
Use expression language or Java Tag Library to display the model in the JSP page.
Let's develop the code.
The filesystem for the project is shown in the following screenshot:
We have created a web application and added the JARs. Let's now add index.jsp to accept the data from the user:
<form action="HelloWorldServlet"> <tr> <td>NAME:</td> <td><input type="text" name="name"></td> </tr> <tr> <td></td> <td><input type="submit" value="ENTER"></td> </tr> </form>
When the user submits the form, the request will be sent to the URL HelloWorldServlet.
Let's create the HelloWorldServlet which will get invoked for the above URL, which will have doGet(). Create a model with the name message, which we will display in the view. It is time to forward the request with the help of the RequestDispatcher object. It will be done as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //read the request parameter String name=request.getParameter("name"); //get the writer PrintWriter writer=response.getWriter(); //set the MIME type response.setContentType("text/html"); // create a model and set it to the scope of request request.setAttribute("message","Hello "+name +" From JAVA Enterprise"); RequestDispatcher dispatcher=request.getRequestDispatcher("jsps/hello.jsp"); dispatcher.forward(request, response); }
Now create the page hello.jsp under the folder jsps to display the model message as follows:
<h2>${message }</h2>
The final step is to configure the servlet which we just have created in DD. The configuration is made for the URL HelloWorldServlet as follows:
<servlet> <servlet-name>HelloWorldServlet</servlet-name> <servlet-class>com.packt.ch02.servlets.HelloWorldServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldServlet</servlet-name> <url-pattern>/HelloWorldServlet</url-pattern></servlet-mapping>
Let's deploy the application to check the output:
Displaying the home page for a J2EE application
The following screenshot shows the output when a name is entered by the user:
Showing the output when a name is entered by the user
After developing the above application, we now have a sound knowledge of how web development happens, how to manage the flow, and how navigation happens. We can observe one more thing: that whether it's searching data, adding data, or any other kind of operation, there are certain steps which are common, as follows:
- Reading the request data
- Binding this data to a domain object in terms of model data
- Sending the response
We need to perform one or more of the above steps as per the business requirement. Obviously, by only performing the above steps, we will not be able to achieve the end effect but there is no alternative. Let's discuss an example.
We want to manage our contact list. We want to have the facilities for adding a new contact, updating a contact, searching one or many contacts, and deleting a contact. The required data will be taken from the user by asking them to fill in a form. Then the data will be persisted in the database.
Here, for example, we just want to insert the record in the database. We have to start the coding from reading request data, binding it to an object and then our business operation. The programmers have to unnecessarily repeat these steps. Can't they get rid of them? Is it possible to automate this process?? This is the perfect time to discuss frameworks.
What is a framework?
A framework is software which gives generalized solutions to common tasks which occur in application development. It provides a platform which can be used by the developers to build up their application elegantly.
Advantages of frameworks
The advantages of using frameworks are as follows:
- Faster development
- Easy binding of request data to a domain object
- Predefined solutions
- Validations framework
In December 1996, Sun Microsystems published a specification for JavaBean. This specification was about the rules, using which developers can develop reusable, less complex Java components. These POJO classes are now going to be used as a basis for developing a lightweight, less complex, flexible framework: the Spring framework. This framework is from the thoughts of Rod Johnson in February 2003. The Spring framework consists of seven modules:
Spring modules
Though Spring consists of several modules, the developer doesn't have to be always dependent on the framework. They can use any module as per the requirement. It's not even compulsory to develop the code which has been dependent upon Spring API. It is called a non-intrusive framework. Spring works on the basis of dependency injection (DI), which makes it easy for integration. Each class which the developer develops has some dependencies. Take the example of JDBC: to obtain a connection, the developer needs to provide URL, username, and password values. Obtaining the connection is dependent on these values so we can call them dependencies, and injection of these dependencies in objects is called DI. This makes the emerging spring framework the top choice for the middle tier or business tier in enterprise applications.
Spring MVC
The spring MVC module is a choice when we look forward for developing web applications. The spring MVC helps to simplify development to develop a robust application. This module can also be used to leave common concerns such as reading request data, data binding to domain object, server-side validation and page rendering to the framework and will concentrate on business logic processes.
That's what, as a developer we were looking for. The spring MVC can be integrated with technologies such as Velocity, Freemarker, Excel, and PDF. They can even take advantage of other services such as aspect-oriented programming for cross-cutting technologies, transaction management, and security provided by the framework.
The components
Let's first try to understand the flow of normal web applications in view of the Spring framework so that it will be easy to discuss the component and all other details:
On hitting the URL, the web page will be displayed in the browser.
The user will fill in the form and submit it.
The front controller intercepts the request.
The front controller tries to find the Spring MVC controller and pass the request to it.
Business logic will be executed and the generated result is bound to the ModelAndView.
The ModelAndView will be sent back to the front controller.
The front controller, with the help of ViewResolver, will discover the view, bind the data and send it to the browser.
Spring MVC
The front controller
As already seen in servlet JSP to maintain each flow of the application the developer will develop the servlet and data model from servlet will be forwarded to JSP using attributes. There is no single servlet to maintain the application flow completely. This drawback has been overcome in Spring MVC as it depends on the front controller design pattern.
In the front controller design pattern, there will be a single entry point to the application. Whatever URLs are hit by the client, it will be handled by a single piece of the code and then it will delegate the request to the other objects in the application.
In Spring MVC, the DispatcherServlet acts as front controller. DispatcherServlet takes the decision about which Spring MVC controller the request will be delegated to. In the case of a single Spring MVC controller in the application, the decision is quite easy. But we know in enterprise applications, there are going to be multiple Spring MVC controllers. Here, the front controller needs help to find the correct Spring MVC controller. The helping hand is the configuration file, where the information to discover the Spring MVC controller is configured using handler mapping. Once the Spring MVC controller is found, the front controller will delegate the request to it.
Spring MVC controller
All processes, such as the actual business logic, decision making or manipulation of data, happen in the Spring MVC controller. Once this module completes the operation, it will send the view and the model encapsulated in the object normally in the form of ModelAndView to the front controller. The front controller will further resolve the location of the view. The module which helps front controller to obtain the view information is ViewResolver.
ModelAndView
The object which holds information about the model and view is called as ModelAndView. The model represents the piece of information used by the view for display in the browser of different formats.
ViewResolver
The Spring MVC controller returns ModelAndView to the front controller. The ViewResolver interface helps to map the logical view name to the actual view. In web applications, data can be displayed in a number of formats, from as simple as JSP to complicated formats like JasperReport. Spring provides InternalResourceViewResolver, JspViewResolver, JasperReportsViewResolver, VelocityLayoutViewResolver, and so on, to support different view formats.
The configuration file
DispatcherServlet needs to discover information about the Spring MVC controller, ViewResolver, and many more. All this information is centrally configured in a file named XXX-servlet.xml where XXX is the name of the front controller. Sometimes the beans will be distributed across multiple configuration files. In this case, extra configuration has to be made, which we will see later in this article.
The basic configuration file will be:
<beans xmlns="" xmlns: <!—mapping of the controller --> <!—bean to be configured here for view resolver - -> </beans>
The controller configuration file will be named name_of_servlet-servlet.xml. In our project, we will name this HelloWeb-servlet.xml.
Let's do the basics of a web application using Spring MVC to accept the data and display it. We need to perform the following steps:
Create a web application named Ch02_HelloWorld.
Add the required JAR files for Spring (as shown in the following screenshot) and servlets in the lib folder.
Create an index page from where the data can be collected from the user and a request sent to the controller.
Configure the front controller in DD.
Create a SpringMVCcontroller as HelloWorldController.
Add a method for accepting requests in the controller which performs business logic, and sends the view name and model name along with its value to the front controller.
Create an XML file in WEB-INF as Front_Controller_name-servlet.xml and configure SpringMVCcontroller and ViewResolver.
Create a JSP which acts as a view to display the data with the help of Expression Language (EL) and Java Standard Tag Library (JSTL).
Let's create the application.
The filesystem for the project is as follows:
We have already created the dynamic web project Ch02_HelloSpring and added the required JAR files in lib folder. Let's start by creating index.jsp page as:
<form action="hello.htm"> <tr> <td>NAME:</td> <td><input type="text" name="name"></td> </tr> <tr> <td></td> <td><input type="submit" value="ENTER"></td> </tr> </form>
When we submit the form, the request is sent to the resource which is mapped for the URL hello.htm. Spring MVC follows the front controller design pattern. So all the requests hitting the application will be first attended by the front controller and then it will send it to the respective Spring controllers.
The front controller is mapped in DD as:
<servlet> <servlet-name>HelloSpring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloSpring</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
Now the controller needs help to find the Spring MVC controller. This will be taken care of by the configuration file. This file will have the name XXX-servlet.xml where XXX is replaced by the name of the front controller from DD. Here, in this case HelloSpring-servlet.xml will have the configuration. This file we need to keep in the WEB-INF folder. In the Configuration files section, we saw the structure of the file. In this file, the mapping will be done to find out how the package in which the controllers are kept will be configured. This is done as follows:
<context:component-scan
Now the front controller will find the controller from the package specified as a value of base-package attribute. The front controller will now visit HelloController. This class has to be annotated by @Controller:
@Controller public class HelloController { //code here }
Once the front controller knows what the controller class is, the task of finding the appropriate method starts. This will be done by matching the values of @RequestMapping annotation applied either on the class or on the methods present in the class. In our case, the URL mapping is hello.htm. So the method will be developed as:
@RequestMapping(value="/hello.htm") publicModelAndViewsayHello(HttpServletRequest request) { String name=request.getParameter("name"); ModelAndView mv=new ModelAndView(); mv.setViewName("hello"); String message="Hello "+name +" From Spring"; mv.addObject("message",message); return mv; }
This method will return a ModelAndView object which contains a view name, model name and value for the model. In our code the view name is hello and the model is presented by message. The Front Controller now again uses HelloSpring-servlet.xml for finding the ViewResolver to get the actual name and location of the view. ViewResolver will provide the directory name (location) where the view is placed with a property prefix. The format of the view is given by the property suffix. Using the view name, prefix and suffix, the front controller gets the page. The ViewResolver will bind the model to be used in the view:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/" /> <property name="suffix" value=".jsp" /> </bean>
In our case, it will be /WEB-INF/jsps/ as prefix, hello as the name of page, and .jsp is the suffix value. Combining them, we will get /WEB-INF/jsps/hello.jsp, which acts as our view.
The Actual view is written as prefix+view_name from ModelAndView+suffix, for instance:
/WEB-INF/jsps/+hello+.jsp
The data is bounded by the front controller and the view will be able to use it:
<h2>${message}</h2>.
This page is now ready to be rendered by the browser, which will give output in the browser as:
Displaying the home page for a Spring application
Entering the name in the text field (for example, Bob) and submitting the form gives the following output:
Showing an output when a name is entered by the user
Now we understand the working of spring MVC, let's discuss a few more things required in order to develop the Spring MVC controller.
Each class which we want to discover as the controller should be annotated with the @Controller annotation. In this class, there may be number of methods which can be invoked on request. The method which we want to map for URL has to be annotated with the annotation @RequestMapping.
There can be more than one method mapped for the same URL but it will be invoked for different HTTP methods. This can be done as follows:
@RequestMapping(value="/hello.htm",method= RequestMethod.GET) publicModelAndViewsayHello(HttpServletRequest request) { } @RequestMapping(value="/hello.htm",method= RequestMethod.POST) publicModelAndViewsayHello(HttpServletRequest request) { }
These methods normally accept Request as parameter and will return ModelAndView. But the following return types and parameters are also supported.
The following are some of the supported method argument types:
- HttpServletRequest
- HttpSession
- Java.util.Map/ org.springframework.ui.Model/ org.springframework.ui.ModelMap
- @PathVariable
- @RequestParam
- org.springframework.validation.Errors/ org.springframework.validation.BindingResult
The following are some of the supported method return types:
- ModelAndView
- Model
- Map
- View
- String
- void
Sometimes the bean configuration is scattered in more than one file. For example, we can have controller configuration in one file and database, security-related configuration in a separate file. In that case, we have to add extra configuration in DD to load multiple configuration files, as follows:
<servlet> <servlet-name>HelloSpring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/beans.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>HelloSpring</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
Summary
In this article, we learned how the application will be single-handedly controlled by the front controller, the dispatcher servlet. The actual work of performing business logic and giving the name of the view, data model back will be done by the Spring MVC controller. The view will be resolved by the front controller with the help of the respective ViewResolver. The view will display the data got from the Spring MVC controller. To understand and explore Spring MVC, we need to understand the web layer, business logic layer and data layer in depth using the basics of Spring MVC discussed in this article.
Resources for Article:
Further resources on this subject: | https://www.packtpub.com/books/content/saying-hello-java-ee | CC-MAIN-2017-13 | refinedweb | 5,074 | 55.44 |
Three
Gatsby lets you create “layout components”. Layout components are sections of your site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts are a sidebar and navigation menu.
On this page, the sidebar to the left (assuming you’re on a larger device) and the header at the top are part of gatsbyjs.org’s layout component.
Let’s dive in and explore Gatsby layouts.
First, create a new site for this part of the tutorial (and, as we mentioned in Part Two, at this point it’s probably a good idea to close the terminal window(s) and project files from previous parts of the tutorial, to keep things clean on your desktop). We’ll use the “hello world” starter again:
gatsby new tutorial-part-three
Once the site is finished installing, install
gatsby-plugin-typography. For a reminder of how to do this, see Part Two of the tutorials. For
the Typography.js theme, let’s try the “Fairy Gates” typography theme this time:
npm install --save gatsby-plugin-typography typography-theme-fairy-gates
Create a
src/utils directory, and then create the typography config file at
src/utils/typography.js:
import Typography from "typography"; import fairyGateTheme from "typography-theme-fairy-gates"; const typography = new Typography(fairyGateTheme); export default typography;
Then edit our site’s
gatsby-config.js at the root of the site:
module.exports = { plugins: [ { resolve: `gatsby-plugin-typography`, options: { pathToConfigModule: `src/utils/typography.js`, }, }, ], };
Now, let’s add a few different pages: a front page, an about page, and a contact page.
src/pages/index.js
import React from "react"; export default () => ( <div> <h1>Hi! I'm building a fake Gatsby site as part of a tutorial!</h1> <p> What do I like to do? Lots of course but definitely enjoy building websites. </p> </div> );
src/pages/about.js
import React from "react"; export default () => ( <div> <h1>About me</h1> <p>I’m good enough, I’m smart enough, and gosh darn it, people like me!</p> </div> );
src/pages/contact.js
import React from "react"; export default () => ( <div> <h1>I'd love to talk! Email me at the address below</h1> <p> <a href="mailto:me@example.com">me@example.com</a> </p> </div> );
We now have the start of a nice personal site!
But there are a few problems. First, it’d be nice if the page content was centered on the screen like in part two of the tutorial. And second, we should really have some sort of global navigation so it’s easy for visitors to find and visit each of the sub-pages.
Let’s tackle these problems by creating our first layout component.
Our first layout componentOur first layout component
First, create a new directory at
src/layouts. All layout components have to be
in this directory.
Let’s create a very basic layout component at
src/layouts/index.js:
import React from "react"; export default ({ children }) => ( <div style={{ margin: `0 auto`, maxWidth: 650, padding: `0 1rem` }}> {children()} </div> );
Notice that unlike most
children props, the
children prop passed to layout
components is a function and needs to be executed
Stop
gatsby develop and start it again for the new layout to take effect.
Sweet, the layout is working! Now, our text is centered and constrained to a column 650 pixels wide, as we specified.
Let’s now add our site title:
import React from "react"; export default ({ children }) => <div style={{ margin: `0 auto`, maxWidth: 650, padding: `0 1rem` }}> <h3>MySweetSite</h3> {children()} </div>
If we go to any of our three pages we’ll see the same title added e.g. the
/about/ page:
Let’s add navigation links to each of our three pages:
import React from "react"; import Link from "gatsby-link"; const ListLink = props => <li style={{ display: `inline-block`, marginRight: `1rem` }}> <Link to={props.to}> {props.children} </Link> </li> export default ({ children }) => <div style={{ margin: `0 auto`, maxWidth: 650, padding: `1.25rem 1rem` }}> <header style={{ marginBottom: `1.5rem` }}> <Link to="/" style={{ textShadow: `none`, backgroundImage: `none` }}> <h3 style={{ display: `inline` }}>MySweetSite</h3> </Link> <ul style={{ listStyle: `none`, float: `right` }}> <ListLink to="/">Home</ListLink> <ListLink to="/about/">About</ListLink> <ListLink to="/contact/">Contact</ListLink> </ul> </header> {children()} </div>
And there we have it! A three page site with a basic global navigation.
With your new “layout component” powers, you can add headers, footers, global navigation, sidebars, etc. to your Gatsby sites.
Continue on to part four of the tutorial where we’ll start learning about Gatsby’s data layer and programmatic pages! | https://www.gatsbyjs.org/tutorial/part-three/ | CC-MAIN-2018-05 | refinedweb | 778 | 56.15 |
Okay, so we are working with linked lists, nodes and the stack ADT. I do believe that I have somewhat of a firm grasp on each of these concepts respectively. However, it is the implementation of all these ideas into code that I am metaphorically tearing my hair out over. When I look at it I am not seeing the big picture. The problem is my teacher just handed us the code and I guess expects us to learn it. What really would have worked is if he could of walked us through the building of the entire piece, step-by-step then I know I would understand these things. I guess my question too all you programming guru's is this: can you help me understand what each of these individual lines of code is doing? I really do not know if that is even possible with the constraints of not actually being face to face with each other but maybe you could take the time *and I am not saying you should* but it might help me if someone went through and gave assertions or comments for each line or something.
The problem is, as I have stated in previous posts, I am in a class that I do not seem prepared for. However, I have been working my butt off to try and catch up to the level that these other students must be on. We have a quiz on Friday over stacks, queues and linked data structures and I will probably fail it... sorry I am venting: in any case yes please help if you can!
package stack1_dog_Linked; import java.util.Scanner; public class Main { public static void main(String[] args) { int choice; String breed; Dog dogReference; boolean done = false; DogStack dogStack = new DogStack(); Scanner keyboard = new Scanner(System.in); while (!done) { System.out .print("Enter 1 to push, 2 to pop, 3 to check empty, and 4 to quit: "); choice = keyboard.nextInt(); System.out.println(); switch (choice) { case 1: System.out.print("Enter a dog breed to push: "); breed = keyboard.next(); dogReference = new Dog(breed); dogStack.push(dogReference); System.out.println(); break; case 2: if (dogStack.isEmpty()) { System.out.println("Can't pop, stack is empty!"); } else { System.out.println("The top dog was a : " + dogStack.pop().getBreed()); System.out.println(); } break; case 3: if (dogStack.isEmpty()) { System.out.println("The stack is empty."); } else { System.out.println("The stack is not empty."); } break; case 4: done = true; break; default: System.out.println("The number you entered, " + choice + ", is not 1, 2, 3, 4. Try again!"); System.out.println(); break; } } System.out.println("...quitting"); } }
package stack1_dog_Linked; public class Dog { private String breed = new String(); private String name = new String(); public Dog(String breedName) { breed = breedName; } public void setBreed(String breedName) { breed = breedName; } public String getBreed() { return breed; } }
package stack1_dog_Linked; public class DogStack { private Node top = null; private class Node { private Dog doggy; private Node nextNode; Node(Dog newDog) { doggy = newDog; } } public void push(Dog aDog) { Node dogNode = new Node(aDog); dogNode = new Node(aDog); dogNode.nextNode = top; top = dogNode; } public Dog pop() { Dog topDog = top.doggy; top = top.nextNode; return topDog; } public boolean isEmpty() { return (top == null); } } | http://www.javaprogrammingforums.com/object-oriented-programming/17931-having-problems-understanding-what-going-linked-stack.html | CC-MAIN-2014-42 | refinedweb | 532 | 64.41 |
Bluetooth Smart, or Bluetooth Low Energy (BLE), is a new type of technology mainly characterized by its low power consumption. This feature is highly convenient for devices that require constant data acquisition. Another benefit of this technology is that mobile operating systems such as Android and Apple, among others, support it.
In this tutorial, we are going to demonstrate how to use Bluetooth Smart to display text on an OLED that was sent from a smartphone.
Step 1: Materials
Below is a list of everything we need:
Hardware
- Breadboard
- OLED Display
- nRF8001 Development Board
- Arduino UNO
- Jumper Wires
- Android Phone Version 4.3 or Higher
Software
Android Apps
Libraries
Step 2: Wiring
The pictures above show the wiring setup for both the OLED screen and the nRF8001 Development Board.
Step 3: Configure NRF8001
Depending on the profile that we want the nRF8001 to have, we can create its Services and Characteristics using nRFgo Studio. When we open nRFgo Studio we get the following window as seen above.
Step 4: Configure NRF8001 - Continued
We click on File – New – nRF8001 to create a new profile, as seen above.
In this window, we are going to set the Services and Characteristics that we want the nRF8001 to have. On the right side of the window we can see a list of Services that are available. In order to add Service to our chip, we simply select and drag the Services that we want and drop them under Local (GATT Server).
Usually GATT server is the slave while GATT client is the master. We can also create our own Services if we want.
Step 5: Configure NRF8001 - Continued
For this tutorial we are going to use two Services: Device Information and Nordic UART over BTLE.
For the first one, we are only going to include the characteristic Hardware Revision String with the following setup as seen in the images above.
Step 6: Configure NRF8001 - Continued
For the second Service, we are going to include the characteristics UART RX with the following setup seen above.
Step 7: Configure NRF8001 - Continued - Some Explanation
Each Characteristic can have several modes:
- Notify
- Indicate
- Write without Response
- Write
In Notify mode, the server is updated and the client is notified. In other words, the slave (nRF8001) informs the client (smartphone) when data has changed. When the sender (in this case the nRF8001) writes, the value is automatically sent to the receiver (smartphone) without the receiver executing a “read” command. This is convenient because we get an immediate update every time something changes. Indicate mode works similar, but the receiver sends an acknowledgment to the sender. In other words, it informs the sender that transfers were successful and data was correctly received. This acknowledgement doesn’t take place in notification mode.
In Write without response mode, data is transmitted to server, but data reception is not acknowledged. In other words, the client (smartphone) sends data to the nRF8001, but the nRF8001 doesn’t let the sender know if the transfer was successful and/or if data was correctly received. Write works similar, but data reception is acknowledged.
In nRF8001, the concept of Service Pipe is used to simplify access to Service Characteristics in a client and/or server. Pipes point to a specific Characteristic in a Service and the value is transmitted or received through that pipe.
The UUID is a Universally Unique Identifier that distinguishes Services and Characteristics. This way the pipe will know what Characteristic or Service it should point to. In this tutorial, we leave the UUIDs unchanged.
Step 8: Configure NRF8001 - Continued
Now our GATT Services window looks like the image above.
While we use GATT Services to create a profile for our device with the Characteristics that we want it to have, GAP Settings is used for advertising.
Step 9: Configure NRF8001 - Continued
We set up the GAP Settings as shown above.
In the General tab we can choose the name of our device, what is the maximum number of characters it can have, if we can modify it, and more. We can use the default settings or customize it with our own if we want.
In this tutorial we simply changed the Bluetooth Device Name to URT.
Step 10: Configure NRF8001 - Continued
In the Service Solicitation and Local Services tab, we select the local Services we want to advertise.
In this case, we want UART over BTLE to be advertised.
Step 11: Configure NRF8001 - Continued
In the Advanced GATT Settings, we select the Add Service Changed Characteristic to allow the server (nRF8001) to alert the client (smartphone) of any structural changes
Step 12: Configure NRF8001 - Continued
In this window, we select the fields that we want to advertise.
We check the box “Local Services (GATT Server)” to broadcast the Characteristic data. This way we can advertise the Services that our device has. These are the Services we defined in the GATT Services window.
Step 13: Configure NRF8001 - Continued
The next step is to generate the source files.
This is done by clicking on nRF8001 – Generate Source Files – Generate services.h. This will create three files:
- services.h
- services_lock.h
- ublue_setup.gen.out
The last step is to create a setup file to run the .xml file (nRFgo Studio file) and setup the nRF8001 with the Services and Characteristics selected.
In a text editor such as Notepad, type the following lines:
del services.h
del services_lock.h
del ublue_setup.gen.out.txt
"%NRFGOSTUDIOPATH%\nrfgostudio.exe" -nrf8001 -g BLE.xml -codeGenVersion 1 -o .
Finally we save the file as a .bat file. When you double click on this file, it will set the nRF8001 chip with the profile created in nRFgo Studio.
All these files are already included in the JS_nRF8001 library.
Step 14: Arduino Code
Now that our chip is ready to be used, we have to write some code to make it interact with our smartphone. There is an Arduino SDK by Nordic (BLE library) that contains the source code for developing applications on Arduino. This will help us include the Services and work with them using the Arduino environment.
The Arduino SDK relies on a concept called ACI (Application Controller Interface). The ACI can be thought of as a communication channel that alerts the Arduino every time there is an event such as change in status, receipt of data, error, etc. Every cycle there is polling for updates over the ACI communication channel to check whether an event has occurred or not. The event of interest in this case is when data has been received. When text is sent over Bluetooth to the development board, the Arduino will be notified so that it can act accordingly to display the text on the OLED.
There is a template in BLE library (ble_my_project_template) that shows how the ACI is implemented in Arduino IDE. In order to keep our code clean, we created the library JS_nRF8001 to deal with the required ACI setup and events. Below is the code used to display text sent from a smartphone on an OLED.
#include <SPI.h>
#include <EEPROM.h> #include <boards.h> #include <JS_nRF8001.h> #include <services.h> #include <SSS1306_text.h> #include <Wire.h> #define OLED_RESET 5 SSD1306_text display(OLED_RESET); void setup(){ display.init(); display.clear(); BLE_initialize(); Serial.begin(57600); } void loop(){ BLE_process(); if ( BLE_free() ){ display.clear(); while ( BLE_free() ){ char r = BLE_get(); Serial.write(r); display.print(r); } } }
Step 15: Arduino Code Explanation
The first section of the code includes the libraries required for the nRF8001 Development Board.
The second section includes the libraries required for the OLED and defines what pin we want to use to reset the screen. Furthermore, it makes reference to the driver that we will be using (SSD1306).
In the setup part, we initialize the screen and the nRF8001, and set the baud for serial data transmission.
In the loop, the function “BLE_process” runs through the ACI events to process them. Then we check if there are any bytes that need to be read.
If the case is true, we clear the screen and while there are bytes that need to be read, we store each one of them at a time in variable “r.” Each byte is then displayed on the serial monitor and on the screen.
Step 16: Arduino Code Results
When we upload the code and open the serial monitor, we get the following window as shown above.
This lets us know that the device is ready and can be viewed (discovery mode).
Step 17: Arduino Code Results - Continued
From our smartphone, we open the nRF UART v2.0 and click on “Connect.”
We are now able to see our device called, “URT.”
When we connect with the device, we get the message as shown in the image above.
This tells us that connection has been established with the device.
Step 18: Arduino Code Results - Continued
When we send a text from our phone, we can see what pipe was used to transmit/receive the data and what information was sent as shown in the image above.
Step 19: Arduino Code Results - Continued
The same message will be displayed on the OLED.
In this tutorial we demonstrate how to use Bluetooth Low Energy to send and receive text.
However, there are many other applications for Bluetooth 4.0 than just sending and/or receiving messages.
With Bluetooth Smart we can use our phones to receive data from sensors, turn lights on/off, control motors, control a robot, and much more.
Ready to start creating? Check out Jaycon Systems online store to get the materials you need!
Want to learn more? Jaycon Systems has a bunch of tutorials and Instructables to help you create more things.
Let us know what you think and what you make! If you have any questions about this tutorial, don't hesitate to post a comment, shoot us an email, or post it in our forum!
Thank you for reading! | http://www.instructables.com/id/BLE-Controlled-OLED-Display/ | CC-MAIN-2017-17 | refinedweb | 1,653 | 64.51 |
Our.
A year after its release in 1995 Netscape took JavaScript to ECMA, a standards organization, to create a standard for JavaScript. In a way, this was a two-sided effort: on one hand, it was an attempt to keep implementors in check (i.e., keeping implementations compatible), and it was also a way for other players to be part of the development process without leaving room for classic "embrace, extend, extinguish" schemes.
A major milestone was finally reached in 1999 when ECMAScript 3 was released. This was the year of Netscape Navigator 6 and Internet Explorer 5. AJAX was just about to be embraced by the web development community. Although dynamic web pages were already possible through hidden forms and inner frames, AJAX brought a revolution in web functionality, and JavaScript was at its center.
To better understand what happened after 1999, we need to take a look at three key players: Netscape, Microsoft and Macromedia. Of these three, only Netscape and Microsoft were part of TC-39, the ECMAScript committee, in 1999.
Netscape
In 1999, some members of TC-39 were already working on ideas for what could be ECMAScript 4. In particular, Waldemar Horwat at Netscape had begun documenting a series of ideas and proposals for the future evolution of ECMAScript. The earliest draft, dated February, 1999 can be found in the Wayback Machine. An interesting look at the ideas for the next version of ECMAScript is outlined in the Motivation section:
JavaScript is not currently a general-purpose programming language. Its strengths are its quick execution from source (thus enabling it to be distributed in web pages in source form), its dynamism, and its interfaces to Java and other environments. JavaScript 2.0 is intended to improve upon these strengths, while adding others such as the abilities to reliably compose JavaScript programs out of components and libraries and to write object-oriented programs. - Waldemar Horwat's early JavaScript 2.0 proposal
However, Netscape would not be the first with a public implementation of these ideas. It would be Microsoft.
Microsoft
In 1999 Microsoft was focused on a revolution of its own: .NET. It was around the release of Internet Explorer 5 and ECMAScript 3 that Microsoft was getting ready to release the first version of the .NET Framework: a full development platform around a new set of libraries and a common language runtime, capable of providing a convenient execution environment for many different languages. The first exponents of .NET were C# and Visual Basic .NET: the first, an entirely new language inspired by Java and C++; the second, an evolution of its popular Visual Basic language, targeting the new platform. The .NET Framework included support for Microsoft's server-side programming framework: ASP.NET. It was perhaps natural that ASP.NET should provide a JavaScript-like language as part of its tools, and an implementation of a dynamic language such as JavaScript could very well serve as a natural demonstration of the capabilities of the common language runtime. Thus JScript .NET was born.
JScript .NET was introduced in 2000. It was slated as an evolution of JScript, the client-side scripting engine used by Internet Explorer, with a focus on performance and server-side uses, a natural fit for the .NET architecture and the ASP.NET platform. It would also serve to displace VBScript, another scripting language developed by Microsoft in the '90s with heavy inspiration from Visual Basic, normally used for server-side/desktop scripting tasks.
One of the design objectives of JScript .NET was to remain largely compatible with existing JScript code; in other words, mostly compatible with ECMAScript 3. There were implementation differences between JScript and Netscape's JavaScript; however it was Microsoft's stated objective to follow the standard. It was also one of the objectives from ECMAScript 4 to remain compatible with previous versions of the standard (in the sense that ECMAScript 3 code should run on ECMAScript 4 interpreters). ECMAScript 4 was, thus, a convenient evolution path for JScript .NET. Released from the constraints of browser development, the team behind JScript .NET could work faster and iterate at their discretion. JScript .NET became, much like Macromedia's ActionScript, another experimental implementation of many of the ideas behind ECMAScript 4.
In the words of the JScript .NET team:
(...) all the new features have been designed in conjunction with other ECMA members. It's important to note that the language features in the JScript .NET PDC release are not final. We're working with other ECMA members to finalize the design as soon as possible. In fact, there's an ECMA meeting this week at the PDC where we'll try to sort out some of the remaining issues. - Introducing JScript .NET
In contrast with the first versions of ActionScript, the first releases of JScript .NET in 2000 already included much more functionality from ECMAScript 4: classes, optional typing, packages and access modifiers were some of its new features.
Macromedia
As the Internet was becoming popular, spearheaded by Netscape and its Communicator suite, a different but no less important battle was taking place. Vector animation companies FutureWave Software and Macromedia had developed by 1995 two of the leading animation platforms: Macromedia Shockware and FutureWave FutureSplash.
From the beginning, Macromedia saw the importance of taking its product to the Web, so with help from Netscape it integrated its Shockwave Player into Netscape Navigator as a plugin. Much of the work required for having "external components" in the browser had already been done for Java, so the needed infrastructure was in place.
In November 1996, Macromedia acquired FutureSplash and promptly renamed it Flash. This made Macromedia the sole owner of the two most important vector-based animation tools for the Web: Shockwave and Flash. For a time, both players and authoring tools coexisted, but after a few years Flash emerged as the winner.
The combined power of the web platform, getting bigger and bigger by the day, and the push from content creators caused Flash to evolve rapidly. The next big step for animation software was to become a platform for interactive applications, much like Java offered at the moment, but catering to designers and with special focus on animation performance and authoring tools. The power of a certain programmability first came to Flash in version 2 (1997) with actions.
"Actions" were simple operations that could be triggered by user interaction. These operations did not resemble a full programming language. Rather, they were limited to simple "goto-style" operations in the animation timeline.
However, by version 4 (1999), actions had pretty much evolved into a programming language: loops, conditionals, variables and other typical language constructs were available. However, the limitations of the language were becoming apparent and Macromedia was in need of something more mature. As it turns out, browsers already had one such language: JavaScript. Catering to non-programmers and already with considerable mindshare, JavaScript was a sound choice.
Flash Player version 5 (2000) drew heavily from ECMAScript 3 for its scripting language. Combined with some of the constructs used for previous versions, this new language expanded actions with many tools from ECMAScript such as its prototype-based object model and weak typed variables. Many keywords (such as
var) were also shared. This new language was called ActionScript.
By this year, Macromedia was committed to improving ECMAScript. The synergy between JavaScript in the browser and ActionScript in Flash was just what Macromedia needed: Macromedia got a powerful programming language, and at the same time tapped into the mindshare from the already-existing designer-oriented JavaScript community. It would be in Macromedia's best interest to see ECMAScript succeed.
Flash as a Platform
The power of vector-based animations, a convenient editor and a powerful programming language proved to be a killer combination. Not only were more and more end users installing the Flash Player plugin, but content creators were also producing ever more complex content. Flash was quickly becoming a tool for more than just animations; it was becoming a platform to deliver rich content, with complex business logic behind it. In a sense, Macromedia had a big advantage compared to the rest of the Web: it was the sole owner and developer of the platform. That meant it could iterate and improve on it and at a much quicker pace than the Web itself. Not only that, it also had the best authoring tools for visual and interactive content, and the mindshare of developers and designers dedicated to this type of content. All of this put Macromedia ahead of other players, even Sun and its Java language (with regards to Java applets in the browser).
The next natural step for Macromedia was to move forward. It had the best authoring tools and it was gaining developer mindshare. It was only logical to keep investing and advancing the development of its tools. And one of these tools was ActionScript. Macromedia saw with good eyes the ideas Netscape was putting forth in its ECMAScript 4 proposals document, and so began adopting many of them for their own language. At the same time, they knew it was in their best interest to not stray too far away from the general community of JavaScript developers, so they made a good effort to first become compliant with the ECMAScript 3 standard. It could only do them good: ECMAScript 4 was slated as the improvement JavaScript needed for bigger programs, and their community would certainly make use of that. Also, by leading the charge, they could have more leverage in the committee to push forward features that worked, or even new ideas. It was a sound plan.
Although interest in ECMAScript 4 eventually dwindled inside the committee, by 2003 Macromedia was ready to release its new version of ActionScript as part of Flash 7. ActionScript 2.0 brought compile-time type checks and classes, two slated features found in the ECMAScript 4 drafts, and improved compliance with ECMAScript 3.
The Years of Silence
TC-39 and ECMA were active between 1999 and 2003. Horwat's (Netscape) latest draft document is dated August 11, 2000. Macromedia and Microsoft continued independently based largely on this draft document, but no interoperability tests were performed at this stage. By 2003, work by the committee had all but stopped. This meant there was no real push for a new release of the ECMAScript standard. Although Macromedia was about to release ActionScript 2.0 in 2003 and Microsoft's .NET platform was flourishing, ECMAScript 4 was not moving forward.
It is important to note that at this stage, the drafts published by Horwat (Netscape) were not exhaustive enough to ensure compatibility between implementations. In other words, although ActionScript and JScript .NET were loosely based on the same drafts, they were not really compatible. Worse, code was already being developed using these implementations; code that could potentially become incompatible with the standard in the future. In a sense, this was not seen as a big problem, as ActionScript and JScript .NET were mostly isolated in their own platforms. Browser engines, for their part, had not advanced as much. Some extensions implemented by the big browsers, Internet Explorer and Netscape, were in use, but nothing big enough.
Two long years passed between when work halted in 2003 until it was resumed. In between several significant events took place:
- implementations.
- Macromedia was acquired by Adobe in 2005.
Although it may seem these events are not related, they all played a part in the reactivation of TC-39.
TC-39 Comes Back to Life
The success of Internet Explorer on the desktop, due in great part to its bundling with Windows, forced Netscape's hand. In 1998, they released Netscape Communicator's source code and started the Mozilla project. By 2003, Microsoft had the majority of the browser market share and AOL, then owner of Netscape, announced major layoffs. The Mozilla project was to be spun off as an independent entity: the Mozilla Foundation. Mozilla would continue the development of Gecko (Netscape Navigators's layout engine) and SpiderMonkey. Soon, the Mozilla Foundation would shift its focus to the development of Firefox, a standalone browser without the bloat of the whole suite of applications that came bundled since Netscape's days. In an unexpected turn of events, Firefox's marketshare commenced to grow.
Microsoft, by the time Firefox was released, had mostly stagnated with regards to web development. Internet Explorer was the king, and .NET was making big inroads in the server market. JScript .NET, getting little traction and developer interest, was left mostly unchanged. In other words, Microsoft had no particular interest at this point in reviving ECMAScript: they controlled the browser, and JScript .NET was an afterthought. It would require some prodding to wake them up.
Macromedia, and then Adobe after its acquisition, started a push toward integration of their internal ActionScript work into ECMA in 2003. They had spent a considerable amount of technical effort on ActionScript, and it would only be in their best interest to see that work integrated into ECMAScript. They had the users, the implementation, and the experience to use as leverage inside the committee.
At this point, Brendan Eich, now part of Mozilla, was concerned about Microsoft's stagnation with regards to web technologies. He knew web development was based on consensus, and, at the moment, the biggest player was Microsoft. He needed their involvement if things were to move forward. Taking notice of Macromedia's renewed interest in restarting the work on ECMAScript 4, he realized now was a good time to get the ball rolling.
At the same time, there was interest in the community in standardizing a set of extensions to ECMAScript 3 meant to make it easier to manipulate XML data. A prototype of this had been developed by BEA Systems in 2002 and integrated into Mozilla Rhino, an alternative JavaScript engine written in Java. BEA Systems took their extension to ECMA; thus, ECMAScript for XML (E4X, ECMA-357) was born in 2004.
As E4X was an ECMA standard concerning ECMAScript, it was a good way to get the key players from TC-39 working back together. Eich used this opportunity to jump-start ECMAScript development again by pushing for a second E4X release in 2005. By the end of 2005, TC-39 was back at work on ECMAScript 4.
Although E4X was unrelated to the ECMAScript 4 proposal, it brought important ideas that would end up being used: namely namespaces and the
::operator.
Macromedia, now Adobe, took the work of TC-39 as a clear indication ActionScript was a safe bet. As work progressed, Adobe continued internal development of ActionScript at a fast pace, implementing many of the ideas discussed by the committee in short time. In 2006, Flash 9 was released, and with it ActionScript 3 was also out the door. The list of features integrated in it was extensive. On top of ActionScript 2 classes were added: optional typing, byte arrays, maps, compile time and runtime type checking, packages, namespaces, regular expressions, events, E4X, proxies, and iterators.
Adobe decided to take one more step to make sure things moved forward. In November 2006, Tamarin, Adobe's in-house ActionScript 3.0 engine (used in Flash 9), was released as open source and donated to the Mozilla Foundation. This was a clear indication that Adobe wanted ECMAScript to succeed and, if at all possible, to be as little different from ActionScript as possible.
A colorful fact of history is that Macromedia wanted to integrate Sun's J2ME JVM into Flash for ActionScript 3. The internal name for this project was "Maelstrom." For legal and strategic reasons this plan never came to fruition and Tamarin was born instead.
The Fallout
Work on ECMAScript was progressing and a draft design document with an outline of the expected features of ECMAScript 4 was released. The list of features had become quite long. By 2007, TC-39 was composed of more players than at the beginning. Of particular importance were newcomers Yahoo and Opera.
Microsoft, for their own part, were not sold on the idea of ECMAScript 4. Allen Wirfs-Brock, Microsoft's representative at TC-39, viewed the language as too complex for its own good. His reasons were strictly technical, though internally, Microsoft also had strategic concerns. Internal discussions at Microsoft eventually converged on a the idea that ECMAScript 4 should take a different course.
Another member of the committee, Douglas Crockford from Yahoo, also had his concerns about ECMAScript 4, although perhaps for different technical reasons. However, he had not been too vocal about them. Wirfs-Brock realized this and convinced Crockford it would be a good idea to voice his concerns. This created an impasse in the committee, which was now not in consensus. In Crockford's words:
Wirfs-Brock put forth the idea of somehow meeting at the middle. The committee decided to split into two work teams: one focused on finding a subset of ECMAScript 4 that was still useful but much easier to implement, and another team focused on moving forward with ECMAScript 4. Wirfs-Brock became the editor of the smaller, more focused standard, tentatively called ECMAScript 3.1. It is important to note that members from both teams worked in both groups, so they were not really separate in this sense.
As time passed, it became clear ECMAScript 4 was too big for its own weight. The group did not advance as much as they had hoped, and by 2008 many problems still had to be solved before a new standard could be drafted. The ECMAScript 3.1 team, however, had made considerable progress.
ECMAScript 4 is Dead, Long Live ECMAScript!
A meeting in Oslo, Norway, had been planned for the committee to establish a way forward. Before this meeting took place, Adobe, off the record, had made it clear they were planning to withdraw from ECMAScript 4 development, joining Microsoft and Yahoo in their stance. This was perhaps the result of seeing ECMAScript 4 become too different from ActionScript. The conclusions of this meeting were to:
- Focus work on ES3.1 with full collaboration.
ECMAScript 3.1 was soon renamed to ECMAScript 5 to make it clear it was the way forward and that version 4 was not to be expected. Version 5 was finally released in 2009. All major browsers (including Internet Explorer) were fully compliant by 2012.
Of particular interest is the word "harmony" in Eich's e-mail. "Harmony" was the designated name for the new ECMAScript development process, to be adopted from ECMAScript 6 (later renamed 2015) onwards. Harmony would make it possible to develop complex features without falling into the same traps ECMAScript 4 experienced. Some of the ideas in ECMAScript 4 were recycled in Harmony. ECMAScript 6/2015 finally brought many of the big ideas from ECMAScript 4 to ECMAScript. Others were completely scrapped.
Wait, What Happened to ActionScript (and JScript .NET)?
Unfortunately for Adobe, the death of ECMAScript 4 and their decision to stop supporting it meant the large body of work they had performed to keep in sync with the ECMAScript 4 proposal was, at least in part, useless. Of course, they had a useful, powerful, and tested language in the form of ActionScript 3. The community of developers was quite strong as well. However, it is hard to argue against the idea that they bet on ECMAScript 4's success and lost. Tamarin, which was open-sourced to help adoption and progress of the new standard, was largely ignored by browsers. Mozilla initially attempted to merge it with SpiderMonkey, but they later realized performance suffered considerably for certain important use cases. Work was needed, and ECMAScript 4 was not complete, so it never got merged. Microsoft continued improving JScript. Opera and Google worked on their own clean-room implementations. Chambers' blog
It was the hope of ActionScript developers that innovation in ActionScript would drive features in ECMAScript. Unfortunately, this was never the case, and what later came to ECMAScript 2015 was in many ways incompatible with ActionScript.
JScript .NET, on the other hand, had been largely left untouched since the early 2000s. Microsoft had long realized developer uptake was just too low. It went into maintenance mode in .NET 2.0 (2005) and remains available only as a legacy product inside the latest versions of .NET. It does not support features added to .NET after version 1 (such as generics, delegates, etc.).
An ECMAScript timeline
Aside: JavaScript use at Auth0
At Auth0 we are heavy users of JavaScript. From our Lock library to our back end, firsthand
JavaScript has a bumpy history. The era of ECMAScript 4 development (1999-2008) is of particular value to language designers and technical committees. It serves as a clear example of how aiming for a release too big for its own weight can result in development hell and stagnation. It is also a stark reminder that even when you have an implementation and are at the forefront of development, things can go in a completely different direction (Adobe, Microsoft). Being cutting-edge is always a bet. On the other hand, the new process established by the Harmony proposal has started to show progress, and where ECMAScript 4 failed in the past, the newer ECMAScript has succeeded. Progress cannot be stopped when it comes to the Web. Exciting years are ahead, and they cannot come soon enough. | https://auth0.com/blog/the-real-story-behind-es4/ | CC-MAIN-2020-16 | refinedweb | 3,572 | 54.73 |
Encoder.GetBytes Method (Char[], Int32, Int32, Byte[], Int32, Boolean)
When overridden in a derived class, encodes a set of characters from the specified character array and any characters in the internal buffer into the specified byte array. A parameter indicates whether to clear the internal state of the encoder after the conversion..
- flush
- Type: System.Boolean
true to clear the internal state of the encoder after the conversion; otherwise, false.
Return ValueType: System.Int32
The actual number of bytes written into bytes..
If your application is to convert many segments of an input stream, consider using the Convert method. GetBytes will throw an exception if the output buffer isn't large enough, but Convert will fill as much space as possible and return the chars read and bytes written. Also see the Encoding.GetBytes topic for more comments.
The following example demonstrates how to encode a range of elements from a character array and store the encoded bytes in a range of elements in a byte array. The GetByteCount method is used to determine the size of the array required by GetBytes.
using System; using System.Text; class EncoderExample { public static void Main() { Byte[]); bytes = new Byte[byteCount]; int bytesEncodedCount = uniEncoder.GetBytes(chars, 0, chars.Length, bytes, 0, true); Console.WriteLine( "{0} bytes used to encode characters.", bytesEncodedCount ); Console.Write("Encoded bytes: "); foreach (Byte b in bytes) { Console.Write("[{0}]", b); } Console.WriteLine(); } } /* This code example produces the following output. 8 bytes used to encode characters. Encoded bytes: [35][0][37][0][160][3][163]. | https://msdn.microsoft.com/en-us/library/5zxk59x5(v=vs.100).aspx | CC-MAIN-2016-40 | refinedweb | 255 | 52.26 |
One of the most popular ways for developers
to extend Windows SharePoint Services 2.0 sites has been to create
custom Web Parts. Web Parts are great because they add the extra
dimensions of user customization and personalization. As a
consequence, many teams at Microsoft and third-party companies alike
have built custom Windows SharePoint Services 2.0 solutions using
Web Parts. Because
of the popularity of Web Parts in Windows SharePoint Services 2.0,
Microsoft decided to add support for custom Web Part development to
ASP.NET 2.0. This strategy to reach a wider audience of developers
was accomplished by creating a new Web Part infrastructure for
ASP.NET 2.0 that is similar yet distinct from the Web Part
infrastructure created for Windows SharePoint Services 2.0. Consequently, there
are now two different styles of Web Parts. The older WSS-style Web
Parts depend on Microsoft.SharePoint.dll and must inherit from the
WebPart base class defined by the Windows SharePoint Services 2.0
teams in the Microsoft.SharePoint.Web- PartPages namespace. The
newer ASP-style Web Parts depend on System.Web.dll and must inherit
from a different base class also named WebPart defined by the
ASP.NET 2.0 team in the System.Web.UI.WebControls.WebParts
namespace. It is
an important design goal for Windows SharePoint Services 3.0 to run
both the older WSS-style Web Parts as well as the newer ASP-style
Web Parts. This has been accomplished by building the Windows
SharePoint Services 3.0 support for Web Parts on top of the ASP.NET
Web Part infrastructure, and then making changes to
Microsoft.SharePoint.dll so that WSS-style Web Parts written for the
Windows SharePoint Services 2.0 environment would be forwardly
compatible with the Windows SharePoint Services 3.0 run-time
environment.
To explain how Web Parts are loaded and run
in Windows SharePoint Services 3.0, this section discusses how the
Windows SharePoint Services 3.0 architecture was redesigned to layer
on top of the ASP.NET 2.0 Web Part infrastructure. First, I will
cover how Web Part Pages are laid out in Windows SharePoint Services
3.0, and then I get into the details of how to develop custom Web
Parts for a Windows SharePoint Services 3.0 environment. To run Web Parts in an
ASP.NET 2.0 application, you must create an .aspx page that contains
exactly one instance of the WebPartManager control and one or more
WebPartZone controls. The WebPartManager control is responsible for
serializing Web Part–related data as well as storing and retrieving
it from the tables in the ASP.NET services database. The .aspx page serving
as a Web Part Page can also contain Editor Parts, which allow users
to customize and personalize persistent Web Part properties. Web
Part Pages can also contain Catalog Parts, which allow users to add
new Web Parts to zones. The Web Part infrastructure of Windows
SharePoint Services 3.0 is built on a control named SPWebPartManager
that is derived from the ASP.NET 2.0 WebPartManager control. The
SPWebPartManager control overrides the standard behavior of the
WebPartManager control to persist Web Part data inside the Windows
SharePoint Services content database instead of the ASP.NET services
database. In most cases, you don’t have to worry about dealing
directly with the SPWebPartManager control because the one and only
required instance is already defined in the standard default.master
page. When you create a content page that inherits from
default.master, the SPWebPartManager control is already there.
The other controls that appear on a typical
Windows SharePoint Services 3.0 Web Part Page are shown in Figure
1-4 on the next page and include Web Part zones, Editor Parts, and
Catalog Parts. Note that Web Part zones for a Web Part Page in
Windows SharePoint Services 3.0 should be created using the
WebPartZone control defined in the Microsoft.SharePoint.Web-
PartPages namespace and not the standard WebPartZone control from
ASP.NET 2.0.
Instances of the WebPartZone control are
usually defined in content pages. The following code shows a simple
example of creating a content page designed to act as Web Part Page
in a Windows SharePoint Services 3.0 site. As you can see, this
.aspx file links to default.master just like the example you saw
earlier. However, it also explicitly inherits from the WebPartPage
base class and adds two WebPartZone controls into PlaceHolderMain.
Figure 1-4 A
Web Part Page in Windows SharePoint Services 3.0 requires the
SPWebPartManager control and one or more WebPartZone controls. If
you create a content page that inherits from the WebPartPage class,
you also get the benefit of Windows SharePoint Services 3.0
supplying Editor Parts and Catalog Parts.
<%@ Assembly Name="[Fully-qualified name for Microsoft.SharePoint.dll]" %>
<%@ Page language="C#" MasterPageFile="~masterurl/default.master"
Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage" %>
<%@ Register Tagprefix="WebPartPages"
Namespace="Microsoft.SharePoint.WebPartPages"
Assembly="[Fully-qualified name for Microsoft.SharePoint.dll]" %>
<asp:Content
<h3>My Custom Web Part Page</h3>
<table border="5" cellpadding="5" cellspacing="0">
<tr>
<td valign="top">
<WebPartPages:WebPartZone
</td>
<td valign="top">
<WebPartPages:WebPartZone
</td>
</tr>
</table>
</asp:Content>
When you create a Web Part Page for a
standard ASP.NET 2.0 application, you are required to add logic that
interacts with the WebPartManager control to manage the Web Part
display mode. Typically, you also need to explicitly add Editor
Parts and Catalog Parts to the page along with the HTML layout to
accommodate them. Fortunately, you don’t have to do these things
when creating content pages for a Windows SharePoint Services 3.0
site. Instead, you inherit from the WebPartPage class that’s defined
in the Microsoft.SharePoint.WebPartPages namespace and let it do all
this work for you behind the scenes.
Figure 1-5 shows a screen shot of a custom
Web Part Page in action. This is the display generated by the custom
Web Part Page definition shown in the previous code when the user
has entered edit mode. Notice that the page allows users to add Web
Parts into zones and to modify existing Web Parts using standard
Editor Parts.
Figure 1-5
Custom Web Part Pages that inherit from the WebPartPage class
provide automatic support for managing display mode as well as
providing Editor Parts and Catalog Parts. | http://www.megasolutions.net/Sharepoint/Web_Parts_in_Windows_SharePoint_Services_3_0.aspx | CC-MAIN-2014-42 | refinedweb | 1,062 | 50.02 |
Important: Please read the Qt Code of Conduct -
Create circle using QPainter
- marlenet15 last edited by
I found the following code which does exactly what I want it to do. However, The QPixmap is making it have a white square background instead of having the same color background as the window which is like gray. Is there anyway to display circle without the white background?
#include <QtGui> int main(int argc, char* argv[]) { QApplication app(argc, argv); QPixmap pm(100,100); pm.fill(); QPainter p(&pm); p.setRenderHint(QPainter::Antialiasing, true); QPen pen(Qt::blue, 2); p.setPen(pen); QBrush brush(Qt::green); p.setBrush(brush); p.drawEllipse(10, 10, 80, 80); QLabel l; l.setPixmap(pm); l.show(); return app.exec(); }
the docs tell us white is the default background color
void QPixmap::fill(const QColor & color = Qt::white) Fills the pixmap with the given color.
you could use :
pm.fill(QColor(255, 0, 0, 0));
to get a transparant fill
- marlenet15 last edited by
Thank you!!! | https://forum.qt.io/topic/60094/create-circle-using-qpainter | CC-MAIN-2020-40 | refinedweb | 168 | 68.16 |
small collection of helper functions More...
#include <Riostream.h>
#include <TFile.h>
#include <TH1.h>
#include <TROOT.h>
#include <TStyle.h>
#include <TLatex.h>
#include <TCanvas.h>
#include "AliEMCALGeometry.h"
#include "AliCalorimeterUtils.h"
#include "AliAODEvent.h"
Go to the source code of this file.
small collection of helper functions
See for general documentation
use root -b to speed up (no canvas drawn)
root [0] .L helperMacrosBC.C++
root [0] Get_RowCollumnID(244917,-1,4,16,4)
root [0] Get_RowCollumnID(244917,2001,-1,-1,-1)
root [0] Compare2Blocks("LHC16l",803,3,5)
Definition in file helperMacrosBC.C.
Compares masked amplidudes from 2 different merged blocks or from 2 different versions of the same block so that one can test the effectivness of added periods
Definition at line 182 of file helperMacrosBC.C.
get all runnumbers from different groups and sort them to give a min and max range for the bad map. Run numbers are in your runList file.
Definition at line 47 of file helperMacrosBC.C.
Definition at line 488 of file helperMacrosBC.C.
Referenced by Compare2Blocks().
check where the bad cell is (row collumn), if you have only its ID or get it's ID if you have its row and collumn
Definition at line 139 of file helperMacrosBC.C.
checks if the cell is part of manually masked cells
Definition at line 475 of file helperMacrosBC.C.
Referenced by Compare2Blocks().
Definition at line 405 of file helperMacrosBC.C.
Referenced by Compare2Blocks().
Funtion to set TH1 histograms to a similar style
Funtion to set TH1 histograms to a similar style
Definition at line 556 of file helperMacrosBC.C.
Referenced by Compare2Blocks(), and AliTrackletDeltaWeights::~AliTrackletDeltaWeights(). | http://alidoc.cern.ch/AliPhysics/vAN-20180926/helper_macros_b_c_8_c.html | CC-MAIN-2019-47 | refinedweb | 274 | 62.14 |
Software design promotes a set of programming qualities:
Some goals:
Modularity helps to have extensible, modifiable, portable, maintainable, reusable, understandable and flexible software. It allows new features to be seamlessly added when desired, and unwanted features to be removed, thus simplifying the user-facing view of the software. It allows several developers to work on different modules concurrently. It also allows to test modules independently. Furthermore, large projects become easier to monitor and to control.
C# such as C, Java and other programming languages allow to create modular software through different ways. In this article, we will briefly explore modular software development through interfaces in C#.
Code specification may take different forms:
Here comes a problem of validation: How can specifications be checked?
Below is the Interface/Type specification:
public interface ISet<T>{
ISet<T> Add(ISet<T> s, T e);
ISet<T> Remove(ISet<T> s, T e);
ISet<T> Empty();
bool IsEmpty(ISet<T> s);
bool Find(ISet<T> s, T e);
int Length(ISet<T> s);
}
Below is the formal specification:
IsEmpty(Empty()) = true
IsEmpty(Add(s, e)) = false
Find(Empty(), e) = false
Find(Add(s, e), e) = true
Find(Add(s, e), e) = Find(s, e)
Add(s, e) = s [if Find(s, e) = true]
[unconstrained otherwise]
Remove(Empty(), e) = Empty()
Remove(Add(s, e), e) = s
Remove(Add(s, e), f) = Add(Remove(s, f), e)
A module is a construct representing a unit of code (set of types, values, functions and any expression allowed by a language) and satisfying:
Sets of modules are meant to be connected according to the dependencies induced by their interfaces:
Many programming languages provide modules complying only to a subset of these properties:
In the following article, we will investigate the capabilities of C# in regard to modules.
All the code is written in a single unit, with few specifications.
Below is an example:
public T[] Empty<T>(){
return new T[]{};
}
public bool IsEmpty<T>(T[] s){
return s.Length == 0;
}
public T[] Add<T>(T[] s, T e){
var l = new List<T>(s);
l.Add(e);
return l.ToArray();
}
public T[] Remove<T>(T[] s, T e){
var l = new List<T>(s);
l.Remove(e);
return l.ToArray();
}
public bool Find<T>(T[] s, T e){
return s.Contains(e);
}
public int Length<T>(T[] s){
return s.Length;
}
Favorable features:
Problems:
Modular programming breaks the code into a set of cohesive and loosely coupled modules, that
shall be composed depending on the specification.
The relationship interface/implemented class is similar to module/signature.
Below is a client module:
public class MySet<T>:ISet<T>{
public ISet<T> Add(ISet<T> s, T e) { /* ... */ }
public ISet<T> Remove(ISet<T> s, T e) { /* ... */ }
public ISet<T> Empty() { /* ... */ }
public bool IsEmpty(ISet<T> s) { /* ... */ }
public bool Find(ISet<T> s, T e) { /* ... */ }
public int Length(ISet<T> s) { /* ... */ }
}
And below is a test module:
public class MySetTest{
public void AddTest() { /* ... */ }
public void RemoveTest() { /* ... */ }
public void EmptyTest() { /* ... */ }
public void IsEmptyTest() { /* ... */ }
public void FindTest() { /* ... */ }
public void LengthTest() { /* ... */ }
}
Advantages:
A type is a subset of the values of the language. For example: The bool type is the set {true, false}.
bool
true
false
A predicate is a function taking any possible value and returning a boolean:
In C#, according to the official documentation, contracts provide a way to specify preconditions, postconditions, and object invariants to the code. Preconditions are requirements that must be met when entering a method or property. Postconditions describe expectations at the time the method or property code exits. Object invariants describe the expected state for a class that is in a good state.
Code contracts include classes for marking the code, a static analyzer for compile-time analysis, and a runtime analyzer. The classes for code contracts can be found in the System.Diagnostics.Contracts namespace.
System.Diagnostics.Contracts
The benefits of code contracts include the following:
null
A type system is a formal method applied to a program which aims at classifying elements of the program with types so as to guarantee some correctness of its behavior.
Depending on the language and its compiler, type systems may come in different flavours:
Abstract data types are:
Interfaces in Java:
interface Set<T>{
Set<T> add(Set<T> set, T e);
Set<T> remove(Set<T> set, T e);
Set<T> empty();
boolean is_empty(Set<T> set);
boolean find(Set<T> set, T e);
int length(Set<T> set);
}
Signatures in OCaml:
module type SET = sig
type ’a set
val add : ’a set → ’a → ’a set
val remove : ’a set → ’a → ’a set
val empty : unit → ’a set
val is_empty : ’a set → bool
val find : ’a set → ’a → bool
val length : ’a set → int
end
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) | https://www.codeproject.com/Articles/5163072/Modular-Software-Development-In-Csharp | CC-MAIN-2019-47 | refinedweb | 807 | 53.92 |
Results 1 to 2 of 2
- Join Date
- Feb 2011
- 1
- Thanks
- 0
- Thanked 0 Times in 0 Posts
"ArrayIndexOutOfBoundsException" error in my stack program
I am having these error for quite some time now, and I was getting frustrated as to what causes it. Can you please help me with this? Any kind of help is deeply appreciated. Thanks!
Code:
import javax.swing.JOptionPane; public class Stack2 { static String data = ""; static int ctr = 0, maxElem, q; static String a[] = new String[maxElem]; static int e(String p) //user-defined element value { String s = JOptionPane.showInputDialog(p); int t = Integer.parseInt(s); return(t); } static void Push() // { if (ctr == maxElem) { JOptionPane.showMessageDialog(null,"The stack is full."); menu(); } else { data = JOptionPane.showInputDialog(null,"Enter any value(String, integer, etc.):"); a[ctr] = data; JOptionPane.showMessageDialog(null,"Operation successful."); ctr++; Display(); menu(); } } static void Pop() { if (ctr == 0) { JOptionPane.showMessageDialog(null,"The stack is empty. Push some elements first, then retry popping."); menu(); } else { ctr--; JOptionPane.showMessageDialog(null,"Popping " + a[ctr] + "..."); a[ctr] = null; JOptionPane.showMessageDialog(null,"Operation successful."); Display(); menu(); } } static void Peek() { if (ctr == 0) { JOptionPane.showMessageDialog(null,"There is nothing to display. The stack is empty."); menu(); } else { ctr--; JOptionPane.showMessageDialog(null,"The current head of the stack is: " + a[ctr]); ctr++; menu(); } } static void Display() { String d = ""; for (int x = maxElem - 1;x >= 0;x--) { d += a[x] + "\n"; } JOptionPane.showMessageDialog(null, d + "----------------------------\nelement 'null' = empty node"); menu(); } static void Exit() { System.exit(0); } static void menu() //menu { String m = JOptionPane.showInputDialog(null,"Stack Operations\n[1] Push\n[2] Pop\n[3] Peek\n[4] Display\n[5] Exit\n"); if (m.equals("1")) Push(); else if (m.equals("2")) Pop(); else if (m.equals("3")) Peek(); else if (m.equals("4")) Display(); else if (m.equals("5")) Exit(); else System.exit(0); } public static void main(String[] args) { q = e("Enter the number of elements for the stack:"); maxElem = q; menu(); } }
- Join Date
- Sep 2002
- Location
- Saskatoon, Saskatchewan
- 17,025
- Thanks
- 4
- Thanked 2,668 Times in 2,637 Posts
The error is simple, it means you have stepped beyond or below the size that your array could possibly be, and either tried to read or write data to it. The error should give you an index as well as to which it was and approximate location - this is actually surprisingly helpful in determining where the error can be especially if you use multiple loops within your program.
In this particular instance, its because you have 0 possible entries in your a[]. MaxElem has not been defined as any particular value by this point, so by default its size is 0. Not sure how large you want that to be though...
Using arrays as stacks or queues is a bit of a pain since you need to resize them, move them, copy them, and do all sorts of things to them. I would suggest changing the String array into a collection such as an ArrayList<String> or a Vector<String> (the overhead is a trade off for simplicity). These lets you move things in and out without needing to resize them manually. For some extra experience, you may want to look at writing your own linked lists. They are about the easiest datastructure to write, and carry a lot of useful features (using a double linked list lets you move from the front and end of a linked list with a O(1) magnitude, removing / adding from middle of collection takes minimal effort). If you do that, consider extending the AbstractCollection class (or implementing the Iterator and Collection interfaces) to create an iterable object that can be used in things like a for each. Very handy.PHP Code:
header('HTTP/1.1 420 Enhance Your Calm'); | http://www.codingforums.com/java-and-jsp/217739-arrayindexoutofboundsexception-error-my-stack-program.html | CC-MAIN-2017-39 | refinedweb | 630 | 66.74 |
Fred Drake wrote:
Even if we could avoid it at a technical level, it means that what we're reading is no longer XML. One of the desires with ZCML was to not invent everything from scratch. So, *if* we're using XML, we needto use it as defined, otherwise it *isn't* XML.
Advertising
Yay.. bow down and worship the god of dead chickens... *sulk* and in other news...Can anyone recommend an XML editor that lets me define certain default namespaces?
Failing that, anyone know how to do this in emacs? Chris -- Simplistix - Content Management, Zope & Python Consulting - _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg03580.html | CC-MAIN-2017-17 | refinedweb | 110 | 75.4 |
Your Account
Active Directory
by Robbie Allen
, Brian Desmond
, Alistair G. Lowe-Norris
, Joe Richards
Fifth Edition November 2012
Active Directory Cookbook
by Laura E. Hunter
, Robbie Allen
Third Edition December 2008
Print: $59.99
Ebook: $43.99
Active Directory
by Brian Desmond
, Joe Richards
, Robbie Allen
, Alistair G. Lowe-Norris
Fourth Edition November 2008
Print: $54.99
Ebook: $43.99
Active Directory Cookbook
by Robbie Allen
, Laura E. Hunter
Second Edition June 2006
Ebook: $39.99
Active Directory
by Robbie Allen
, Joe Richards
, Alistair G..95
Ebook: $35.99
Windows Server Cookbook
by Robbie Allen
March 2005
Print: $44.95
Ebook: $35 G. Lowe-Norris
Second Edition April 2003
OUT OF PRINT
Recent Posts | All O'Reilly Posts
Robbie blogs at:
Data as seeds of content
April 05 2012
How I automated my writing career
November 03 2011
You need to enable JavaScript to view more than 15 articles by this author.
VBScript or Perl?
Publish Date: Nov. 18, 2003.
Overview of the New Active Directory Tools in Windows Server 2003
Publish Date: Oct. 14, 2003
Microsoft set out to improve manageability in several key areas with the release of Windows Server 2003. Did it succeed? Robbie Allen, author of the recently released Active Directory Cookbook, gives you the rundown on the best new tools for improving manageability.
Introduction to System.DirectoryServices, Part 2
Publish Date: Aug. 4, 2003
In the conclusion to this two-part series on using the .NET Framework's System.DirectoryServices namespace, Robbie Allen, coauthor of Active Directory, 2nd Edition, looks at how to search with the DirectorySearcher class.
System.DirectoryServices
DirectorySearcher
Introduction to System.DirectoryServices, Part 1
Publish Date: Jul. 28, 2003
The .NET Framework's System.DirectoryServices namespace contains numerous classes, but two you should become familiar with are DirectoryEntry and DirectorySearcher. In Part 1 of this two-part series, Robbie Allen, coauthor of Active Directory, 2nd Edition, covers the DirectoryEntry class and shows examples of how to iterate over the attributes of an object. In Part 2 next week, he'll cover the DirectorySearcher class and show examples of how you can modify objects.
DirectoryEntry
© 2014, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.linuxdevcenter.com/pub/au/1046 | CC-MAIN-2014-15 | refinedweb | 380 | 52.76 |
If you're a team developing and maintaining a software monolith, there's a good chance you're considering or planning a move to an architecture based around microservices. I'm won't go into the various trade-offs involved in that decision in this article; rather, I will focus on one specific technique that might help you make the transition: Change Data Capture (CDC)
It's relatively straightforward to build a system around microservices if you're starting from scratch. However, it can be difficult to plan and manage a transition from an existing monolith. The kinds of changes involved can be substantial, and it's hard to keep a live system running smoothly while you fundamentally change how it works.
It's a big shift from an ACID-compliant database to a distributed architecture based on eventual consistency, and keeping data consistent during a long migration, when different information is held in different parts of your system can be particularly challenging.
Change Data Capture (CDC) enables you to make minimal changes (if any at all) to your production system at first. Rather, you set up a system to observe your database, and create events whenever key data is changed, with your "new architecture" systems responding to these events.
Change Data Capture
Let's look at an example. Say you want to add an onboarding email flow to your application, so that new users receive helpful emails over the course of several days after they create an account. Using CDC, you can create this new flow as a microservice. Whenever a new user record is added to your main users table, a new event is created. Then, your new microservice would consume that event and manage the onboarding process, without requiring any further changes to your main legacy application. Another example would be to send users an exit survey after they deleted their account, to capture data on why your service no longer meets their requirements.
I'm going to walk through one technique for achieving this, which requires literally no changes whatsoever to the "main" application; Heroku's recently-launched Streaming Data Connectors Beta.
The way this works is that you add a managed Kafka and a "data connector" to your Heroku application, defining the tables and columns where changes should generate events. Then, you can set up your new microservices to consume events from Kafka topics.
In the rest of this article, I'm going to walk you through how to set this up. We'll be using a trivial database-backed web application to represent our monolith, and a separate application subscribed to a Kafka topic, which will consume the events we generate by making changes to our database.
The Streaming Data Connectors Beta is only available to Heroku Enterprise users at the moment, because it only works in a Heroku Private Space (which is an enterprise feature).
Let's look at some code.
I'm working on a Mac laptop, but these commands should work fine in any posix-compliant terminal environment.
Cleanup
Some of the commands we'll be using create resources in your Heroku account which incur charges. Please}
Please use the name of your Heroku private space, in the command above.
The Users Application
We're going to use a trivial web application that manages "user" records in a Postgres database. I've written this one in Sinatra, which is a ruby library for lightweight web applications.
The application has a few HTTP endpoints:
get "/" do redirect "/users" end get "/users" do erb :users, locals: { users: get_users } end post "/users" do add_user(params) redirect "/users" end post "/delete_user" do delete_user(params["id"]) redirect "/users" end
An HTTP GET to "/users" renders a list of the users in the database, a POST to "/users" adds a new user, and a POST to "/delete_user" will delete a user.
This is the implementation of the database code:
def connection PG.connect(ENV.fetch("DATABASE_URL")) end def get_users connection.exec( "SELECT * FROM users" ) end def add_user(u) addsql = %[ INSERT INTO users (first_name, last_name, password, email) VALUES ($1, $2, $3, $4) ] connection.exec_params(addsql, [ u["first_name"], u["last_name"], u["password"], u["email"] ]) end def delete_user(id) connection.exec_params("DELETE FROM users WHERE id=$1", [ id ]) end
The full application is available here. Let's get it running.
I'm using a private space called devspotlight-private. Please substitute the name of your private space in the code that follows:
git clone cd sinatra-postgres-demo export HEROKU_PRIVATE_SPACE=devspotlight-private heroku apps:create --space ${HEROKU_PRIVATE_SPACE}
This will create an app with a random name. To keep the code samples consistent, I'm going to read the name and store it in an environment variable APP.
export APP=$(heroku apps:info | head -1 | sed 's/=== //') echo ${APP}
We need a database for our app, and in order to use the Streaming Data Connectors Beta you need to use a specific version of the Heroku Postgres add-on:
heroku addons:create heroku-postgresql:private-7 --as DATABASE --app ${APP}
Please note that running this command will incur charges on your Heroku account.
heroku addons:wait
It can take a few minutes to create the database, so the wait command above will let you know when you can move on to the next step:
git push heroku master heroku run make setup-db
This deploys our application, and sets up the database with the users table and a few sample records.
Once this process has completed, you should be able to run heroku open and see a web page that looks like this:
Now we have an example web application, backed by a Postgres database, where we can add and remove records from the users table. This represents our monolith application. Now let's add the Streaming Data Connectors Beta to see how we could use CDC to add microservices without changing our application.
Adding Kafka
We need Kafka to act as the messaging backbone of our connected applications, so we need the Kafka add-on. Again, you need to use a specific version:
heroku addons:create heroku-kafka:private-extended-2 --as KAFKA --app ${APP}
Please note that running this command will incur charges on your Heroku account.
heroku kafka:wait
Again, this can take some time.
Adding the Database Connector
Once we have our Kafka add-on, we can set up the connector to generate Kafka events whenever a table in our Postgres database changes.
We need to install a plugin to be able to add the database connector:
heroku plugins:install @heroku-cli/plugin-data-connectors
Once you've done that, the syntax to create our database connector looks like this:
heroku data:connectors:create \ --source [postgres identifier] \ --store [kafka identifier] \ --table [table name]...
To get the Postgres identifier, run this command:
heroku addons:info heroku-postgresql
You should see output that looks like this (your values will be different):
=== postgresql-tapered-49814 Attachments: lit-bastion-67140::DATABASE Installed at: Sun Jul 19 2020 10:26:20 GMT+0100 (British Summer Time) Owning app: lit-bastion-67140 Plan: heroku-postgresql:private-7 Price: $7000/month State: created
The identifier we need is on the first line. In this case, postgresql-tapered-49814
The process for getting the Kafka identifier is similar, with the identifier appearing on the first line of output:
heroku addons:info heroku-kafka
Now that we have identifiers for both the Postgres database and the Kafka instance, we can create the database connector. I'm using the identifiers from my application, so you'll need to substitute the appropriate values from yours when you run this command:
heroku data:connectors:create \ --source postgresql-tapered-49814 \ --store kafka-octagonal-83137 \ --table public.users \ --exclude public.users.password
I've specified the table as public.users. I used the default public schema of my Postgres database when I created my users table. If you used a different schema, you'll need to specify that instead.
Notice also that I've used --exclude public.users.password. This means there won't be any information about the value of the password field included in the Kafka events which are generated. This is a very useful feature to ensure you don't accidentally send sensitive user information from your main application to a microservice which doesn't need it.
The database connector can take a while to create, and the output of the create command will tell you the command you can use to wait for your database connector to be provisioned.
heroku data:connectors:wait [connector name]
Consuming the Kafka events
Now we have our original database-backed application, and we've added the Streaming Data Connectors Beta, so we should see an event on the Kafka service whenever we make a change to our users table.
The next step is to set up another application to consume these events. In a real-world scenario, you would want to do something useful with these events. However, for this article, all we're going to do is display the events in a very simple web interface.
Creating the Web Application
I've written a very simple "kafka-consumer" application, also using Ruby and Sinatra, which you can see here. In creating this, I
ripped off a bunch of code from was inspired by this heroku-kafka-demo-ruby application.
Let's get this deployed, and connect it to our Kafka instance. Fire up a new terminal session and run these commands.
export HEROKU_PRIVATE_SPACE=devspotlight-private
Substitute the name of your own Heroku private space.
git clone cd kafka-consumer heroku apps:create --space ${HEROKU_PRIVATE_SPACE} export APP=$(heroku apps:info | head -1 | sed 's/=== //')
Before we deploy our application, we need to do some setup to enable this application to read from the Kafka topic that was created when we set up the database connector.
To give your new application access to the Kafka instance, we need to run a command like this:
heroku addons:attach [app with kafka]::KAFKA -a [app that wants to access kafka]
The [app with kafka] is the name of your instance of the sinatra-postgres-demo application, which you'll see if you run heroku apps:info in your other terminal session.
The [app that wants to access kafka] is the instance of kafka-consumer, the application we're creating now.
We used the KAFKA label when we originally created the Kafka instance.
In my case, the command I need looks like this (substitute the values for your applications):
heroku addons:attach lit-bastion-67140::KAFKA -a boiling-sierra-18761
Be careful to put two colons before KAFKA, or you'll get Couldn't find that add-on.
The output should look something like this:
Attaching kafka-octagonal-83137 to ⬢ boiling-sierra-18761... done Setting KAFKA config vars and restarting ⬢ boiling-sierra-18761... done, v3
If you run heroku config you'll see that our new application now has several KAFKA* environment variables set, which will enable us to connect to the Kafka instance.
There is still one more thing we need though: We need to know the Kafka topic on which our events are going to be published. The topic was automatically created when we added the database connector. To find out what it is, go back to your sinatra-postgres-demo directory and run this command:
heroku kafka:topics
The output should look something like this:
=== Kafka Topics on KAFKA_URL Name Messages Traffic ──────────────────────────────────────────────────── ──────── ──────────── connect-configs-311cea8b-0d94-4b02-baca-026dc3e345e0 0/sec 0 bytes/sec connect-offsets-311cea8b-0d94-4b02-baca-026dc3e345e0 0/sec 7 bytes/sec connect-status-311cea8b-0d94-4b02-baca-026dc3e345e0 0/sec 0 bytes/sec heartbeat.witty_connector_44833 0/sec 12 bytes/sec witty_connector_44833.public.users 0/sec 0 bytes/sec
We want the topic ending with public.users. In my case, that's witty_connector_44833.public.users. If you specified multiple tables when you created the data connector, you'll see a topic for each of them.
Our demo kafka-consumer application just uses a single topic, which it gets from the KAFKA_TOPIC environment variable. So, we can set that now.
Back in your kafka-consumer terminal session, run this command (substituting your own topic name):
heroku config:set KAFKA_TOPIC=witty_connector_44833.public.users
Now we can deploy our application:
git push heroku master
As with the sinatra-postgres-demo application, you may have to wait several minutes for the DNS changes to complete.
CDC in Action
Now, we have all the pieces in place:
- User List - our database-backed pretend monolith, sinatra-postgres-demo
- The Streaming Data Connectors Beta which publishes events to a Kafka topic whenever our users table changes
- Message List - the kafka-consumer application that lets us see the Kafka events
In your browser, use the form to add a new user. A few seconds later, you should see a JSON message appear in the Message List application.
Message structure
The JSON you can see is the "value" of the Kafka event. There is other metadata in the event which you can see by tweaking the kafka-consumer application, but for now let's just look at the JSON data.
You can use a tool such as jq to inspect the JSON, or paste it into an online JSON tool like this one.
Collapsed down to just the top level, you can see that the message has a "schema" and a "payload":
There is a lot of metadata in the "schema" part, but most of the time you'll probably be more interested in the "payload" which has a "before" and "after" section. This should show you the values of the database record before and after the reported change(s). There are some important caveats about "before" in the best practices document about the Streaming Data Connectors Beta.
Notice how the "after" section does not include the "password" field of the user record. This is because we excluded it when we created the data connector.
Conclusion
Let's recap what we've covered.
- We started with a database-backed web application, managing a users table.
- We added Kafka, and the Streaming Data Connectors Beta to publish changes to the users table as Kafka events.
- We created a separate application and connected it to the Kafka topic, and saw messages generated by changes to the database.
It's worth emphasizing that we didn't have to make any changes at all to our "monolith" application code to make this happen.
Cleanup
Discussion (0) | https://dev.to/heroku/making-monolith-to-microservices-easier-with-kafka-streaming-data-connector-555e | CC-MAIN-2021-43 | refinedweb | 2,415 | 57.61 |
Author: cutting
Date: Tue Oct 24 14:44:48 2006
New Revision: 467497
URL:
Log:
HADOOP-626. Correct the documentation in the NNBench example code, and also remove a mistaken
call there. Contributed by Nigel Daley.
Modified:
lucene/hadoop/trunk/CHANGES.txt
lucene/hadoop/trunk/src/examples/org/apache/hadoop/examples/NNBench.java
Modified: lucene/hadoop/trunk/CHANGES.txt
URL:
==============================================================================
--- lucene/hadoop/trunk/CHANGES.txt (original)
+++ lucene/hadoop/trunk/CHANGES.txt Tue Oct 24 14:44:48 2006
@@ -40,6 +40,10 @@
11. HADOOP-554. Fix DFSShell to return -1 for errors.
(Dhruba Borthakur via cutting)
+12. HADOOP-626. Correct the documentation in the NNBench example
+ code, and also remove a mistaken call there.
+ (Nigel Daley via cutting)
+
Release 0.7.2 - 2006-10-18
Modified: lucene/hadoop/trunk/src/examples/org/apache/hadoop/examples/NNBench.java
URL:
==============================================================================
--- lucene/hadoop/trunk/src/examples/org/apache/hadoop/examples/NNBench.java (original)
+++ lucene/hadoop/trunk/src/examples/org/apache/hadoop/examples/NNBench.java Tue Oct 24 14:44:48
2006
@@ -44,12 +44,15 @@
import org.apache.hadoop.util.Progressable;
/**
- * This program uses map/reduce to just run a distributed job where there is
- * no interaction between the tasks and each task creates 1M/NTasks files
- * of 8 bytes each, closes them. Opens those files again, and reads them,
- * and closes them. It is meant as a stress-test and benchmark for namenode.
+ * This program uses map/reduce to run a distributed job where there is
+ * no interaction between the tasks. Each task creates a configurable
+ * number of files. Each file has a configurable number of bytes
+ * written to it, then it is closed, re-opened, and read from, and
+ * re-closed. This program functions as a stress-test and benchmark
+ * for namenode, especially when the number of bytes written to
+ * each file is small.
*
- * @author Owen O'Malley
+ * @author Milind Bhandarkar
*/
public class NNBench extends MapReduceBase implements Reducer {
@@ -67,7 +70,8 @@
}
/**
- * Given a number of files to create, create and open those files.
+ * Given a number of files to create, create and open those files
+ * for both writing and reading a given number of bytes.
*/
public void map(WritableComparable key,
Writable value,
@@ -97,7 +101,6 @@
int toBeRead = numBytesToWrite;
while (toBeRead > 0) {
int nbytes = Math.min(buffer.length, toBeRead);
- randomizeBytes(buffer, 0, nbytes);
toBeRead -= nbytes;
in.read(buffer, 0, nbytes);
reporter.setStatus("read " + (numBytesToWrite-toBeRead) +
@@ -134,8 +137,7 @@
/**
* This is the main routine for launching a distributed namenode stress test.
- * It runs 10 maps/node and each node creates 1M/nMaps DFS files.
- * The reduce doesn't do anything.
+ * It runs 10 maps/node. The reduce doesn't do anything.
*
* @throws IOException
*/ | http://mail-archives.apache.org/mod_mbox/hadoop-common-commits/200610.mbox/%3C20061024214448.E77771A9846@eris.apache.org%3E | CC-MAIN-2016-44 | refinedweb | 443 | 52.36 |
Sometimes.
The most basic interface is the signing interface. The Signer class can be used to attach a signature to a specific string:
>>> from itsdangerous import Signer >>> s = Signer('secret-key') >>> s.sign('my string') 'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA'
The signature is appended to the string, separated by a dot (.). To validate the string, use the unsign() method:
>>> s.unsign('my string.wh6tMHxLgJqB6oY1uT73iMlyrOA') 'my string'
If unicode strings are provided, an implicit encoding to utf-8 happens. However after unsigning you won’t be able to tell if it was unicode or a bytestring.
If the unsigning fails you will get an exception:
>>> s.unsign('my string.wh6tMHxLgJqB6oY1uT73iMlyrOX') Traceback (most recent call last): ... itsdangerous.BadSignature: Signature "wh6tMHxLgJqB6oY1uT73iMlyrOX" does not match
If you want to expire signatures you can use the TimestampSigner class which will additionally put in a timestamp information and sign it. On unsigning you can validate that the timestamp did not expire:
>>> from itsdangerous import TimestampSigner >>> s = TimestampSigner('secret-key') >>> string = s.sign('foo') >>> s.unsign(string, max_age=5) Traceback (most recent call last): ... itsdangerous.SignatureExpired: Signature age 15 > 5 seconds
Because strings are hard to handle this module also provides a serialization interface similar to json/pickle and others. (Internally it uses simplejson by default, however this can be changed by subclassing.) The Serializer class implements that:
>>> from itsdangerous import Serializer >>> s = Serializer('secret-key') >>> s.dumps([1, 2, 3, 4]) '[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo'
And it can of course also load:
>>> s.loads('[1, 2, 3, 4].r7R9RhGgDPvvWl3iNzLuIIfELmo') [1, 2, 3, 4]
If you want to have the timestamp attached you can use the TimedSerializer.
Often it is helpful if you can pass these trusted strings to environments where you only have a limited set of characters available. Because of this, itsdangerous also provides URL safe serializers:
>>> from itsdangerous import URLSafeSerializer >>> s = URLSafeSerializer('secret-key') >>> s.dumps([1, 2, 3, 4]) 'WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo' >>> s.loads('WzEsMiwzLDRd.wSPHqC0gR7VUqivlSukJ0IeTDgo') [1, 2, 3, 4]
Starting with “itsdangerous” 0.18 JSON Web Signatures are also supported. They generally work very similar to the already existing URL safe serializer but will emit headers according to the current draft (10) of the JSON Web Signature (JWS) [draft-ietf-jose-json-web-signature].
>>>'
When loading the value back the header will not be returned by default like with the other serializers. However it is possible to also ask for the header by passing return_header=True. Custom header fields can be provided upon serialization:
>>> s.dumps(0, header_fields={'v': 1}) 'eyJhbGciOiJIUzI1NiIsInYiOjF9.MA.wT-RZI9YU06R919VBdAfTLn82_iIQD70J_j-3F4z_aM' >>> s.loads('eyJhbGciOiJIUzI1NiIsInYiOjF9.MA.wT-RZI9YU06R919VBdAf' ... 'TLn82_iIQD70J_j-3F4z_aM', return_header=True) ... (0, {u'alg': u'HS256', u'v': 1})
“itsdangerous” only provides HMAC SHA derivatives and the none algorithm at the moment and does not support the ECC based ones. The algorithm in the header is checked against the one of the serializer and on a mismatch a BadSignature exception is raised.
All classes also accept a salt argument. The name might be misleading because usually if you think of salts in cryptography you would expect the salt to be something that is stored alongside the resulting signed string as a way to prevent rainbow table lookups. Such salts are usually public.
In “itsdangerous”, like in the original Django implementation, the salt serves a different purpose. You could describe it as namespacing. It’s still not critical if you disclose it because without the secret key it does not help an attacker.
Let’s assume that you have two links you want to sign. You have the activation link on your system which can activate a user account and then you have an upgrade link that can upgrade a user’s account to a paid account which you send out via email. If in both cases all you sign is the user ID a user could reuse the variable part in the URL from the activation link to upgrade the account. Now you could either put more information in there which you sign (like the intention: upgrade or activate), but you could also use different salts:
>>> s1 = URLSafeSerializer('secret-key',>> s2 = URLSafeSerializer('secret-key',>> s2.loads(s1.dumps(42)) Traceback (most recent call last): ... itsdangerous.BadSignature: Signature "kubVFOOugP5PAIfEqLJbXQbfTxs" does not match
Only the serializer with the same salt can load the value:
>>> s2.loads(s2.dumps(42)) 42
Starting with itsdangerous 0.14 exceptions have helpful attributes which allow you to inspect payload if the signature check failed. This has to be done with extra care because at that point you know that someone tampered with your data but it might be useful for debugging purposes.
Example usage:
from itsdangerous import URLSafeSerializer, BadSignature, BadData s = URLSafeSerializer('secret-key') decoded_payload = None try: decoded_payload = s.loads(data) # This payload is decoded and safe except BadSignature, e: encoded_payload = e.payload if encoded_payload is not None: try: decoded_payload = s.load_payload(encoded_payload) except BadData: pass # This payload is decoded but unsafe because someone # tampered with the signature. The decode (load_payload) # step is explicit because it might be unsafe to unserialize # the payload (think pickle instead of json!)
If you don’t want to inspect attributes to figure out what exactly went wrong you can also use the unsafe loading:
from itsdangerous import URLSafeSerializer s = URLSafeSerializer('secret-key') sig_okay, payload = s.loads_unsafe(data)
The first item in the returned tuple is a boolean that indicates if the signature was correct.
This class can sign a string and unsign it and validate the signature provided.
Salt can be used to namespace the hash, so that a signed string is only valid for a given namespace. Leaving this at the default value or re-using a salt value across different parts of your application where the same signed value in one part can mean something different in another part is a security risk.
See The Salt for an example of what the salt is doing and how you can utilize it.
New in version 0.14: key_derivation and digest_method were added as arguments to the class constructor.
New in version 0.18: algorithm was added as an argument to the class constructor.
The digest method to use for the signer. This defaults to sha1 but can be changed for any other function in the hashlib module.
Changed in version 0.14.
Controls how the key is derived. The default is Django style concatenation. Possible values are concat, django-concat and hmac. This is used for deriving a key from the secret key with an added salt.
New in version 0.14.
This method is called to derive the key. If you’re unhappy with the default key derivation choices you can override them here. Keep in mind that the key derivation in itsdangerous is not intended to be used as a security method to make a complex key out of a short password. Instead you should use large random secret keys.
Returns the signature for the given value
Signs the given string.
Unsigns the given string.
Just validates the given signed value. Returns True if the signature exists and is valid, False otherwise.
Works like the regular Signer but also records the time of the signing and can be used to expire signatures. The unsign method can rause a SignatureExpired method if the unsigning failed because the signature is expired. This exception is a subclass of BadSignature.
Returns the current timestamp. This implementation returns the seconds since 1/1/2011. The function must return an integer.
Signs the given string and also attaches a time information.
Used to convert the timestamp from get_timestamp into a datetime object.
Works like the regular unsign() but can also validate the time. See the base docstring of the class for the general behavior. If return_timestamp is set to True the timestamp of the signature will be returned as naive datetime.datetime object in UTC.
Just validates the given signed value. Returns True if the signature exists and is valid, False otherwise.
This class provides a algorithm that does not perform any signing and returns an empty signature.
This class provides signature generation using HMACs.
This class provides a serialization interface on top of the signer. It provides a similar API to json/pickle/simplejson and other modules but is slightly differently structured internally. If you want to change the underlying implementation for parsing and loading you have to override the load_payload() and dump_payload() functions.
This implementation uses simplejson for dumping and loading.
Starting with 0.14 you do not need to subclass this class in order to switch out or customer the Signer. You can instead also pass a different class to the constructor as well as keyword arguments as dictionary that should be forwarded:
s = Serializer(signer_kwargs={'key_derivation': 'hmac'})
Changed in version 0.14:: The signer and signer_kwargs parameters were added to the constructor.
If a serializer module or class is not passed to the constructor this one is picked up. This currently defaults to json.
The default Signer class that is being used by this serializer.
New in version 0.14.
Like dumps() but dumps into a file.
Dumps the encoded object into a bytestring. This implementation uses simplejson.
Returns URL-safe, signed base64 compressed JSON string.
If compress is True (the default) checks if compressing using zlib can save some space. Prepends a ‘.’ to signify compression. This is included in the signature, to protect against zip bombs.
Like loads() but loads from a file.
Loads the encoded object. This implementation uses simplejson. This function raises BadPayload if the payload is not valid. The serializer parameter can be used to override the serializer stored on the class.
Like loads_unsafe() but loads from a file.
New in version 0.15.
Reverse of dumps(), raises BadSignature if the signature validation fails.
Like loads() but without verifying the signature. This is potentially very dangerous to use depending on how your serializer works. The return value is (signature_okay, payload) instead of just the payload. The first item will be a boolean that indicates if the signature is okay (True) or if it failed. This function never fails.
Use it for debugging only and if you know that your serializer module is not exploitable (eg: do not use it with a pickle serializer).
New in version 0.15.
A method that creates a new instance of the signer to be used. The default implementation uses the Signer baseclass.
Uses the TimestampSigner instead of the default Signer().
alias of TimestampSigner
Reverse of dumps(), raises BadSignature if the signature validation fails. If a max_age is provided it will ensure the signature is not older than that time in seconds. In case the signature is outdated, SignatureExpired is raised which is a subclass of BadSignature. All arguments are forwarded to the signer’s unsign() method.
This serializer implements JSON Web Signature (JWS) support. Only supports the JWS Compact Serialization.
The default algorithm to use for signature generation
Like dumps() but creates a JSON Web Signature. It also allows for specifying additional fields to be included in the JWS Header.
Reverse of dumps(). If requested via return_header it will return a tuple of payload and header.
Works like Serializer but dumps and loads into a URL safe string consisting of the upper and lowercase character of the alphabet as well as '_', '-' and '.'.
Works like TimedSerializer but dumps and loads into a URL safe string consisting of the upper and lowercase character of the alphabet as well as '_', '-' and '.'.
Raised if bad data of any sort was encountered. This is the base for all exceptions that itsdangerous is currently using.
New in version 0.15.
This error is raised if a signature does not match. As of itsdangerous 0.14 there are helpful attributes on the exception instances. You can also catch down the baseclass BadData.
The payload that failed the signature test. In some situations you might still want to inspect this, even if you know it was tampered with.
New in version 0.14.
Raised for time based signatures that fail. This is a subclass of BadSignature so you can catch those down as well.
If the signature expired this exposes the date of when the signature was created. This can be helpful in order to tell the user how long a link has been gone stale.
New in version 0.14.
Signature timestamp is older than required max_age. This is a subclass of BadTimeSignature so you can use the baseclass for catching the error.
This error is raised in situations when payload is loaded without checking the signature first and an exception happend as a result of that. The original exception that caused that will be stored on the exception as original_error.
New in version 0.15.
If available, the error that indicates why the payload was not valid. This might be None. | http://pythonhosted.org/itsdangerous/ | CC-MAIN-2013-20 | refinedweb | 2,128 | 58.99 |
1/5 or .2 of a dollar) and tpennies.
Create an array of three Tmoney objects. Use a loop to input data into each of the elements. Print out
the data for the second Tmoney entered.
● inputdata prompts the user for input and then stores the values they enter in the object
● outputdata prints the information stored in the object
I am stuck because I keep getting this error code for line 31 and 48 the error code is C2109 it says subscript requires array or pointer type.
#include <iostream> using namespace std; class TMoney { private: int tdollars; int twons; int tpennies; public: TMoney():tdollars(0),twons(0),tpennies(0){} void getinputdata(); void outputdata(); }; int main() { TMoney; int money; money[3]; int tdollars,twons,tpennies; for (int j = 0; j < 3; j++) { cout << "Enter the number of tdollars you own:"; cin >> tdollars; cout << "Enter the number of twons you own:"; cin >> twons; cout << "Enter the number of tpennies you own:"; cin >> tpennies; } for (int j=0; j<1; j++) { cout << "You have tdollars," << " twons," << " tpennies." << endl; cin >> money[tdollars][twons][tpennies]; } return 0; }
thanks for all help in advance | http://www.dreamincode.net/forums/topic/75557-i-am-stuck/ | CC-MAIN-2016-36 | refinedweb | 189 | 54.66 |
- 0shares
- Facebook0
- Twitter0
- Google+0
- Pinterest0
- LinkedIn0
Storage Classes in C
Where the variables are declared in a C program, is determined by storage classes. The scope and life time of variables is defined by storage variables. It is very clear from the name storage classes that it specifies how variables are stored in the memory. In other words we can say that every variable has a storage class that determines the life time and scope of the variable. The following are the storage classes that are used in C programming language:
- Local Variables
- Global variables or external variables
- Static variables
- Automatic variables
- Register variables
Local Variables:
These variables are declared inside any module in a C program. A variable declared inside a function is known as local variable. Local variables are also called automatic variables. The following is the syntax to declare local variables:
data-type identifier;
Here data-type is the data type of the variable and identifier is used to indicate the name of the variable.
Scope of local variables:
The area where a variable can be accessed is known as scope of variable. Local variable can be used only in the function in which it is declared. If a statement accesses a local variable that is not in scope, the compiler generates a syntax error.
Lifetime of local variables:
The time period for which a variable exists in the memory is known as the lifetime of that variable. Different types of variables have different lifetimes.
The lifetime of local variable starts when the control enters the function in which it is declared. Local variable is automatically destroyed when the control exits from the function and its lifetime ends. When the lifetime of a local variable ends, the value stored in this variable also becomes inaccessible.
Global Variables:
A variable declared outside a program module is global variable. All functions in the program can access these variables. Their values are shared among different functions. If one function changes the value of a global variable, this change is also available to other functions.
Scope of global variables:
Global variables can be used by all functions in the program. It means that these variables are globally accessed from any part of the program. Normally they are always declared after the header files and before the main () function.
Lifetime of global variables:
Global variables exist in the memory as long as the program is running. These variables are destroyed from the memory when the program terminates. These variables occupy memory longer than local variables. So, global variables should be used only when these are very necessary.
Consider the following code which inputs a number in global variable. It calls a function that multiplies the global variable by 2. The main function then displays value of global variable:
CODE:
# include <stdio. h>
# include <conio. h>
int g;
void fun ();
void main ()
{
printf (“Enter a number”);
scanf (“%d”, &g);
printf (“Value of g before function call: %d\n”, g);
fun ();
printf (“Value of g after function call: %d”, g);
getch ();
}
void fun ()
{
g = g * 2;
}
OUTPUT:
Enter a number: 5
Value of g before function call: 5
Value of g after function call: 10
In the above example we used functions (declaration, calling and definition of function) which will be discussed in the next topic.
Static Variables:
Static variables are initialized once at the beginning of the program. The value of static variable remains constant. They are sometimes used to count objects referring to object oriented programming. The static variables are initialized only once in a program and their values are not changed and they cannot be destroyed whether they are in scope or out of scope.
The internal static variables or local static variables are those that are declared inside the function and their scope remains inside the function in which they are declared. The scope of external or global static variables remains to the file in which they are declared. The initial value of static variable is zero which is assigned by the compiler by default.
Scope of static variables:
Just like global variables, static variable can also be used by all functions of a program.
Lifetime of static variable:
The lifetime of static variables is equal to the lifetime of the program in which they are used.
Auto variable:
Local variables are also called automatic variables. Automatic variables have the same scope and lifetime as the local variables.
When a variable is declared locally, by default it is declared as an auto variable. We can use the auto keyword before declaring a local variable which indicates that the variable is automatic. Consider the following syntax to declare an automatic variable:
auto data-type identifier;
Here auto is the keyword that indicates that the variable is automatic; the auto keyword is not necessary to declare an automatic variable, a variable is declared automatic by default. Data-type is the type of the variable and identifier indicates the name of the name of the variable. The automatic variables are created when we call a function and are destroyed when the control is returned from the function. An automatic variable is assigned a null value by default by the compiler.
Register variable:
When a variable is created it is automatically stored in RAM. To store a variable in a register, register variable is used. These variables are accessed fast by the compiler. The register variable tells the compiler to store the variable in register instead of storing the variable into memory. Register have a limited storage and only a few variables can be stored in the register. Usually the variables that are used frequently are stored in a register. We cannot get the address of a register variable.
Consider the following syntax to declare a register variable:
register int num;
Scope of register variable:
Register variable is a type of local variable it means it can only be used inside a function where it is declared.
Lifetime of register variable:
Register variable destroys when the control exits from the function where it was declared.
extern keyword:
We use the extern keyword while declaring a variable to tell the compiler that this variable is declared somewhere. When we use the extern keyword the variable is not allocated any storage. Suppose we have declared a global variable in one file then we can use that variable in another file by using the extern keyword. When we do not use the extern keyword while using the global variable declared in another file then an error will be generated that this variable is not found.
Consider the following example in which we have used the extern keyword:
CODE:
# include <stdio. h>
# include <conio. h>
int y;
void main ()
{
extern int y;
y = 10;
printf (“%d”, y);
}
In the above example extern keyword is declaring that the variable y is defined somewhere else. | http://www.tutorialology.com/c-language/storage-classes-in-c/ | CC-MAIN-2017-47 | refinedweb | 1,146 | 62.17 |
CodePlexProject Hosting for Open Source Software
Hi there,
I have just created a module inorder to add two new fields to the User Content type (I intend to add more later). However with the latest downloaded version of the source when I started it up and went to Content/Content Types User does not show up.
It did however showup in another version of I had installed....
Is there a way of revealing the User type so that I can add Parts to it.
Kind Regards
Simon
Ps if this is not the way to add extra fields (including, later drop downs) then what is the preferred way?
is the module that first set up that content type installed in the new system?
I must be missing something here... is there a module for "User" that shouldbe attached?
Actually there is a module right at the bottom called users under "Modules/Features" and its enabled - there is no option to disable it.
You can only add parts to User through code.
So what do you do if you want to add an address or extra identifiers to a user? I would have thought this would have been a process of adding a part to a user?
You do it through code, or you use one of the modules from the gallery that enable it.
Ok so I have created a module with two fields and it compiles etc. Its able to be enabled and it is.
I am now assuming there is some extra piece of code that causes my part to be able to be attatched however I thought it was:
ContentDefinitionManager.AlterPartDefinition(typeof(UserInfoPart).Name, builder => builder.Attachable());
Which is in the migration file.
Either way I dont seem to have User showing up in "Content/Content Types" in order to attach a part.....
Here is my migration file as it stands.
using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using UserInfo.Models;
namespace UserInfo
{
public class Migrations : DataMigrationImpl
{
public int Create()
{
// Creating table UserInfoRecord
SchemaBuilder.CreateTable("UserInfoRecord", table => table
.ContentPartRecord()
.Column("Address1", DbType.Double)
.Column("Address2", DbType.Double)
);
ContentDefinitionManager.AlterPartDefinition(typeof(UserInfoPart).Name, builder => builder.Attachable());
return 1;
}
}
}
I also have Profile enabled... wondering if that would enable Users to be displayed so as to allow my part to be attached?
To make it appear there you would have to alter the content type, not your part. What I was suggesting is different, I was suggesting that you attach the part to the type from your migration, not that you enable the user to do it from the UI. Why did you
want to do it from the admin?
My intention was to extend the number of fields that is required to register. We would like to have the address and full name etc as part of the registration process. To this end I looked at the profile module and was unable to get it to work. In particular
I enabled it in the module section but the user type did not appear in the content types area.
Is there something that I am missing with this module (why wont it display the user type uder content types).... and.... is this the approach to take with having extra fields for the register page?
It is still not clear to me why you would want to do it from the admin instead of just doing it once and for all from the migration code. The user type doesn't appear because it's not been marked creatable, I think, but again I don't think you need to change
that for your scenario.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://orchard.codeplex.com/discussions/264040 | CC-MAIN-2017-22 | refinedweb | 664 | 66.74 |
Safely serves multiple, isolated terminal sessions in a browser
Project description
runthis-server
RunThis Server is a tool for serving up unique, interactive terminal sessions over HTTP. This enables interactive demonstration pages and documentation for a variety of command-line applications.
Installation
RunThis-server may be installed with either conda or pip:
# use the conda-forge channel $ conda install -c conda-forge runthis-server # Or you can use Pip, if you must. $ pip install runthis-server
Test Usage
You can start up the server with the
runthis-server command line utility.
$ runthis-server --help usage: runthis-server [-h] [--config CONFIG] optional arguments: -h, --help show this help message and exit --config CONFIG Path to config file
Production Usage
For production, we recomment using
hypercorn, as the server here is
a Quart application. To use RunThis Server + hypercorn together, run the
following command:
$ hypercorn runthis.server.hypercorn:app
Or if you need to run with HTTPS certificates:
$ hypercorn runthis.server.hypercorn:app \ --certfile /pat/to/certs/fullchain.pem \ --keyfile /path/to/certs/privkey.pem \ --bind 0.0.0.0:80
Note: Currently there is no way to pass a path to a config file into the
runthis server when running under hypercorn. The server will just look for
a
runthis-server.yml file in the current working directory and use that.
If such a file does not exist, the default values will be used! Please
change directory into the location of the
runthis-server.yml file before
running hypercorn.
Configuration
By default, the server is configured to run by looking for a
runthis-server.yml file
in the current working directory. You can pass in a specific configuration file with
the
--config flag.
All configuration variables are optional. The following lists there meaning and default values. Usually, these appear as top-level keys in the YAML file:
# The path to the public certificate file. This is currently only # used by the hypercorn interface, and is passed directly though # to hypercorn's configuration. certfile: None # The command variable is a string that lists ths command, or path # to run whenever a new instance is requested. Nominally, this is # a command that starts a REPL, but doesn't have to be. command: "python3" # The docker variable is a boolean that determines whether or not # the command should be run in its own single-use docker container. # Docker, of course, must be available on the host. docker: true # The docker_image varible specifies which docker image should be # started up if the command is being run in a docker container. docker_image: "ubuntu:latest" # The host variable is the URL or IP address that the server is # running on. By default, this is "127.0.0.1". Other valid options are # "0.0.0.0", which will expose the server to the outside world, as well # as any valid CNAME or IP address. RunThis Server works by taking in # a request and then redirecting to a new port on this server. The selection # of the host determines the redirection address. Here is the mapping: # # host -> TTY redirect_base # 127.0.0.1 -> 0.0.0.0 # 0.0.0.0 -> IP address of server as seen by # IP or CNAME -> Same IP or CNAME host: "127.0.0.1" # The path to the private certificate file. This is currently only # used by the hypercorn interface, and is passed directly though # to hypercorn's configuration. certfile: None # The port variable is an int that specifies the port number that the # the RunThis Server itself operates on. The TTY redirects go to # separate ports. Therefore you would access the RunThis Server as f"http://{host}:{port}" port: 5000 # The tty_server variable is a string flag that represents the TTY server software that # will be executed each time a request is made. Currently, the valid options are: # # gotty: go-based TTY server # ttyd: C++ TTY server tty_server: "gotty" # The gotty_path is the path to the gotty executable gotty_path: "gotty" # The ttyd_path is the path to the ttyd executable ttyd_path: "ttyd" # The tty_server_port_start variable is an integer at which the TTY servers # will start serving their terminals. Each successive request increases this # value by one, so that each session recieves its own unique value. tty_server_port_start: 8080
The above values may also be embedded into a top-level
runthis key,
if needed for compatibily with other files. For exmaple,
runthis: host: 0.0.0.0 port: 80
Request Parameters
Requests of the server are be made to the URL
f"http://{host}:{port}".
However, this URL accepts either GET or POST requests and takes
the following parameters as options.
presetup: This is code that the new interpreter session is initialized. It is executed without any notification to the user.
setup: This is code that is executed right when the interpreter starts up, after the presetup code is executed. Additionally, this code is echoed (printed in its source form) to the user prior to being execute. This is good for running examples.
For example, the following GET request would run
import sys silently, and then
execute
print(sys.executable) after printing literally
"print(sys.executable)".
Usually, you should have a URL encoding library generate these URLs from source code for you.
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/runthis-server/ | CC-MAIN-2021-04 | refinedweb | 891 | 56.96 |
Hi, I wanted to pass an input to a char* then pass it to a class member.
but before i even get to the class member, i got stuck in the char* itself.
after i compile, it's ok.after i compile, it's ok.Code:#include <iostream> using namespace::std; class CTest { public: char *name; }; CTest Test; char *gName = ""; int main() { cout<<"Enter Name: "; cin>>gName; //<--here's the error Test.name = gName; return 0; }
but once i run it.
then it breaks and popup a message saying:
then opens a page on the "istream" file.then opens a page on the "istream" file.Unhandled exception at 0x104f01be (msvcp80d.dll) in test.exe: 0xC0000005: Access violation writing location 0x0041664b.
any leads to solve this?
I thought char* was able to store as string? | http://cboard.cprogramming.com/cplusplus-programming/81686-problem-cin-char*.html | CC-MAIN-2015-48 | refinedweb | 134 | 87.52 |
There is one small and nice object to object mapper called AutoMapper. I gave it a little try and I found it very useful. Specially if you have web service and you are using DTOs to move data between client and server. Good news is that AutoMapper is able to perform these mappings and you don't have to write more code than couple of lines. Let’s see example.
Suppose you have following classes: Order, OrderLine, Customer and OrderDto. OrderDto is DTO we are using to send order data to client. I have really simple classes for example purposes, so don’t try to find any good practices here.
public class Party
{
public string DisplayName { get; set; }
}
public class Order
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public List<OrderLine> OrderLines { get; set; }
public Party Customer { get; set; }
public decimal GetTotal()
{
var query = from line in OrderLines
select line;
return query.Sum<OrderLine>(a => a.Sum);
}
public class OrderLine
public string LineItem { get; set; }
public decimal Sum { get; set; }
public class OrderDTO
public string CustomerDisplayName { get; set; }
public decimal Total { get; set; }
public static OrderDTO Create(Order order)
var dto = new OrderDTO();
dto.CustomerDisplayName = order.Customer.DisplayName;
dto.OrderDate = order.OrderDate;
dto.OrderNo = order.OrderNo;
dto.Total = order.GetTotal();
return dto;
DTO creation and initialization is done in OrderDTO.Create() method. The code here is short if we compare it to real life DTOs. And usually we write this code manually. Here is the code that creates order and asks order DTO from OrderDTO class.
public void ClassicDTOExample()
var party = new Party();
party.DisplayName = "Smith, John";
var order = new Order();
order.OrderDate = DateTime.Now;
order.Customer = party;
order.OrderNo = "102";
order.OrderLines = new List<OrderLine>();
order.OrderLines.Add( new OrderLine() { LineItem = "Tea", Sum = 10 } );
order.OrderLines.Add( new OrderLine() { LineItem = "Coffee", Sum = 15 } );
order.OrderLines.Add( new OrderLine() { LineItem = "Juice", Sum = 5 } );
var dto = OrderDTO.Create(order);
Now let’s see how AutoMapper works. All we have to is to define mappings and use names of class members so auto mapping can take place. We need to modify OrderDTO class and remove Create() method. Our example code also changes a little bit.
public void AutoMapperDTOExample()
Mapper.CreateMap<Order, OrderDTO>();
var dto = Mapper.Map<Order, OrderDTO>(order);
As you can see we have now one method less to test and worry about. Pay attention to DTO member names – I chose names so that AutoMapper can understand what members of order and OrderDTO match. If I look what is inside order DTO created by AutoMapper I see something like this in my locals window.
The most interesting here is OrderDTO member Total. If you look at code above you can see that Order class has method GetTotal(). The value of GetTotal() was automatically mapped to Total property of OrderDTO class.
Although AutoMapper is pretty new and I’m not sure how good it is for using in production code I am sure that another tool for everydays work is coming.
Thank you for submitting this cool story - Trackback from DotNetShoutout
Pingback from Reflective Perspective - Chris Alcock » The Morning Brew #297
#.think.in infoDose #20 (2nd Mar - 6th Mar)
That looks pretty sweet. While the GetTotal was automagically mapped, I'm more impressed with the CustomerDisplayName as it had to traverse across the objects. Anyway, informative post...thanks.
AutoMapper use from Reflection ?
Very useful. Thx!
Pingback from A Useful Entity Translator Pattern / Object Mapper Template « Rich Hewlett
Its a really a nice example for help regarding DTO,
However i would recommend that the author should upload a complete small project in which data is accessed on web pages from database using DTO..
It would be useful on auto mapper configuration as well. | http://weblogs.asp.net/gunnarpeipman/archive/2009/03/01/creating-dtos-using-automapper.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+gunnarpeipman+%28Gunnar+Peipman%27s+ASP.NET+blog%29 | crawl-003 | refinedweb | 623 | 57.47 |
I’ve been working in the SAP HR industry as a developer and an architect for the last 15 years and I must say that I am really impressed by the speed of all the changes that SAP has brought within the last 2 years. For developers, a really amazing journey is just beginning.
A couple of weeks ago, I started playing around in SuccessFactors to see how easy it would be possible to build some extensions, it turned out it would not be that easy… I learned a lot over the first few weeks, including:
- The architecture of SAP HANA Cloud Platform is something all developers must understand.
- oData is a very powerful protocol that I have learned to love and I must say that the exposed service from SuccessFactors is really well done.
- The basics of Java can still take me out of my comfort zone.
To get comfortable with all of these technologies, I decided to work on a small project this week that would just allow me to connect from HCP to SuccessFactors and get information from the metadata. For this little project, I worked with my friend Jonathan Jouret, and all I can say is that it was not a walk in the park (especially for novices like us in Java!).
For all the Java gurus, please don’t throw me rocks for the code I published. While everything here might seem very obvious, I think for a SAP developer, it might be interesting.
oData libraries
As newbies in Java, we googled “oData Java” and found out that there were a few libraries out there that we could use. So Jon and I decided to take one each and try to make them work.
I picked Restlet (apparently a standard in the industry) and Jon picked oData4J from Google. After a couple of hours, we managed to get some data from SuccessFactors using both libraries but we failed in getting some SuccessFactors specific annotations.
In the following example, we were able to get most of the oData standard information, but we were also interested in getting the “Label” (here below: Address) and the oData “sf:” attributes. On Restlet, I tried to inherit a few classes and get my way through the source of the XML, but I quickly gave up.
I asked help from Krassi, who told me that SAP was using Olingo (from Apache) as a library. We went back to our computers with the motivation to get the data we wanted, and while listening to Rammstein to give us a rhythm, we managed to get everything we wanted after just a few hours.
I tried to load these libraries with Maven but although my code was building, at runtime I had an error so I just put the libraries in the build path.
Some code
In the snippet, you will find some code we used that we hope can help you get started.
Eclipse Configuration
We started with an Eclipse that contains all HCP tools, etc., and to make our life easier, we created a Dynamic Web Application. We chose this because we wanted to call a webpage and return a JSON with the info we needed. An important note is that the Tomcat Server should be configured with the link and credential from SuccessFactors.
In this example, I created the destination (under connectivity tab) “sap_hcmcloud_core_odata” and put the URL and the credentials. Note that with this destination name is standard and will make your life way easier when you’ll deploy your application.
Getting connectivity information from the context
SAP is making our life easy by providing us with some nice libraries. I used the following libraries:
import com.sap.core.connectivity.api.configuration.ConnectivityConfiguration; import com.sap.core.connectivity.api.configuration.DestinationConfiguration;
The following code is used to get the destination configuration:
Context context = new InitialContext(); // Get the connectivity settings from the context ConnectivityConfiguration configuration = (ConnectivityConfiguration) context.lookup("java:comp/env/connectivityConfiguration"); this.destConfiguration = configuration.getConfiguration("sap_hcmcloud_core_odata");// Create user/password token + Authentication String userPassword = destConfiguration.getProperty("User") + ":" + destConfiguration.getProperty("Password"); this.userPassword = "Basic " + new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
Getting the metadata
So, once we got all the information we needed to connect to SuccessFactors, we just had to call the service and have an EDM object created.
// Construct the URL for the metadata String urlMetadata = destConfiguration.getProperty("URL") + SEPARATOR + METADATA; URL url = new URL(urlMetadata); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HTTP_METHOD_GET); connection.setRequestProperty("Authorization", this.userPassword); connection.setRequestProperty(HTTP_HEADER_ACCEPT, APPLICATION_XML); connection.connect(); checkStatus(connection); // Get the metadata from the server Edm edm = EntityProvider.readMetadata(connection.getInputStream(), false); connection.disconnect(); // get some memory back
The metadata is loaded in the edm object… from there a lot of methods are available to get necessary information from the metadata.
And the rest of the code
Our challenge was to get some labels and <SF:> elements, and we managed to do that with the following code. Some of these information are “hidden” deep in the objects.
You can have a look at the files attached to this blog and more specifically at the method “loadAnnotations” and “loadSFAttributes”. I am happy to provide more explanation if necessary.
Here is the link to the github.
HANA Cloud Platform
The code can be published on HANA Cloud Platform and works if the proper destination is set up… I havent tried yet with the SSO but I am sure it should work (I’ll give it a try in a couple of days).
In a next blog, I’ll probably show an example on how to run a Query… but I think that for this, I might use Restlet as it is easier (at least, with my few days of experience, that’s my current conclusion).
Have fun and let me know if you think it could be done better, if it helped you or if you need more information.
Rammstein is the key to most of our dev problems 😉
Nice post, clear and complete…
Hello Greg,
Very informative blog.
I have a question. Can I pull data from HANA Views into Success Factors? If so, how? Can you give me some pointers?
Hey,
Can you please give me more details ? My understanding is that you want to read data in a HANA database and display it in a tile in SuccessFactors ?
Cheers
Greg
Hello Greg,
Thanks for your prompt response. You got it right. Currently I am pulling data from HANA database through calculation views and exposing them through Odata Service to be consumed in Fiori (Analytical App).
I would like to know if I can consume data from HANA (Analytical/calculation views) and display it in a tile in Success factors. Since success factors is cloud based how can we achieve this ? Any inputs are highly appreciated.
Thank you
Hello,
Sorry for the late reply, I was on leave for a few days… Anyway, the way we currently achieve this is by creating an UI5 application on HCP and consume the data via oData. We created a generic component in SuccessFactors and put the link to this application within an iFrame. Since there is SSO between SFSF and HCP, it works quite well.
If you’re certified with SuccessFactors, I think you’re allowed to create native extensions but I have no experience yet with this.
Cheers
Greg
Thank you Greg.
Hi Greg,
Olingo is definitely the way to go for this sort of thing, I find the hardest part the conversion to and from pojos, I’m sure there are ways to do this more easily using annotations but I haven’t yet found this to be easier – would be interested if you had any view on that.
Although you may have looked at it, I’d also look closely at using OAuth2SAMLBearerAssertion to connect yourself to SuccessFactors – SAP HANA Cloud Platform
You should be able to create the destination connection in exactly the same way no matter what auth you are using – so if using basic to test on local development, or OAuth2 SAML Bearer when deployed to HCP.
Check out the example SAP HANA Cloud Platform – which is pretty cool. Perhaps one of the best reasons to use the Java Web profile over the Tomcat7 one is the more fully featured connectivity features.
Nice blog post.
Cheers,
Chris
Hi Greg.
Great post! This is exactly what I was looking for.
I tried testing your application but I get an error with the connectivity import. How can I include this SAP library?
Hello Tiago,
Thanks 🙂 I think you might have overlooked to include the libraries from SAP in Eclipse. If this is the case, you need to follow this guide
If it does not work, I am happy to help.
Cheers
Greg
Hi Greg.
The project was not compiling with the SDK. I included it manually and it worked. Thank you for your help. 🙂
Hello Greg,
I come from an SAP HCM world and very new to JAVA. I am also trying to achieve access of data from SF to HCP. Your article has given me confidence.
I was trying to import the code which i extracted from the GIT. However, com.sap.core.connectivity.api.configuration.ConnectivityConfiguration and com.sap.core.connectivity.api.configuration.DestinationConfiguration is not found. Is there any specific library i need to import or all the cloud tools installation should have ensured it. I am using neo-java-web-sdk-1.78.16.
Regards,
Tarun Mishra
Hello Tarun,
Thanks for the kind words… This sample will only work with Tomcat, I think you downloaded the Java Web version…
Note that I think you did great by downloading the Java Web version as I think it can handle better the connectivity to SuccessFactors.
Give me one day and I’ll publish a sample of code working on Java Web.
Cheers
Greg
Thank you so much for your support.. it would really help!!
Thank you very much Greg, a very useful post.
Have you published the Java Web/Java EE Version 6 Web Profile version?
I’m looking forward to seeing his next post.
Regards.
Juan C.Orta | https://blogs.sap.com/2015/04/23/connect-to-successfactors-odata-from-hana-cloud-plateform/ | CC-MAIN-2017-39 | refinedweb | 1,690 | 54.12 |
"Douglas S. Blank" <dblank at brynmawr.edu> writes: > Just thought I'd post the details of what worked for me in interrupting a > loop in idle with no subprocesses and no print statements on WindowsXP. For those tuning in late, we are discussing running IDLE without the subprocess. This is not the recommended way to run IDLE. > Checking on PyShell.flist.pyshell.canceled did not work, because it > appears that "canceled" doesn't get set until "write()" is called. It seemed to be working for me. The 'canceled' attribute was being accessed. But I think I was mistaken and was 'interrupting' the code before it was actually running: I needed another <enter> :-) Digging deeper: pyshell.canceled is set by PyShell.cancel_callback(). But this callback isn't being run because Tk isn't servicing its events (the GUI is frozen) while the non-printing program is running as part of PyShell.enter_callback(). The event loop won't resume until that callback is completed. If the program should print (via a re-directed stdout -> PseudoFile -> OutputWindow -> tkinter text widget) then OutputWindow.write() calls self.text.update(). That update causes the event loop to run. The pending cancel_callback sets pyshell.canceled, which is then picked up when PyShell.write() completes, and a KeyboardInterrupt is generated. A solution is to update Tkinter. Include this in your module: ===================== try: shell = idlelib.PyShell.flist.pyshell root = idlelib.PyShell.root def break_check(): root.update() if shell.canceled: raise KeyboardInterrupt except NameError: # idlelib not in namespace: running in subprocess def break_check(): # subprocess responds to KBI pass ==================== and use break_check in your code where it might loop. while True: break_check() Another solution when running without the subprocess is to hit a Ctrl-C in the console window from which you started IDLE. (On Windows, you would need to start IDLE from a command window. cd to ..../Lib/idlelib and ..\..\python .\PyShell.py ) The ModifiedInterpreter.runcode() has called exec code in self.locals and the interrupt in the console window is received by python (which without the subprocess is the only python involved). There's an except: statement in runcode() which traps this and causes IDLE to reset. > But with that hint, I just add a bunch of write's in my code, like so: > > def func(): > PyShell.flist.pyshell.write("") > return None > > Then I can control+c the following: > >>>> while 1: func() > > If you remove the write(), you won't be able to stop the program (short of > killing IDLE). This is also a reasonable solution. A little magical, but reasonable :-) All of this is needed because without the subprocess, it's a little tricky to interrupt user code without interrupting IDLE itself. -- KBK | http://mail.python.org/pipermail/idle-dev/2006-December/002526.html | CC-MAIN-2013-20 | refinedweb | 445 | 67.86 |
Agenda
See also: IRC log, Previous 2007-02-12
Simone: my name is pronounced (as Ralph hears it) "see moan eh"
ACTION: Michael to prepare RDF/XML - RDFa comparison wiki page [recorded in] [CONTINUES]
Michael: I agreed to support that action for Ben
Michael: RiR is meant to be a list
of features supported by RDFa
... e.g. containers probably are 'in', reification is probably 'out'
... I can add more detail to the list and I may have missed some features
Ben: TimBL might add some examples of N3 that
cannot be expressed in RDFa
... what are the 'levels' meant to indicate?
Michael: links point to QA document
... allows for incremental enhancement of a spec
Ben: I worry this idea of 'levels' might imply more complication than there really is
Michael: we should decide whether to say 'this is all we support and no more' or indicate possible future features
Ralph: is it still useful to have a Wiki page so the community can edit?
Ben: I think so
Michael: I can prepare a discussion of this in
the Wiki
... don't want to duplicate work
ACTION: [DONE] Ralph to check if the test suite can be hosted at the W3C--is Tomcat available? [recorded in]
-> action progress: test suite hosting [Ralph 2007-02-26]
ACTION: Steven to put together sample XHTML2 doc with all mime type, etc. [recorded in] [CONTINUES]
ACTION: Ben start a list of RDF/XML features that are not supported by RDFa [recorded in] [CONTINUES]
ACTION: [WITHDRAWN] Ben to contemplate about the Dev Track [recorded in]
Ben: I thought about it so long that I missed
the deadline
... I might talk during the W3C track
ACTION: Ben to look into Science Commons use case [recorded in] [CONTINUES]
Ben: making some progress; Use Case document
updated to include a little bit of Science Commons example
... still hope for a big realistic example to include
ACTION: Ben to update RDFa schedule on wiki to aim for last call on June 1 [recorded in] [CONTINUES]
Ben: I'd like feedback on this
ACTION: Elias to send email to list with use case from IBM [recorded in] [CONTINUES]
Elias: I also am looking for a use case that
adds more specifics
... deciding whether to go to WWW2007 or XTech; I submitted an RDFa/GRDDL talk
Ben: a Use Case can be more abstract; can show "here's the triples we'd like to produce"
ACTION: Mark produce more examples of applicability of n-ary relations from IPTC documents [recorded in] [CONTINUES]
ACTION: Michael continue work on the FAQ template that Elias started [recorded in] [CONTINUES]
Ben: Simone, comments on the FAQ from your new fresh eyes would be especially useful
Ben: I commited new updates to Primer and
Scenarios on Friday
... mostly editorial, related to comments received
-> Update to RDFa Scenarios, including response to Comments [Ben 2007-03-02]
Ben: one comment remaining on clarifying the
predicates should be cleaned up
... the document currently assumes namespaced classes
... are we comfortable enough with this to publish these WDs as they are?
Ralph: "publish, publish, publish" It's not going to be perfect
Steven: don't say I didn't warn you
Ralph: WAI-ARIA is emphasizing use of @role, so
I certainly don't think this discussion is over
... but let's publish and get comments
<EliasT> I'm +1 to publishing. (dialing back in)
PROPOSE: publish Primer and Scenarios as WDs
<mhausenblas> +1
<wing> +1
<RalphS> +1
<Simone> +1
Steven: warning, re: use of @class
RESOLVED Ask WG to publish Primer and Scenarios as WDs
Ben: I would like to respond to Antoine's comment about multiple @rel and @property before publishing; I think it is one sentence
Ben: we're not providing enough feedback on the test suite
<mhausenblas>
Michael: DanC has given us lots of test suite
feedback
... I'd like us to settle whether we're going to try to do conformance testing or not
Michael: I would like just to claim that "any
tool that claims to be RDFa-compliant has to correctly parse all the test
cases"
... i.e. passing test suite is necessary but may not be sufficient
... DanC was commenting about what conformance testing could or should be
... he felt that we could not do conformance testing
... I hope to prove that something is conforming but not to try to prove non-conformance
... many specifications already provide conformance tests, though perhaps not as strong as what I envision
Elias: is the problem just because of the word "conformance"? If so, let's drop that word
Michael: look at -> my
response to Dan
... an agent that claims to be RDFa-aware must pass the test suite, but passing the test suite does not guarantee the agent is conforming
Ben: what is the GRDDL test suite called?
Elias: W3C does not bless implementations, so
we're not required to do conformance tests
... all we need to do is provide guidance to developers
Steven: the real reason for a test suite is to test the _specification_
Ralph: I agree with Steven. DanC has used the
test suite to determine how the WG has responded to a question.
... if a question is raised, one should develop a test to show how to answer it
... Dan has encouraged us to write a test case in response to any technical discussion.
<mhausenblas> Conformance testing discussion on QA
Ben: so this seems to be about the usage of the
term "conformance"
... I recommend continuing to build the input/output tests but drop the word "conformance"
Michael: an agent can always trick the test suite by producing exactly what it requires yet not be a true implementation
Ben: so the test suite is to help developers, help test the specification, but *not* to test implementations
Elias: the SPARQL test suite gives a set of
files and the expected output
... every SPARQL developer downloads the test suite and runs it themselves, then they can debate the test suite
... the SPARQL test suite does not invoke any code; it's just the input and expected output
Mark: I agree that input and expected output is
what Michael was doing but I don't think that is all we should do
... I'd like to provide an interface for people to test their endpoints
... concerned about only REST-based endpoint, as we haven't specified a REST requirement
... we should stop at just describing inputs and outputs
... the other side of what Dan is getting at is 'anytime we mention RDFa in a document we should add to the test suite'
... the moment we create a sample or a line of text in a paragraph, reflect this in the test suite with an input and output document
Ben: are you suggesting we drop the REST test harness?
Mark: no, it's useful but don't make it
mandatory
... the REST harness should not be "the test suite" itself
<mhausenblas>
Michael: agree. First we should look at the manifest file
<mhausenblas>
Michael: rdfa-test-manifest is the source; everything else is generated by Wing's script
<mhausenblas>
<wing> test case results are still TTL
Michael: test runner is supplemental; it just
helps test REST-based endpoints, but I'm happy to move the test runner
elsewhere
... the mandatory part is just the manifest and the test case directory
... we've taken Mark's suggestion to add a SPARQL query to test that the expected triples are present
... the test asssertions are generated from the manifest
Elias: what property is available in the manifest to cite, e.g. the irc log where we discuss a test?
<mhausenblas>
Michael: see 'status'
Elias: I'm looking for a property that describes why the test was written
<mhausenblas> pls choose one from
Wing: we can use seeAlso
Elias: also record when we accepted or rejected a test
ACTION: Wing add a property to the test case schema for tracking origin and approval of an individual test [recorded in]
Mark: sounds like we're moving closer to a W3C test ontology
Wing: yep, we've been following that
Ben: are we outputting RDFa on the test suite page? :)
Michael: we've thought about that but aren't doing it yet
ACTION: Mark produce RDFa XHTML 1.1 module and spec [recorded in] [CONTINUES]
Mark: there's a document describing the
modularization
... I've given comments to Shane
... sadly, Shane is ill right now
... he had agreed to write the schemas
... the RDFa schemas I wrote don't (yet) drop in smoothly
... I will work on this myself in Shane's absence
... I won't be able to pick this up again until next week
... I'll do the schemas and then we can review
ACTION: Mark to put M12N schema up somewhere, and tell us where [recorded in] [CONTINUES]
Ben: would March 19 be a reasonable date to expect to see update schemas?
Mark: I have had schemas on my server but they're old
Ben: we should have some versions published in
the W3C process to get feedback
... I don't want this to be a rushed, last-minute thing
Mark: the work on XHTML modularization has been underway for a long time
Ben: people will be looking at every little detail when we go to REC
Mark: the draft is the primary thing; Shane has
aligned this with the latest XHTML Modularization spec
... we won't gain by getting people to look at year-old schemas
... point people to Shane's draft now
Ben: so let's hope to have schemas updated by March 19
Mark: I'll have the schemas done by March 12
<mhausenblas> next week
Mark's mashup demo
MarkB: asked to demonstrate SideWinder
... framework to put together application "widgets"
... how do you get RDF? While you're browsing, etc...
... sidebar in IE and, while you're browsing, looks for RDFa in main window
... converts it, stores it, and different running sidewinder applications can run queries
... to pull data out. Example: google map that periodically maps events browsed.
... browsing process adds triples as you go, don't pay any attention.
... separate process renders items found.
... next stage is to combine that with previous data.
... parser also does microformat processing.
... main thing we're trying to do is to build stuff into the browser.
... no demo just yet, but working on it soon.
ADJOURNED | http://www.w3.org/2007/03/05-rdfa-minutes.html | CC-MAIN-2019-51 | refinedweb | 1,728 | 65.96 |
NAME
evp - high-level cryptographic functions
SYNOPSIS
#include <openssl/evp.h>
DESCRIPTION_fromdata(3) page, or new keys can be generated using EVP_PKEY_keygen(3). EVP_PKEYs can be compared using EVP_PKEY_eq(3), or printed using EVP_PKEY_print_private(3). EVP_PKEY_todata(3) can be used to convert a key back into an OSSL_PARAM(3) array.InitInit(3) and EVP_OpenInit(3)_EncodeXXX and EVP_DecodeXXX functions implement base 64 encoding and decoding._fromdata(3), EVP_PKEY_todata), ENGINE_by_id(3)
Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at. | https://www.openssl.org/docs/man3.0/man7/evp.html | CC-MAIN-2021-43 | refinedweb | 106 | 52.97 |
boils down to reporting this error (or not) and retrying to process the failed input data later (or not). Part 1 of this post is about this aspect.
This implies that when processing a tuple, it is in general hard to be sure if it’s the first time we encounter it or if its content has already been partially applied to persistence. We therefore need to make our state update operations idempotent, which is the subject of the second part of this post.
Don’t be impressed by the size of this post, Storm is actually doing most of the work for us. All that is required really is understanding how it all fits togheter to plug things in a way that makes sense.
This post is based on Storm 0.9, Cassandra 2.0.4 and Kafka 0.7. I have put a toy project on github to illustrate several points discussed below. This project is actually adapted from the “room presence” example I introduced in a previous post.
Part 1: handling erroneous situation
Deciding when to ask to retry
A first simple error handling strategy is simply accepting the degradation of the computation quality caused by runtime errors. This could be the case for example if the topology is computing some real-time trend estimate on a sliding window over a very recent past, or if we are working on sampled data already, like the twitter public stream. If we chose to ignore such errors, the implementation is trivially simple, just wrap the topology logic with a big fat try/catch, report the errors somehow and do not let anything bubble up to Storm .
Most of the time however, we care about consistency and must make a careful decision about attempting to retry or not the failed data.
A typical example of runtime error is inbound data format issues. In that case retrying is of course pointless since it’s not going to get better the second time. We should log the faulting data instead and maybe ask some humans to investigate. Here is a simplistic example from the BytesToString Storm function from my toy project:
public class BytesToString extends BaseFunction { @Override public void execute(TridentTuple tuple, TridentCollector tridentCollector) { try { String asString = new String((byte[]) tuple.getValueByField("bytes"), "UTF-8"); tridentCollector.emit(new Values(asString)); } catch (UnsupportedEncodingException e) { logger.err("ERROR: lost data: unable to parse inbound message from Kafka (expecting UTF-8 string)", e); } }
On the other side, if an error is related to some unreachable external data sources, caused for example by a network partition, we should trigger a retry as described in the next section.
There are many other kinds of errors than the two mentioned above but the point remains: it’s important to distinguish re-tryable from non-retryable errors and react accordingly.
As a final note, be very careful when you decide not to report an error that occurred within a multiget of IBackingMap, because that function must return a list of the same size as the input list of keys. So in case of non retried error, we must return some result one way or another. Most of the time, if we choose not to retry errors in that case, it’s because something is already broken in persistence due to some past error and it’s too late to correct it. In the example below, the error occurs due to failed parsing of some data read from DB and the code just returns null values instead, which is equivalent to considering there is nothing in persistence (nothing useful at least). See also part 3 below for a possible solution for that case.
@Override public List<OpaqueValue> multiGet(List<List<Object>> keys) { try { return Utils.opaqueStringToOpaqueValues(opaqueStrings, HourlyTimeline.class); } catch (IOException e) { logger.err("error while trying to deserialize data from json => giving up (data is lost!)", e); return Utils.listOfNulls(keys.size()); // this assumes previous state does not exist => destroys data! } }
(well, this code from TimelineBackingMap actually replaces all data with nulls, which makes things worse, but it’s a toy project…)
Causing a Trident tuple to be replayed…
Once we have decided it makes sense to trigger a tuple replay, we just have to ask for it and Storm will do everything else (just plug the correct spout, cf next section). Technically, this is very simple: triggering a retry from within a Trident primitive like Function or Filter is as simple as throwing FailedException, like in the TimeLineBackingMap from my toy project, which includes example of retried and non-retried errors (Note that the code below from TimelineBackingMap assumes that any DB error is retryable, which is an over-simplification):
@Override public void multiPut(List<List<Object>> keys, List<OpaqueValue> timelines) {; List<OpaqueValue> jsonOpaqueTimelines; try { jsonOpaqueTimelines = Utils.opaqueValuesToOpaqueJson(timelines); } catch (IOException e) { System.err.println("error while trying to serialize data to json => giving up (data is lost!)"); return; } if (jsonOpaqueTimelines != null) { try { DB.put("room_timelines", toSingleKeys(keys), jsonOpaqueTimelines); } catch (Exception e) { logger.err("error while storing timelines to cassandra, triggering a retry...", e); throw new FailedException("could not store data into Cassandra, triggering a retry...", e); } } };
Storm will then propagate the error back to the spout in order to force a tuple replay. If we want the error to be reported in Storm UI, we can throw ReportedFailedException instead.
Another way, which I strongly discourage, is to let any other kind of RuntimeException bubble up to Storm. This essentially achieves the same result at much higher performance cost: it will trigger a worker node crash with automatically restart by Nimbus and all spout will resume reading from the latest known successful index (spout implementation like Kafka spout store their latest successfully processed offset in zookeeper for that purpose). This fail-fast strategy is part of the design of Storm (see documentation on worker supervision and fault-tolerance). In essence this achieves the same consistency guarantees as letting the spout replay some tuples, but the performance impact is of course bigger since we have a full JVM restart with a reset of all currently running topology instances. So never do that on purpose. Still it’s reassuring to be aware that if our nodes crash, the data is not broken and the flow will naturally continue.
A third situation when Storm decides to replay tuples is if they fail to reach the end of the topology before a configured timeout. More precisely, this mechanism is actually triggered by the spout which emitted the tuple if no ACK is received on time, so those replays could also be triggered in case the tuples are processed successfully but the ACK fail to reach the spout due to some network partition. The Storm parameters to control this are
topology.enable.message.timeouts and
topology.message.timeout.secs, and their default value according to defaults.yaml are “true” and 30 seconds. This is just one more reason why idempotence in our topologies is so important.
… and actually replaying tuples
Once the failure notification reaches the spout (or is generated by it, in case of timeout), we need to make sure the failed tuples will be replayed. Unless you are developing your own spout, this just boils down to choosing the right spout flavor. This choice impacts the way tuples are replayed (or not), so it must be aligned with the strategy in place to handle the replayed tuples within the topology, which is the subject of the next section. There exists 3 kinds of spouts:
- non transactional: no guarantee, but they can still be useful in some cases if the implementation you choose offers “at-least-once” guarantee
- transactional: not recommended because they might block the topology in some partition cases
- opaque: offers a weak-ish guarantee on replay in the sense that they reach tuple will be played at least once but in case of replay the emitted batches might not be identical. In practice all that matters when using those, which I recommend, is to make sure that topology is robust for this kind of flexible replays, which is discussed int he next section.
A final note on tuple and batch replay
I discuss above at tuple level because this makes design decisions simpler. In reality, asking Storm to replay a single tuple will trigger a replay of many other tuples contained in the same batch, some of them potentially error-free.
Part 2: idempotent handling of replayed tuples
The other side of the story is, now that we know tuples could possibly be processed several times, making sure the topology is idempotent, i.e. sending several times the same tuples at it won’t make the state inconsistent. The parts of a topology that have no side effect are of course not impacted by tuple replays.
Storm Trident documentation on state consistency is quite clear, so I’m just adding a bit of salt here.
In case our state update operations are already idempotent
If a state update operation is already idempotent by nature, then it’s already resilient to tuples replays and none of the Storm special mechanism is required.
This is the case of any “store by id” operation if the id value is fully based on inbound tuple content. For example, in my toy project I store occupancy sessions whose primary key is derived from a correlation id found in the inbound events, so in that case the write operation is already replay-ready because any replay will just overwrite an existing data with the same information without any data destruction (assuming we have ordering guarantee, which is true in this case).
public void multiPut(List<List<Object>> keys, List<RoomPresencePeriod> newOrUpdatedPeriods) { DB.upsertPeriods(newOrUpdatedPeriods); }
and in CassandraDB.java:
try { PreparedStatement statement = getSession().prepare("INSERT INTO presence (id, payload) values (?,?)"); execute(new BoundStatement(statement).bind(rpp.getId(), periodJson)); } catch (Exception e) { logger.error("error while contacting Cassandra, triggering a retry...", e); new FailedException("error while trying to record room presence in Cassandra ", e); }
Making read-update-write operation idempotent as well
I described in a previous blog post how Storm enables us to implement operations that performs the following without requiring DB-locks and still avoid race conditions:
- read previous state from DB,
- update state in memory according to new tuples data,
- save new state to DB
One beauty of storm is that in order to handle replayed tuples without destroying state we only have to adapt steps 1 and 3. This is super important: we can now implement all our processing logic in step 2 as if each tuple were played only once and not caring at all about replays (as long as we are “pure”, see remark below…). This is what they mean by “storm has exactly once semantic”.
Moreover, if we have an in-house implementation of 1 and 3, making them replay-ready is just a matter of wrapping them with existing Storm classes. The most robust way of doing so is using the Opaque logic, at the cost of storing twice each state, as explained in Trident documentation on transaction spout.
Even better, there already exists plenty of Opaque BackingMap implementation for many backends like Cassandra or Mysql in storm-contrib, so most of the time there is really nothing to do apart from choosing the right one.
The most important point to take away is that in order to use an Opaque BackingMap that handles replayed-tuples, we must use a spout that respects opaque pre-conditions, as summarized in this matrix.
In case we need to implement our own BackingMap for some reason, the only thing we have to do is making it store a current and previous version of the data and a transaction id. Here is a simplistic example from my toy project (but really, consider storm-contrib before coding something like that):
public void put(String table, List<String> keys, List<OpaqueValue> opaqueStrings) {; // this should be optimized with C* batches... for (Pair<String, OpaqueValue> keyValue : Utils.zip(keys, opaqueStrings)) { PreparedStatement statement = getSession().prepare(format("INSERT INTO %s (id, txid, prev, curr) values (?, ?, ?, ?)", table)); OpaqueValue opaqueVal = keyValue.getValue(); execute(new BoundStatement(statement).bind(keyValue.getKey(), opaqueVal.getCurrTxid(), opaqueVal.getCurr(), opaqueVal.getPrev())); } } public List<OpaqueValue> get(String table, List<String> keys) {; List<OpaqueValue> vals = new ArrayList<>(keys.size()); ResultSet rs = execute(format("select id, txid, prev, curr from %s where id in ( %s ) ", table, toCsv(keys) )); Map<String, OpaqueValue> data = toMapOfOpaque(rs); for (String key: keys){ vals.add(data.get(key)); } return vals; }
Then the only thing to do to actually obtain the exactly-once semantic of Trident is to wrap it within an OpaqueMap, like this:
public static StateFactory FACTORY = new StateFactory() { public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) { return OpaqueMap.build(new TimelineBackingMap(new CassandraDB(conf))); } }
What’s happening behind the scene is that the OpaqueMap will choose which previously stored state (“curr” or “prev”) to expose to our update logic depending on the transaction id associated with the current batch of tuples and the one found in persistence. This transaction ID is provided by the spout, so this is the reason why keeping spout and state choices aligned is so important: state make assumption about the meaning of each transaction ids.
Do not break the previous instance!
Let’s come back a minute to step 2 of the read-update-write sequence mentioned above. Now that we know that an Opaque logic needs to store both the new and old version of any state, look at the following Reducer code and try to determine why it’s broken:
public RoomPresencePeriod reduce(RoomPresencePeriod curr, TridentTuple tuple) { LocationChangedEvent event = (LocationChangedEvent) tuple.getValueByField("occupancyEvent");; if (ENTER == event.getEventType()) { curr.setStartTime(event.getTime()); // buggy code } else { curr.setEndTme(event.getTime()); // buggy code } return curr; }
Adepts of functional programming call this an “impure” method because it modifies its input parameters. The reason it breaks Storm opaque logic is that now both the “current” and “previous” java references actually refer to the same instance in memory. So that when the opaque logic is persisting both the previous and current version of some piece of state, really it’s saving twice the new version, and the previous version is therefore lost.
A better implementation could be something like this
public RoomPresencePeriod reduce(RoomPresencePeriod curr, TridentTuple tuple) { LocationChangedEvent event = (LocationChangedEvent) tuple.getValueByField("occupancyEvent");; RoomPresencePeriod updated = new RoomPresencePeriod(curr); // copy constructor if (ENTER == event.getEventType()) { updated.setStartTime(event.getTime()); } else { updated.setEndTme(event.getTime()); } return updated; }
Part 3: human errors: replay all
As a final note, one has to realize with humility that no matter how much efforts and safeguards like those described above we put in place, we will still deploy bugs in production (and be sorry about that, I swear!). In case of a data processing platform, bugs potentially mean data-destroying bugs, which is bad when data is our business. In some cases, we’ll only discover data is broken after the fact, like explained on the note on multiget above.
In his Big Data book, Nathan Marz describes a simple replay-all idea based on the lambda architecture to work around that idea. A short summary of that book is also available here. | http://www.javacodegeeks.com/2014/02/error-handling-in-storm-trident-topologies.html | CC-MAIN-2015-35 | refinedweb | 2,537 | 50.06 |
The information needed to query your specific environment, to optimize your searches, and provide the custom context needed to diagnose failures and rapidly gain insights can be easily added to build scans.
You can complete this tutorial in:
1 minute (read the Introduction)
5-10 minutes (read the Introduction and Tour)
15-20 minutes (read the Introduction and Tour and perform the Hands-on Lab)
Introduction
Gradle Enterprise build scans already contain a vast amount of information about what is happening in your builds.
Because every environment is different, we also understand that there typically is additional metadata that you will want to have included in your build scans.
This information helps you to more quickly diagnose failed builds, identify ownership or other custom attributes for your builds, and are especially useful for providing integration links to other federated systems involved in your CI/CD pipeline.
There are three different mechanisms to allow you to add data to your build scans:
links — hyperlinks to things like CI build records, ticketing systems, source code control systems.
tags — used for attributes such as build type [CI or dev], environment, owner, application, etc.
custom values — name/value pairs that are used for things like code scanning results, attaching metric values, posting computed results from querying some other system.
The ability to attach extended metadata to build scans can make their application to use cases such as reducing debugging time, reducing the occurrence of flaky or false alarms, and identifying trends to help keep builds fast that much more powerful and effective - saving you and your team valuable time and money.
Tour: Extending build scans
Distinguish CI build scans from developer build scans
This tutorial assumes some basic familiarity with the Gradle build scan plugin and its configuration model. If you need to familiarize yourself with that, we recommend you read this before continuing.
In most situations, a tag is used to distinguish CI builds from local developer builds. The management of CI builds is sometimes done mostly by different people, and in many cases, it is useful to filter scan lists to show only CI builds.
Most CI servers (e.g. Jenkins) will set standard environment variables and the standard technique is to set a tag conditional to the presence of one of those variables in the build.
Here is a trivial code example of doing this:
// Local or CI if (System.getenv('CI')) { buildScan.tag 'CI' buildScan.link 'CI Build', System.getenv('BUILD_URL') } else { buildScan.tag 'LOCAL' }
// Local or CI if (System.getenv("CI") != null) { buildScan.tag("CI") buildScan.link("CI Build", System.getenv("BUILD_URL")) } else { buildScan.tag("LOCAL") }
Here we set a tag (and also a link) based on an environment variable. The usage of links in this fashion demonstrates linking back to the CI server from the build scan, which is a common use case.
We can find out the builds that have the CI tag by entering
CI in the Tags filter at the top of the build scan list and clicking the Search button. Go ahead and do that now.
You should see that 8 of the builds are so tagged.
You can optionally repeat these steps for the tag
LOCAL.
For either case, click on one of the build scans that come back as the result of the search, and you will see the tag prominently displayed at the very top of the scan page.
Add source control information to your build scans
A very useful addition to your build scans is to embed source control information. For example, if you are using Git, you can attach the commit ID, branch, repository pointers, and workspace status to the build scan. Using GitHub API’s, you can also do things like post a Gist that contains the diffs between the workspace and the last pushed commit.
Open this build scan to learn more.
First, notice that the tag
dirty is visible at the top. This indicates that there are un-committed changes in the workspace.
You will also notice the
Source link, which allows for navigation to the Github repository (even though this one is private to Gradle Inc.).
Using the left-hand navigation, select the
Custom Values build scan section, and you will see that we have also computed and written as custom values the Git branch name, commit ID, and the output of the
git status command.
Here is a code sample that shows how some of these values can be inserted into your build scans through your Gradle build scripts:
// Git commit id def commitId = 'git rev-parse --verify HEAD'.execute().text.trim() if (commitId) { buildScan.value 'Git Commit ID', commitId buildScan.link 'Source', "$GITHUB_REPO/tree/$commitId" } // Git branch name def branchName = 'git rev-parse --abbrev-ref HEAD'.execute().text.trim() if (branchName) { buildScan.value 'Git Branch Name', branchName } // Git dirty local state def status = 'git status --porcelain'.execute().text if (status) { buildScan.tag 'dirty' buildScan.value 'Git Status', status }
// Execute a CLI command and return the output val execute = { p: String -> ProcessBuilder(p.split(" ")).start().apply { waitFor() }.inputStream.bufferedReader().use { it.readText().trim() } } // Git commit id val commitId = execute("git rev-parse --verify HEAD") if (!commitId.isNullOrEmpty()) { buildScan.value("Git Commit ID", commitId) buildScan.link("Source", "$GITHUB_REPO/tree/$commitId") } // Git branch name val branchName = execute("git rev-parse --abbrev-ref HEAD") if (!branchName.isNullOrEmpty()) { buildScan.value("Git Branch Name", branchName) } // Git dirty local state val status = execute("git status --porcelain") if (!status.isNullOrEmpty()) { buildScan.tag("dirty") buildScan.value("Git Status", status) }
Surface static code analysis issues in build scans
Your build might automate many different tools that generate output about your code. Checkstyle is an example of a code checker that is not (currently) fully integrated into a Gradle core plugin. Let’s use that to demonstrate how to run an external tool and then brand the build scan with a set of values; in this case we will annotate the build scan with the output of the checkstyle command.
This build scan deep link takes you directly to the custom values for this build scan that shows you the checkstyle output.
Here is a code sample that demonstrates all it takes to cause this to happen:
// Checkstyle violations gradle.taskGraph.afterTask { Task task, TaskState state -> if (task instanceof Checkstyle) { if (state.failure) { def checkstyle = new XmlSlurper().parse(task.reports.xml.destination) def errors = checkstyle.file.collect { String filePath = task.project.rootProject.relativePath(it.@name.text()) it.error.collect { "${filePath}:${it.@line}:${it.@column} \u2192 ${it.@message}" } }.flatten() errors.each { task.project.buildScan.value 'Checkstyle Issue', it } } } }
import groovy.util.XmlSlurper import groovy.util.slurpersupport.NodeChildren import groovy.util.slurpersupport.NodeChild ... gradle.taskGraph.afterTask { if (this is Checkstyle && state.failure != null) { val x = XmlSlurper().parse(reports.xml.destination) val files = x.getProperty("file") as NodeChildren files.forEach { f -> val file = f as NodeChild val filePath = rootProject.relativePath(file.attributes()["name"]) val errors = file.getProperty("error") as NodeChildren errors.forEach { e -> val error = e as NodeChild val attr = error.attributes() val msg = "${filePath}:${attr["line"]}:${attr["column"]} \u2192 ${attr["message"]}" project.buildScan.value("Checkstyle Issue", msg) } } } }
Reach out for help when local build fails to succeed
Expanding on the earlier example where we annotate the build scan with Git properties, we now go a step further and actually take the diffs and create a Gist from them.
If a local build fails, a build team engineer can now look at possible build script changes that are in the developer’s workspace and determine in any of those diffs played a role in the failure, potentially saving a lot of time to determine root cause.
Examine this build scan.
Notice the Diff link at the header of the main area. If you click on that link, you will go to a Gist which clearly shows that a lot of local changes to tests occurred, and possibly those changes are what is causing some test failures to appear in this particular build scan.
Categorize build failures
Your workflow for build failures might be different depending on whether the failure was a true build failure or if it is a test failure.
But furthermore, it can be interesting to further classify failures and perform queries based on the failure type. For example, to know how many Java compilation failures we are seeing versus other types of failures.
To see this in action, view this build scan.
We have used the deep link to take you directly to the custom values section, and you can see that this failure is a compilation failure.
You can get further details about the compile failure by navigating to the Failure section of the build scan via the left-hand navigation.
Here is the code snippet from a build script that computes these custom values:
buildScan.buildFinished { result -> if (result.failure instanceof LocationAwareException) { if (result.failure.cause instanceof TaskExecutionException) { def value if (result.failure.cause.task instanceof Test) { value = 'TEST' } else if (result.failure.cause.cause instanceof CompilationFailedException) { value = 'COMPILATION' } else { value = 'UNKNOWN_TASK' } buildScan.value 'FAILURE', value } else { buildScan.value 'FAILURE', 'OTHER' } } }
buildScan.buildFinished { if (failure is LocationAwareException) { if (failure.cause is TaskExecutionException) { val cause = failure.cause as TaskExecutionException val value = if (cause.task is Test) { "TEST" } else if (cause.cause is CompilationFailedException) { "COMPILATION" } else { "UNKNOWN_TASK" } buildScan.value("FAILURE", value) } else { buildScan.value("FAILURE", "OTHER") } } }
type
FAILURE=COMPILATION into the search box for Custom values.
You should see that we have encountered so far 4 builds that suffered a compilation error.
Hands-on Lab: Extending build scans
Read on to go one level deeper.
Prerequisites
To follow these steps, you will need:: Generating extended metadata in Gradle Enterprise build scans
Open a terminal window and clone the GitHub repository build scan quickstart.
custom-values with
git checkout custom-values.
Using the text editor of your choice, modify the build scan configuration in
build.gradle to point to your Gradle Enterprise server instance:
All of the examples we discussed in the tour are combined in this example, and the code can be viewed in the build script
customData.gradle in the root directory of the repository now.
Run the build with
gradle build and open the build scan that logs at the conclusion of the build. You will be able to see the custom values for checkstyle, links, CI tags, etc.
Conclusion
This tutorial has covered a few common scenarios for adding extended data to build scans. This information can greatly assist you and your team in fully leveraging the power of Gradle Enterprise.
We would welcome seeing your use cases for extended data and hope to see your suggestions and code in the public GitHub repository! | https://docs.gradle.com/enterprise/tutorials/extending-build-scans/ | CC-MAIN-2019-13 | refinedweb | 1,773 | 56.45 |
What is i2r?I2c, spi, serial?
I2C is designed for chaining - just connect both devices to the SDA and SCK lines, and make sure they have nonconflicting addresses.
#include <Wire.h> // bring in Wire Library//Then you can set up some addresses to use, these are for MAX6953 for example:// I2C device address is 1 0 1 A3 A2 A1 A0 with AD1, AD0 both low#define COMMAND_ADDRESS (0x50);#define CONFIG_ADDRESS (0x04);#define INTENSITY10_ADDRESS (0x01);#define INTENSITY32_ADDRESS (0x02);#define SCANLIMIT_ADDRESS (0x03);#define DIGIT0_ADDRESS (0x60);#define DIGIT1_ADDRESS (0x61);#define DIGIT2_ADDRESS (0x62);#define DIGIT3_ADDRESS (0x63);
void setup() { // start up I2C, uses Analog 5 for Clock, Analog 4 for data Wire.begin(); // nothing in () because we are the master/* Need this stuff now?? Try with & without, Wire.h & Wire.begin might do it for you: // define stuff to use for ShiftOut // SCL, SDA, BLINK //set pins to output so you can control the shift register pinMode(Blink, INPUT); // Blink pinMode(clockPin, OUTPUT); // SCL pinMode(dataPin, OUTPUT); // SDA*/ // Send config register address Wire.beginTransmission(address); Wire.send(COMMAND_ADDRESS); Wire.send(CONFIG_ADDRESS); // Connect to device and the byte Wire.send(0x01); // low byte Wire.endTransmission();
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=62931.0;prev_next=prev | CC-MAIN-2016-40 | refinedweb | 225 | 54.73 |
Technical Support
On-Line Manuals
CARM User's Guide
Discontinued
#include <math.h>
unsigned char _chkfloat_ (
float val); /* number to check */
The _chkfloat_ function checks the status of the
floating-point number val.
The _chkfloat_ function returns the status of the
floating-point number val:
_chkdouble_
#include <intrins.h>
#include <stdio.h> /* for printf */
float f1, f2, f3;
void test_chkfloat (void) {
f1 = f2 * f3;
switch (_chkfloat_ (f1)) {
case 0:
printf ("result is a number\n"); break;
case 1:
printf ("result is zero\n"); break;
case 2:
printf ("result is +INF\n"); break;
case 3:
printf ("result is -INF\n"); break;
case 4:
printf ("result is NaN. | http://www.keil.com/support/man/docs/ca/ca__chkfloat_.htm | CC-MAIN-2020-16 | refinedweb | 106 | 69.11 |
Electric motors can be found inside just about everything you use; your phone uses a vibration motor, coffee machines have a water pump, and your car uses them!
Learning how to control an electric motor is a great skill to retain..
Hardware and Assembly:
This is where the MC33932 Motor shield comes in. It allows you to control two DC motors, or one bipolar stepper motor.
In this tutorial, we will show you how to assemble the shield and how to use it to drive both types of motors. The shield comes with all the headers and connectors you will need to put the shield together, but you will need an Arduino Board (Uno, Leonardo, Mega) to control the shield.
Start by inserting all the headers in their respective spots on the board. No need to solder anything just yet, we will do all four at the same time.
Next we will use a piece of masking tape to hold all four pieces on, so that you can flip it over before soldering.
Solder one pin on each of the headers so that you can remove the tape. Once the tape is off, you can check the alignment of the headers before soldering all the pins in.
Here is what it looks like all soldered up. Next step is to solder in the screw terminals.
Go ahead and place your screw terminals in place and use a piece of tape to hold them down.
Flip over the shield and solder the remaining 6 joints. Once you are done, you can remove the tape and mount the completed shield on your Arduino Board. We chose to work with an UNO, since we have a gazillion of these laying around the shop.
DC Motor Connection:
The completed board/shield assemble should look like this..
Here is the completed motor shield mounted on an Arduino Uno and connected to a DC motor. The rest of the wires from the motor are for a built in encoder, which we will not be using for this tutorial. Now for the code!
DC Motor Code:
We have already written some code for this shield, which you can download here. It includes the code to control both channels, as well as one bipolar stepper motor. Go ahead and open up the Dual_DC_Motor.ino sketch.
int PWMA = 3; // PWM Pin for Output A int PWMB = 5; // PWM Pin for Output B int DIRA= 8; // DIR Pin for Output A (There is a Mistake on Silkscreen on V1 of the board) int DIRB= 7; // DIR Pin for Output B (There is a Mistake on Silkscreen on V1 of the board) // the setup routine runs once when you press reset: void setup() { pinMode(DIRA, OUTPUT); // Make Direction Pins Outputs pinMode(DIRB,OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(DIRA,LOW); // Set Direction of Output A analogWrite(PWMA, 60); // Set Speed for Output A (0-255) delay(1000); // Delay 1 Second digitalWrite(DIRA,HIGH); // Switch Direction of Output A delay(1000); // Delay 1 Second analogWrite(PWMA,0); // Turn off Output A by setting speed to 0 digitalWrite(DIRB,LOW); // Set Direction of Output B analogWrite(PWMB,60); // Set Speed for Output B (0-255) delay(1000); // Delay 1 Second digitalWrite(DIRB,HIGH); // Switch Direction of Output B delay(1000); // Delay 1 Second analogWrite(PWMB,0); // Turn off Output B by setting speed to 0 }
Here silkscreen on our board because we accidentally which).
Here you can see the proper way to power the shield. Use an external power source connected directly to the shield. The shield will automatically route power to the UNO, so you do not need to power it separately..
#include <Stepper.h> const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution // for your motor // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 7,8); int PWMA = 3; // PWM Pin for Output A int PWMB = 5; // PWM Pin for Output B void setup() { // set the speed at 60 rpm: myStepper.setSpeed(60); // The 255 can be lowered to reduce power to the steppers. analogWrite(PWMA, 255); // Set Speed for Output A (0-255) was added to turn on Channel A analogWrite(PWMB, 255); // Set Speed for Output B (0-255) was added to turn on Channel B //); }
The sample code aboveV.
Next we need to set our PWM pins HIGH. We can do this using the analog direction.
Now connect your stepper; channel A goes to one coil, and channel B goes to the second coil. Connect each pair to the shield; if you got it right, the motor will turn one full revolution, and then return back home. If the motor fails to turn, flipping one pair will fix the problem.
That concludes our motor shield tutorial. Now you are ready to put these motors to some good use.
If you have any questions about this tutorial, don't hesitate to post a comment, shoot us an email, or post it in our forum! | http://www.jayconsystems.com/tutorials/MC33932-Dual-Motor-Shield | CC-MAIN-2017-13 | refinedweb | 841 | 67.49 |
Hi,
I would like to use aerospike python client within uwsgi-python (nginx).
When I try to retrieve values using a key, the query works fine.
records = client.get(“d42c62c2a7562a39-0”)
{‘user_id’: 0, ‘ssid’: 0, ‘ts’: 1452676728, ‘sid’: ‘d42c62c2a7562a39’ }
But when I try to retrieve the values using a query, this does not work.
query = client.query(“my_namespace”,
“my_set”)
query.select(‘sid’,‘ssid’)
query.where(predicates.equals(‘user_id’ , 0 ))
records = query.results()
The process seems to be blocked in query.results(). The query is working fine when executed inside aql or script python.
I do not understand what is wrong in executing a query inside uwsgi-python ?
Thanks | https://discuss.aerospike.com/t/uwsgi-python-blocked-in-query-results/2383 | CC-MAIN-2018-30 | refinedweb | 108 | 76.72 |
PRANG::Graph::Meta::Attr - metaclass metarole for XML attributes
package My::XML::Language::Node; use Moose; use PRANG::Graph; has_attr 'someattr' => is => "rw", isa => $str_subtype, predicate => "has_someattr", ;
When defining a class, you mark attributes which correspond to XML attributes. To do this in a way that the PRANG marshalling machinery can use when converting to XML and back, make the attributes have this metaclass.
You could do this in principle with:
has 'someattr' => traits => ['PRANG::Attr'], ...
But PRANG::Graph exports a convenient shorthand for you to use.
If you like, you can also set the
xmlns and
xml_name attribute property, to override the default behaviour, which is to assume that the XML attribute name matches the Moose attribute name, and that the XML namespace of the attribute is empty. Note if you specify the
xmlns for an attribute, it must have that namespace set, or it is not the same attribute.
If you set the
xml_required property, then it is an error for the property not to be set when parsing or emitting.
Setting the
xmlns attribute to
* will allow any XML namespace to be set for that attribute. In this case, you should also set the
xmlns_attr property, which should refer to another attribute which will record which XML namespace URI was passed in. This introduces a potential ambiguity; the same attribute may be passed in multiple times, with different XML namespaces.
You can also set
xml_isa, which currently if set will not check the type constraint against the input on marshall in. In the future it will specify the type constraint to apply at marshall in time, instead of waiting for the constructor to apply one.
PRANG::Graph::Meta::Class, PRANG::Graph::Meta::Element
Development commissioned by NZ Registry Services, and carried out by Catalyst IT -
Copyright 2009, 2010, NZ Registry Services. This module is licensed under the Artistic License v2.0, which permits relicensing under other Free Software licenses. | http://search.cpan.org/~mutant/PRANG-0.17/lib/PRANG/Graph/Meta/Attr.pm | CC-MAIN-2018-09 | refinedweb | 322 | 59.23 |
1.Get a Quote
Solar Brass Outdoor Integrated LED 2500K 10-Lumens Vintage Bulb Landscape Pathway Light Set (6-Pack) by Hampton Bay (319) Solar Golden Bronze Outdoor Integrated Filament LED Path Light (6-Pack) by Hampton Bay (249) Top Rated. Solar Black LED 10 Lumens Path Light (5-Pack) by Hampton Bay There are over 3 special value prices on Landscape
300w-600w 12v 30w solar street lighting used in pulic square-operated with pole remote control. au $14.63. au $16.62 previous price au $16.62 300/450w led solar power outdoor wall street light pir motion sensor lamp. au $17.23 + au $8.99 shipping. 300w outdoor solar street wall light sensor pir motion led lamp remote t k. au $17.83Get a Quote
Find here Solar Garden Lights, Solar Power Garden Light manufacturers, suppliers & exporters in India. Get contact details & address of companies manufacturing and supplying Solar Garden Lights, Solar Power Garden Light, Solar Powered Garden Light across India.
import quality solar led street light (24w) at supplied by experienced manufacturers at global sources. aio 60w led solar street lights integrated solar power street lights us$ 330 - 350 / set; 100 sets (min. order) facotry outdoor garden all in one integrated 10w led integrated solar sensor led street light us$ 76.95 - 81 / set.
langy official high brightness all in one radar sensor 180w solar led outdoor light pir motion sensor in UK. .
Local store prices may vary from those displayed. Products shown as available are normally stocked but inventory levels cannot be guaranteed For screen reader problems with this website, please call 1-800-430-3376 or text 38698 (standard carrier rates apply to texts)Get a Quote
Buy Solar Lights For Garden and get the best deals at the lowest prices on eBay! Great Savings & Free Delivery / Collection on many items
new products esavior green energy solar street light 60w 120w 180w 240w high brightness 2385 led ip65 outdoor solar flood light. us $58.80 - 83.34 / piece; free shipping; 2018 new solar powered lighting market in Central Luzon 20w 30w 40w 50w 100w high brightness 3030 led ip65 outdoor solar flood light dhgate.com is your new choicest seller of the outstanding quality of solar lights atGet…Get a Quote
LITOM 12 LEDs Solar Landscape Spotlights, IP67 Waterproof Solar Powered Wall Lights 2-in-1 Wireless Outdoor Solar Landscaping Light for Yard Garden Driveway Porch Walkway Pool Patio 6 Pack Warm White #1 Best Seller 4.0 out of 5 stars Good lights for price. Reviewed in the United States on September 17, 2018. Color:
solar spot lights (7) solar powered parking lot light price in Pakistan (8) solar plaza lights (2) solar underground lights (0) street light poles (2) solar packages (33) solar panels (17) victron energy (0) latest. categories : solar packages. not only does this inverter work in a complete solar power system,Get a Quote
Outdoor Lighting Fixtures Outdoor Security Lights Landscape Lights Decorative Outdoor Lighting Outdoor LED Lighting Outdoor Solar Lighting Outdoor Light Bulbs White Brown Black Blue Red Green Gray Multicolor Silver Gold Clear Yellow Purple Beige Orange Pink Bronze Other Off-White Metallic Outdoor Lighting Price $ Min $ Max. Go. $0 - $20Get a Quote
TSL Solar Power SunFlower 2PC, Sun Flower Garden Decor Solar, Solar Powered Sunflower, Sunflower Led Lamp, Solar Garden Lights Decor Gifts MariaArtandDesigns Sale Price $16.00 $ 16.00Get a Quote
Hanging Solar Lights Outdoor - 2 Pack Solar Powered Waterproof Landscape Lanterns with Retro Design for Patio, Yard, Garden and Pathway Decoration ( Warm Light ) 4.3 out of 5 stars 2,022 #1 Best Seller in Outdoor Lanterns.
new design ce&rohs solar microwave 8000mah mini portable system high quality solar power lighting 12v 20ah solar street light rechargeable (28) solar/wind hybrid streetlights (8) solar lanterns (21) standard battery chargers (69) lifepo4 battery chargers (3) emergency mobile phone chargersGet a Quote
For better protection, connect a 2.7V zener diode between SBAT pin and ground to maintain 2.7V if the solar cell voltage goes above 2.7V. Solar cell. A 1.5V, 100mA solar cell is sufficient to charge the battery and light the LED. It can be mono-crystalline or polycrystalline. The nominal current of the solar cell should not be more than 800mA.
set of 4 solar powered metal deck lights easily light up any pathway, patio, deck, sidewalk or staircase with this set of four, bronze colored, solar powered metal deck lights! these ultra-durable solar street light dealers in lucknow, can be easily mounted on any flat surface and feature auto on/off functionality for a truly hands-free lightingGet a Quote For Garden and get the best deals at the lowest prices on eBay! Great Savings & Free Delivery / Collection on many.
as a specialist of charger products for sale solar light, zhongshan xiaolan town ruiyi street lamp factory can offer you comprehensive selections of goods in this industry 12v 24v cob led solar street 120w 30w 40w 50w 60w 80w aio2. factory oem odm galvanized street light pole parts 5m 6m 7m 8m 9m with q235 steel. waterproof outdoor all in one led.
reliable solar led street light from Solar china suppliers with competitive 24w all in two solar street light on jumia and high-quality. view our web! mobile: +86-139 2539 5351 e-mail : Solar solar power die-casting aluminum waterproof outdoor 180 watt solar led street light.Get a Quote
2 Pack Solar Fireworks Light Outdoor LED String Lights 8 Modes Starburst Lights Pathway Patio Lawn JOFIIN 4 out of 5 stars (20) $ 23.99 FREE shipping Add to Favorites Outdoor Solar Garden Lights for Pathway, Landscape, Porch, Lawn, Weddings, Special Events Decoration Ice Cube LED Solar Garden Decor Lights $ 1.60 Original Price $1.60" (10%
malaysia canadian solar buyers directory provides list of malaysia canadian solar importers, buyers and purchasers who wanted to import canadian solar in malaysia. malaysia solar garden light buyers malaysia 150w solar panel street light on amazon buyers. malaysia. contact buyer. accfree industrial supply malaysia just a student trying to buy solarGet a Quote | https://www.gierman.pl/77d8b844c1a62cc1ee3d7949c08ecf94 | CC-MAIN-2021-39 | refinedweb | 1,015 | 59.13 |
Release 2.0.0
June 2007
These are frequently asked questions regarding Pojocache.
What is PojoCache?
PojoCache
attach
, for example), then any POJO get/set
method will be
intercepted by PojoCache to provide the data from the
cache.
What is the relationship between Cache and PojoCache?
The core JBoss Cache library
Cache
is a traditional generic distributed cache system.
PojoCache uses Cache as the underlying distributed state system to achieve POJO caching. It uses Cache as
a
delegate. As a result, all the replication aspects are configured with the Cache configuration XML.
Additionally, PojoCache also has API to expose the Cache interface (via
getCache()
API).
What is the difference between Cache and
PojoCache?
Think of PojoCache as a Cache on steroids. :-)
Seriously, both are cache stores-- one is a generic cache and the other other one POJO Cache.
However, while Cache.
How does PojoCache work then?
PojoCache uses the so-called AOP technology (aspect oriented programming) to do field level
interception. Currently, it uses
JBoss Aop
library to do it.
What's changed between 1.x and 2.x release then?
Starting in 2.0 release, we have a separate library for PojoCache,joCache
interceptor stack (that can be left as default).
Additionally, here are the changed features:
New APIs. It replaces
putObject, removeObject, and get
with
attach, detach, and find
.
New POJO based events that a user can subscribe to.
New configuration pojocache-aop.xml specifically for PojoCache, in addition to
the regular cache-service.xml for the delegating Cache.
New package namespace (
org.jboss.cache.pojo)
for PojoCache.
The previous
org.jboss.cache.aop
space has been deprecated.
What are the steps to use the PojoCache feature?
In order to use PojoCache, you will need to:
prepare POJO. You can do either via xml declaration or JDK50 annotation.
This is the step to declare your POJO such that it will be instrumented by
JBoss Aop
.
instrumentation. You will need to instrument your POJO either at compile- or load-time.
If you do it during compile-time, you use so-called an aop pre-compiler (aopc) to do bytecode
manipulation.
If you do it via load-time, however, you need either a special system class loader or, in JDK50,
you can
use the javaagent option. Either way,
JBoss Aop
will byte code manipulate your POJO
class such that all field access can be intercepted..
What is the JDK version required to run PojoCache 2.x?
PojoCache 2.x requires JDK5.0 since it uses the annotation extensively.
Can I run PojoCache as a standalone mode?
Yes, same as the core Cache library, you can run PojoCache either as a standalone or
inside an application server.
What is the JBoss AS recommended version to run PojoCache 2.x?
PojoCache can be run either in AS4.0.5 (and up) and 5.0. But either way, it will require
JDK5.0 though.
Can I pre-compile the aop classes such that I don't need to
use the system classloader and jboss-aop configuration xml during runtime?
aopc
. In addition, please also check out the
examples
directory for concrete examples.
In PojoCache 2.x release, do I still need
annoc
?
The annoc precompiler is needed for JDK1.4 style annotation. For 2.x release, since
we require the use of JDK5.0, there is no need to use annoc anymore.
How do I use aopc on multiple module directories?
In aopc, you specify the src path for a specific directory. To
pre-compile multiple ones, you will need to invoke aopc multiple
times.
Does PojoCache provide POJO event subscription?
Yes, since 2.0, you can use PojoCacheListener to subscribe to events
such as POJO attach and detach and field updates. And if you need some customization,
you can also use the Obervable pattern directly. TO see an example, please check
out the test case:
org.jboss.cache.pojo.observer.LocalTest.java.pojo.interceptor.dynamic.CacheFieldInterceptor
to this POJO
to perform object mapping and relationship management.
Note that to add your POJO, you should declare all the fields
to be "prepared" as in the example.
What's the difference between
jboss-aop.xml
pojocache-aop.xml
?
pojocache-aop.xml
is essentially a
jboss-aop.xml
,
except it is used specifically for PojoCache. The analogy is similar to JBoss' own
MBean service file
jboss-service.xml
, for example. So in our documentation,
we will use these two terms interchangeably.
Can I use annotation instead of the xml declaration?
Yes, in release 2.0, you can use JDK5.0 annotation to
instrument your POJO..pojo.annotation.Transient
and
@org.jboss.cache.pojo.annotation.Serializable
field level annotations?
In 2.0, we also offer two additional field-level annotations. The first one,
@org.jboss.cache.pojo.Transient
,
when applied has the same effect as declaring a field
transient
. PojoCache
won't put this field under management.
The second one,
@org.jboss.cache.pojo.Serializable
when applied,
will cause PojoCache to
treat the field as a Serializable object even when it is
@org.jboss.cache.pojo.Replicable
.
attach.attach("list/test", list); // Put the list under the a
attach
, "attach" and "detach" often, it will be slow in performance.
Can I use eviction to evict POJO from the memory?
No. In 2.0 release, we have deprecated the POJO-based eviction policy since it has always been
problematic in earlier release. The main reason is that when we evict a POJO from
the memory, the user has no ways of knowing it. So if the POJO is accessed after the
eviction, there won't be any PojoCache interception (e.g., it will be just like ordinary POJO),
but user may still expect that it will be managed by PojoCache.
So what do I do now?
In order to keep your memory from overflowing, you can use the passivation feature that comes with
the core Cache. Passivation uses the combination of eviction and cache loader such that when the
items are old, it will be evicted from memory and store in a cache store (can be DB or file). Next time,
when the item needs to be accessed again, we will retrieve it from the cache store.
In this sense, PojoCache level is not aware of the passivation aspect. It is configured through
the underlying cache xml.
I am having problems getting PojoCache to work, where can I get information on troubleshooting?
Troubleshooting section can be found in the following
wiki link
. | https://docs.jboss.org/jbosscache/2.0.0.GA/faq-pojo/en/html/index.html | CC-MAIN-2021-39 | refinedweb | 1,075 | 61.33 |
SQL Statements
This list of SQL statements provide a record of SQL queries and other operations for each table, including insert, update, and delete. These SQL statements are linked to a query plan, and this link provides the option to freeze this query plan.
The system creates an SQL Statement for each SQL DML operation. This provides a list of SQL management (DML) operations include queries against the table, and insert, update, and delete operations. Each data management (DML) operation (both Dynamic SQL and Embedded SQL) creates an SQL Statement when the operation is executed.
Dynamic SQL SELECT commands create an SQL Statement when the query is prepared. In addition, an entry is created in the Management Portal Cached Queries listing.
Embedded SQL cursor-based SELECT commands create an SQL Statement when the OPEN command invokes a DECLARED query. No separate entry is created in the Management Portal Cached Queries listing.
If a query references more than one table, a single SQL Statement is created in the namespace’s SQL Statements listing that lists all of the referenced tables in the Table/View/Procedure Name(s) column, and for each individual referenced table the Table’s SQL Statements listing contains an entry for that query.
An SQL Statement is created when the query is prepared for the first time. If more than one client issues the same query only the first prepare is recorded. For example, if JDBC issues a query then ODBC issues an identical query the SQL Statement index would only have information about the first JDBC client and not the ODBC client.
Most SQL Statements have an associated Query Plan. When created, this Query Plan is unfrozen; you can subsequently designate this Query Plan as a frozen plan. SQL Statements with a Query Plan include DML commands that involve a SELECT operation. SQL Statements without a Query Plan are listed in the “Plan State” section below.
SQL Statements only lists the most recent version of an SQL operation. Unless you freeze the SQL Statement, InterSystems IRIS® data platform replaces it with the next version. Thus rewriting and invoking the SQL code in a routine causes the old SQL code to disappear from SQL Statements.
Other SQL Statement Operations
The following SQL commands perform more complex SQL Statement operations:. Note that this listing of SQL Statements can contain stale (no longer valid) listings., but must follow statement text punctuation whitespace (name , age, not name,age). If a query references more than one table, the Filter includes the SQL Statement if it selects for any referenced table in the Table/View/Procedure Name(s) column. The Filter option is user customized.
The Max rows option defaults to 1,000. The maximum value is 10,000. the minimum value is 10. To list more than 10,000 SQL Statements, use INFORMATION_SCHEMA.STATEMENTS. The Page size and Max rows options are user customized. InterSystems IRIS). Executing the OPEN command for a declared CURSOR generates an SQL Statement with an associated Query Plan. Embedded SQL statements that use that cursor (FETCH cursor, UPDATE...WHERE CURRENT OF cursor, DELETE...WHERE CURRENT OF cursor, and SQL statement generation normalizes lettercase and whitespace. Other differences are as follows:
If you issue a query from the Management Portal interface or the SQL Shell interface, the resulting SQL Statement differs from the query by preceding the SELECT statement with DECLARE QRS CURSOR FOR (where “QRS” default schema name..
When SQL statements are prepared via xDBC, SQL statement generation appends SQL Comment Options (#OPTIONS) to the statement text if the options are needed to generate the statement index hash. This is shown in the following example:
DECLARE C CURSOR FOR SELECT * INTO :%col(1) , :%col(2) , :%col(3) , :%col(4) , :%col(5) FROM SAMPLE . COMPANY /*#OPTIONS {"xDBCIsoLevel":0} */
Stale SQL Statements
When a routine or class associated with an SQL Statement is deleted, the SQL Statement listing is not automatically deleted. This type of SQL Statement listing is referred to as Stale. Because it is often useful to have access to this historic information and the performance statistics associated with the SQL Statement, these stale entries are preserved in the Management Portal SQL Statement listing.
You can remove these stale entries by using the Clean Stale button. Clean Stale removes all non-frozen SQL Statements for which the associated routine or class (table) is no longer present or no longer contains the SQL Statement query. Clean Stale does not remove frozen SQL Statements.
You can perform the same clean stale operation using the $SYSTEM.SQL.Statement.Clean() method.
If you delete a table (persistent class) associated with an SQL Statement, the Table/View/Procedure Name(s) column is modified, as in the following example: SAMPLE.MYTESTTABLE - Deleted??; the name of the deleted table is converted to all uppercase letters and is flagged as “Deleted??”. Or, if the SQL Statement referenced more than one table: SAMPLE.MYTESTTABLE - Deleted?? Sample.Person.
For a Dynamic SQL query, when you delete the table the Location(s) column is blank because all cached queries associated with the table have been automatically purged. Clean Stale removes the SQL Statement.
For an Embedded SQL query, the Location(s) column contains the name of the routine used to execute the query. When you change the routine so that it no longer executes the original query, the Location(s) column is blank. Clean Stale removes the SQL Statement. When you delete a table used by the query, the table is flagged as “Deleted??”; Clean Stale does not remove the SQL Statement.
A system task is automatically run once per hour in all namespaces to clean up indices for any SQL Statements that might be stale or have stale routine references. This operation is performed to maintain system performance. This internal clean-up is not reflected in the Management Portal SQL Statements listings.. Note that these operations do not change the SQL Statements listings; you must use Clean Stale to update the SQL Statements listings.
Data Management (DML) SQL Statements
The Data Management Language (DML) commands that create an SQL Statement are: INSERT, UPDATE, INSERT OR UPDATE, DELETE, TRUNCATE TABLE, SELECT, and OPEN cursor for a declared cursor-based SELECT. You can use Dynamic SQL or Embedded SQL to invoke a DML command. A DML command can be invoked for a table or a view, and InterSystems IRIS creates a corresponding SQL Statement.
The system creates an SQL Statement when Dynamic SQL is prepared or when an Embedded SQL cursor is opened, not when the DML command is executed. The SQL Statement timestamp records when this SQL code invocation occurred, not when (or if) the query was executed. Thus an SQL Statement may represent a change to table data flags the corresponding SQL Statement for Clean Stale deletion. Purging a frozen cached query removes the Location value for the corresponding SQL Statement. Unfreezing the SQL Statement flags it for Clean Stale deletion.
Executing.
Opening a cursor-based Embedded SQL Data Management Language (DML) routine creates an SQL Statement with a Query Plan. Associated Embedded SQL statements .
SELECT Commands
Invoking
There are two ways to display the SQL Statement Details:
From the SQL Statements tab, select an SQL Statement by clicking the Table/View/Procedure Name(s) link in the left-hand column. This displays the SQL Statement Details in a separate tab. This interface allows you to open multiple tabs for comparison. It also provides a Query Test button that displays the SQL Runtime Statistics page.
From the table’s Catalog Details tab (or the SQL Statements tab), select an SQL Statement by clicking the Statement Text link in the right-hand column. This displays the SQL Statement Details in a pop-up window.
You can use either SQL Statement Details display to view the Query Plan and to freeze or unfreeze the query plan.
SQL Statement Details provides buttons to Freeze or Unfreeze the query plan. It also provides a Clear SQL Statistics button to clear the Performance Statistics, an Export button to export one or more SQL Statements to a file, as well as a buttons to Refresh and to Close the page.
The SQL Statement Details display contains the following sections. Each of these sections can be expanded or collapsed by selecting the arrow icon next to the section title:). Occasionally, what appear to be identical SQL statements may have different statement hash entries. Any difference in settings/options that require different code generation of the SQL statement result in a different statement hash. This may occur with different client versions or different platforms that support different internal optimizations. InterSystems IRIS version under which the plan was created. If the Plan state is Frozen/Upgrade, this is an earlier version of InterSystems IRIS. When you unfreeze a query plan, the Plan state is changed to Unfrozen and the Version is changed to the current InterSystems IRIS an InterSystems IRIS.
Frozen plan different: if you freeze the plan, this additional field is displayed, displaying whether the frozen plan is different from the unfrozen plan. When you freeze the plan, the Statement Text and Query Plan displays the frozen plan and the unfrozen plan side-by-side for easier comparison.
This section also includes five.
InterSystems IRIS does not separately record performance statistics for %PARALLEL subqueries. %PARALLEL subquery statistics are summed with the statistics for the outer query. Queries generated by the implementation to run in parallel do not have their performance statistics tracked individually.
InterSystems IRISML commands this can be set using #SQLCompile Select; the default is Logical. If #SQLCompile Select=Runtime, a call to the SelectMode option of the $SYSTEM.SQL.Util.SetOption() method can change the query result set display, but does not change the Select Mode value, which remains Runtime.
Default schema(s): the default schema name that were set when the statement was compiled. This is commonly the default schema in effect when the command was issued, though SQL may have resolved the schema for unqualified names using a schema search path (if provided) rather than the default schema name. However, if the statement is a DML command in Embedded SQL using one or more #Import macro directives, the schemas specified by #Import directives are listed here.
Schema path: the schema path defined when the statement was compiled. (persistent class) was last compiled.
Classname: the classname associated with the table.
This section includes a Compile Class. InterSystems IRIS SQL Statement Details page Export button. From the Management Portal System Explorer SQL interface, select the SQL Statements tab and click on a statement to open up the SQL Statement Details page. Select the Export button. This opens a dialog box, allowing you to select to export the file not selected by default.
Browser: Exports the file statementexport.xml to a new page in the user’s default browser. You can specify another name for the browser export file, or specify a different software display option.
Use the $SYSTEM.SQL.Statement.ExportFrozenPlans() method.
Export all SQL Statements in the namespace:
Use the Export All Statements Action from the Management Portal. From the Management Portal System Explorer SQL interface, select the Actions drop-down list. From that list select Export All Statements. This opens a dialog box, allowing you to export all SQL Statements in the namespace selected by default. This is the recommended setting when exporting all SQL Statements. When Run export in the background is checked, you are provided with a link to view the background list page where you can see the background job status.
Browser: Exports the file statementexport.xml to a new page in the user’s default browser. You can specify another name for the browser export file, or specify a different software display option.
Use the $SYSTEM.SQL.Statement.ExportAllFrozenPlans() method.
Importing SQL Statements
Import an SQL Statement or multiple SQL Statements from a previously-exported file:
Use the Import Statements Action from the Management Portal. From the Management Portal System Explorer SQL interface, select the Actions drop-down list. From that list select Import Statements. This opens a dialog box, allowing you to specify the full path name of the import XML file.
The Run import in the background check box is selected by default. This is the recommended setting when importing a file of SQL Statements. When Run import in the background is checked, you are provided with a link to view the background list page where you can see the background job status.
Use the $SYSTEM.SQL.Statement.ImportFrozenPlans() method.
Viewing and Purging Background Tasks
From the Management Portal System Operation option, select Background Tasks to view the log of export and import background tasks. You can use the Purge Log button to clear this log. | https://docs.intersystems.com/irislatest/csp/docbook/Doc.View.cls?KEY=GSQLOPT_sqlstmts | CC-MAIN-2020-45 | refinedweb | 2,121 | 55.34 |
Okay then - your the boss :), we'll do it that way (ofcause the code
could be changed, but it is fine with me that we e.g. wait till X is
skipped in this project and gtk1 is abandoned by mozilla or just let it
be as it is.
Here is the raw code for the button handling for gtk 2 and the icons in
xpm are attached. I diff later - if needed by you - so you can see the
code now.
---Top of plugin-ui.cpp---
#include "../pixmaps/menu_down_small.xpm"
#include "../pixmaps/menu_up_small.xpm"
---In method InitPixbufs---:
instance->pb_sm_menu_up =
gdk_pixbuf_new_from_xpm_data((const char **) menu_up_small);
instance->pb_sm_menu_down =
gdk_pixbuf_new_from_xpm_data((const char **) menu_down_small);
---New methods placed after the other callbacks such as
keyboard_callback and mouse_callback - these new methods is by the way
the ones I thought of placing in a dedicated class to handle all the
buttons along with other gui related code ---:
#ifdef GTK2_ENABLED
/* control focus of menu */
static gboolean menu_has_focus = FALSE;
static gboolean menu_button_pressed = FALSE;
static gboolean menu_button_down (nsPluginInstance * instance, gboolean
down)
{
if (instance->panel_height > 16)
instance->panel_height = 16;
gtk_container_remove(GTK_CONTAINER(instance->menu_event_box),
instance->image_menu);
//#ifdef GTK2_ENABLED
if(down == true)
instance->image_menu =
gtk_image_new_from_pixbuf(instance->pb_sm_menu_down);
else
instance->image_menu =
gtk_image_new_from_pixbuf(instance->pb_sm_menu_up);
//#endif
//#ifdef GTK1_ENABLED
//instance->image_menu =
// gtk_pixmap_new(instance->pb_sm_menu_down, NULL);
//#endif
gtk_container_add(GTK_CONTAINER(instance->menu_event_box),
instance->image_menu);
if (instance->showbuttons) {
gtk_widget_show(instance->image_menu);
gtk_widget_show(instance->menu_event_box);
}
gtk_widget_show(instance->fixed_container);
gdk_flush();
return TRUE;
}
gboolean menu_released_callback( GtkWidget * widget, GdkEvent * event,
nsPluginInstance * instance)
{
if (instance == NULL)
return FALSE;
if (event->type == GDK_BUTTON_RELEASE) {
menu_button_pressed = FALSE;
if(menu_has_focus == TRUE) {
GdkEventButton *bevent = (GdkEventButton *) event;
gtk_menu_popup (GTK_MENU (instance->popup_menu), NULL, NULL,
NULL, NULL,
bevent->button, bevent->time);
/* Tell calling code that we have handled this event; the
buck
* stops here. */
}
return TRUE;
}
/* Tell calling code that we have not handled this event; pass it
on. */
return FALSE;
}
gboolean menu_pressed_callback( GtkWidget * widget, GdkEvent * event,
nsPluginInstance * instance)
{
if (instance == NULL)
return FALSE;
if (event->type == GDK_BUTTON_PRESS && menu_has_focus == TRUE) {
if (instance->controlsvisible == 1) {
menu_button_pressed = TRUE;
menu_button_down(instance, TRUE);
}
return TRUE;
}
return FALSE;
}
gboolean menu_enter_callback( GtkWidget * widget, GdkEvent * event,
nsPluginInstance * instance)
{
if (instance == NULL)
return FALSE;
if (event->type == GDK_ENTER_NOTIFY) {
if (instance->controlsvisible == 1) {
menu_has_focus = TRUE;
/* if we regain focus while button is pressed - redraw to get
attetion */
if(menu_button_pressed == TRUE)
menu_button_down(instance, TRUE);
}
return TRUE;
}
return FALSE;
}
gboolean menu_leave_callback( GtkWidget * widget, GdkEvent * event,
nsPluginInstance * instance) {
if (instance == NULL)
return FALSE;
if (event->type == GDK_LEAVE_NOTIFY) {
menu_has_focus = FALSE;
menu_button_down(instance, FALSE);
return TRUE;
}
return FALSE;
}
#endif
---In gtkgui_draw in the first #ifdef GTK2_ENABLED section insert this
just before fullscreen (instance->image_fs) for instance ---:
instance->image_menu =
gtk_image_new_from_pixbuf(instance->pb_sm_menu_up);
---In gtkgui_draw --- insert this chunk of code just before fullscreen
as I think it would be placed fine there---:
#ifdef GTK2_ENABLED
instance->menu_event_box = gtk_event_box_new();
gtk_widget_set_events(instance->menu_event_box,
GDK_BUTTON_PRESS_MASK
| GDK_BUTTON_RELEASE_MASK
| GDK_ENTER_NOTIFY_MASK
| GDK_LEAVE_NOTIFY_MASK);
g_signal_connect (G_OBJECT(instance->menu_event_box),
"button_release_event",
G_CALLBACK(menu_released_callback), instance);
g_signal_connect (G_OBJECT(instance->menu_event_box),
"button_press_event",
G_CALLBACK(menu_pressed_callback), instance);
g_signal_connect (G_OBJECT(instance->menu_event_box),
"enter_notify_event",
G_CALLBACK(menu_enter_callback), instance);
g_signal_connect (G_OBJECT(instance->menu_event_box),
"leave_notify_event",
G_CALLBACK(menu_leave_callback), instance);
gtk_container_add(GTK_CONTAINER(instance->menu_event_box),
instance->image_menu);
if (win_width > 147) { /*IS THIS MAGIC NUMBER CORRECT
NOW???????????????????????????? GUESS IT IS buttonwidth times buttons =
21 * 6 + 21 * 1 (for the menubutton) so the size should be changed to
147 instead of 126 */
gtk_fixed_put(GTK_FIXED(instance->fixed_container),
instance->menu_event_box,
win_width - width*2, win_height - height);
if (instance->showbuttons) {
gtk_widget_show(instance->image_menu);
gtk_widget_show(instance->menu_event_box);
}
}
#endif
--- Then something is missing in gtkgui_updatebuttons (and some of the
other methods in the plugin.cpp) however not needed now just to test ---
--- In plugin.h in the #ifdef GTK_ENABLED section of class
nsPluginInstance:public nsPluginInstanceBase insert where it should
resign --- :
GtkWidget *menu_event_box;
---and---:
GtkWidget *image_menu;
--- and in the #ifdef GTK2_ENABLED part of the class ---:
GdkPixbuf *pb_sm_menu_up;
GdkPixbuf *pb_sm_menu_down;
--- In plugin.cpp in the class implementation of nsPluginInstance,
nsPluginInstance::nsPluginInstance(NPP
aInstance):nsPluginInstanceBase(),
mInstance(aInstance),
mInitialized(FALSE), mScriptablePeer(NULL),
mControlsScriptablePeer(NULL), insert in #ifdef GTK_ENABLED section ---:
menu_event_box = NULL;
--- In void nsPluginInstance::shutdown() insert in the #ifdef
GTK_ENABLED section among the rest of the eventboxes the same line as
above ---:
menu_event_box = NULL;
--- in plugin-setup.h I'm not sure whether it is necessary to have the
callbacks I've made as prototypes - well you decide :) ---:
And that should be it to test how it works. So please do :)
Well, my most wanted feature (beside getting the mplayer team to fix the
bug about the MBR mms streams) would be a volume slider, and I found
some examples. So beside my first proposal:
, something like these would be nice. the one from shelltoys are
groovy :) but less can do it as well. What is important is that the
control is small and smaller than the default gtk one.
So I'll look into it and make it go for the simplistic version of a
volume slider button like ------|-- - we can always make it look
different.
I just saw you mail about the tooltips went in - I look at it and see
how it looks as the cvs version is coming in from sourceforge.
Kind regards
Anders
man, 24 10 2005 kl. 09:37 -0600, skrev Kevin DeKorte:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Show me the code....
>
> Also you might want to prepare a diff against current CVS as I have been
> busy with the GUI. I had to mess with a few things to get the Apple HD
> stuff to work better.
>
> Personally I don't think the button code is really that bad. I'm sure it
> could use some improvements, but it could be a lot worse.
>
> I'm am not planning on switching to GTK_BUTTONs as the current
> GTK_EVENT_BOXes give some flexibility that you cannot really do with
> buttons.
>
> I believe for the tooltips the only events you would need would be the
> enter and leave events
>
> But this may be even easier (I've been saving this info for awhile if I
> were to implement tooltips)
>
>
>
> GtkTooltips *tooltips;
> GtkWidget *button;
> tooltips = gtk_tooltips_new ();
> button = gtk_button_new_with_label ("button 1");
> gtk_tooltips_set_tip (tooltips, button, "This is button 1", NULL);
>
> So you should just have to hook up the tooltip to the button and be done
> with it..
>
> Here are the docs on the tooltips
>
>
>
> I'm sure I could put this in the code in about 5 mins... so if you want
> me to do that, that is ok with me.
>
> I'm still not sure about a "menu" button, right click is pretty common
> and is "docuumented" on the screen shots page. I'd rather have a volume
> button and since we are cramped on space, volume would be accepted quicker.
>
> Kevin
>
> Anders Lind wrote:
> > Hi Kevin and all of you
> >
> > You probably wonder why you havent heard from me yet :)
> >
> > Well, I made the button, and the code for putting the button on the
> > screen, when it e.g. is resized to full screen, has to be set some
> > places in the code. The last thing I havent made yet, but tried it out
> > some time ago.
> >
> > However after I started to make some code and I could soon see, that
> > what I wanted was normal button behaviour for the menu button. So I used
> > some time to figure out the right events that should trigger button up
> > and down etc. (gtk isn't that good documented after my point of view ;))
> > So I use GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
> > GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK and some methods and 2
> > variables for handling button up and down and whether the mouse is in
> > focus over the button.
> >
> > Now I'm quite convinced that this feature would be nice to have on the
> > other buttons so I'm starting to make some generic class for the button
> > methods that handle button up and down and what is related to setting up
> > the button in the panel - cause I think the code is a mess all the
> > places where the image has to be loaded, disabled and the like.
> >
> > So, if you are not going to change to gtk alone in the near future - and
> > therefore consider only to use ordinary gtk button - but still use gtk
> > event boxes I'll continue my work.
> >
> > My intention is, that it should be really more easy to handle the button
> > events than it is today where you have to fiddle with the code so many
> > places so it is possible to write the necessary code only once and make
> > it easier to NOT lose oneself in details when just placing a single new
> > button or getting the unstable states that we discussed to many times -
> > well probably it will not solve everything but it will tidy it up i
> > hope. I hope you like if I comment the code!
> >
> > I'm ready to do that job allthough it'll take some time to finish. But
> > in the end it is my wish that the irritating GUI problems will vanish
> > because the responsibility for common features is placed in a common
> > class(es).
> >
> > Sorry for the long post.
> >
> > Hope it is something you will endorse.
> >
> >
> > Regards
> >
> > Anders
> >
> > PS As to my other wishes in my last post - well when they irritate me
> > too much I'll make a patch :)
> >
> > søn, 09 10 2005 kl. 15:35 -0600, skrev Kevin DeKorte:
> >
> >>On Saturday 08 October 2005 10:01 am, Anders Lind wrote:
> >>
> >>>1. I've made a patch for mplayerplug-in so when a menu button is pressed
> >>>the menu is shown at the position of where the mouse is. In that way the
> >>>user is knowing that there is a menu!
> >>>
> >>>- For now I've only made it for GTK2, which makes it useless for GTK1
> >>>users. So I need to do some testing on GTK1 - also to see whether I
> >>>havent made a bug between the the 2 versions of GTK.
> >>>Do I need to install the old netscape 4.79 for getting an environment
> >>>with GTK1 and does it use GTK1?
> >>
> >>Send it in, GTK2 is definitely where all the good stuff is going. But GTK1
> >>will be around until mozilla quits shipping that way. I downloaded it
> >>recently and that is what I use to test GTK1 code.
> >>
> >>
> >>>- Will GTK1 be supported forever or will it be removed in the near
> >>>future?
> >>
> >>I'd love to remove GTK1 and X, but so far I can't. X mode gives a warning when
> >>you configure it that way.
> >>
> >>
> >>>- What is your prefered options for diff when I post the patch for the 2
> >>>or 3 files I have altered?
> >>>
> >>
> >>Diff against CVS with the -u option is ok. But diffing against the last
> >>release is ok too.
> >>
> >>
> >>>2. I thought about adding a tool tip for the buttons like described on
> >>>
> >>>
> >>>The tool tip for the buttons could tell the user of:
> >>>Name of function eg.: Play
> >>>Shortcut key eg.: P
> >>>
> >>>Eg. like: "Play media - <P>"
> >>>or "Play - P"
> >>>
> >>>For people knowing the functions (eg fast forward) or bothered of the
> >>>tooltips one could make an option in the Configuration window to
> >>>enable/disable this feature!
> >>>
> >>
> >>Well I've tried to make the controls look like the controls on a tape
> >>recorder, so I'm not sure why someone would not know them. But I'll take a
> >>patch.
> >>
> >>
> >>>It is also posssible to set a delay before the tooltip is shown with
> >>>gtk_tooltips_set_delay
> >>>
> >>>Finally see my example in the bottom of my mail.
> >>>
> >>>3. I made some concept art for a volume slider that is 2 times a buttons
> >>>width. The dimensions and the look may ofcause change, but it is more to
> >>>get an idea to how it works and the way it signals the current audio
> >>>level.
> >>>
> >>>- What do you think of the idea?
> >>>
> >>>- Does anyone know of a library where custom made gtk widgets are
> >>>located on the net - I would really like to see some examples?
> >>>
> >>>Else I guess I have to use the gtkDialPad example for studying (from
> >>>gtk.org) if no custom made widget is ready or easy to alter.
> >>>
> >>>
> >>
> >>Volume has been asked about before, mainly since I always use the master
> >>volume it has not been a high priority for me personally. So that is why I
> >>have not coded it up.
> >>
> >>I was thinking about a tooltip-ish type of dialog that came up that has a left
> >>right slider it in, that you used to control the volume. The semantics of how
> >>it would work I have not figured out, and so I have not done it.
> >>
> >>
> >>
> >>>If possible please take a look at winamp 5.1 for windows and see the
> >>>fullscreen view for video media.
> >>>I like how the fullscreen icon is placed in the top of the screen and
> >>>how the controls are made as well as the progress/seeking slider. Notice
> >>>also that the controls are shown when you move the mouse.
> >>>
> >>
> >>Probably not going to happen, since the full screen and small screen code for
> >>positioning the buttons share the same code path. I find it usable, and so
> >>there is not a real good reason to change.
> >>
> >>
> >>>- Would it be something we would like to see in mplayerplug-in?
> >>> (It would take some effort to make it look like that! I'm not sure
> >>>whether I've got the time or that skilled to do that. But nice though.)
> >>>
> >>>
> >>>
> >>>4. Bug
> >>>When mplayerplug-in starts to play a media then if you disable "Show
> >>>Controls" from the menu the buttons flash once, but are afterwards still
> >>>shown - however without working.
> >>>(Enabling the control buttons again make them work properly.)
> >>>
> >>
> >>Yup, your right it does that... I might take a look at it.
> >>
> >>
> >>>5. I'm also (still) planning to make a patch/workarround for the bad
> >>>sound and videoquality issue because of the mplayer bug when mplayer
> >>>handles MS's mms multibitrate streams, however I see that a method
> >>>mmsToHttp already exists in plugin-support.cpp but it is however not
> >>>used by mplayerplug-in when I seek through the files of the project.
> >>>
> >>>An option in the configuration window to enable renaming of mms streams
> >>>to http would be nice, so when mplayer finally gets the URL of the
> >>>stream (after it has been parsed by mplayerplug-in) it has already been
> >>>replaced with http by mplayerplug-in. That would be really nice.
> >>>
> >>
> >>So what happens in the case where the URL says to use an MMS and you change it
> >>to an HTTP and the site returns a 404? What do you do then?
> >>
> >>
> >>>Kind regards
> >>>
> >>>Anders Lind
> >>>
> >>
> >>Interesting comments Anders... I'll accept and maybe merge in patches. I'm
> >>trying to minimize the amount of changes that go in to ensure that the code
> >>is stable. That last push kinda burned me out on the code for awhile.
> >>
> >>Kevin
> >>
> >
> >
> >
> >
> > -------------------------------------------------------
> >@...
> >
> >
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.1 (GNU/Linux)
>
> iD8DBQFDXP/NaR60qN0tF+8RAiwqAJ9Z4AQWNcYporuDas9intWhoTmEgACg1Lxg
> 6GCYeBLlw9WW5h0rK/+0OZo=
> =r8XT
> -----END PGP SIGNATURE-----
>
>
> -------------------------------------------------------
> | https://sourceforge.net/p/mplayerplug-in/mailman/message/8637804/ | CC-MAIN-2016-36 | refinedweb | 2,459 | 57.5 |
On 09/27/2014 05:59 PM, Chet Ramey wrote: > On 9/27/14, 4:29 PM, Eric Blake wrote: >> On 09/27/2014 12:53 PM, Chet Ramey wrote: > >> Right now, we know of no way for an attacker to force an arbitrary >> variable name - ONLY arbitrary variable contents. > > Sure, but we didn't know that at the time. We still don't, really. On the bright side: _if_ we find a way for an attacker to generate an arbitrary variable name in a parent process before calling into bash, that is more likely to be raised as a security bug against THAT program, and not bash. The reason bash is getting the limelight for CVE-2014-6271 is because there are so many existing programs that pass untrusted input to environment variable values, where fixing bash solves ALL of those cases at once; but there are a lot fewer (if any) programs stupid enough to create arbitrary environment variable names. The regression with 'at' failing to work is because 'at' is making unportable assumptions that the environment it is passed will always be parsable in shell. But this assumption is wrong whether or not bash uses an alternate namespace for function exports - ANY C program that uses execve can tickle that bug in 'at'. So that particular fix is not bash's problem, but 'at's problem. > >> Exactly, this break is undesirable. Remember, the security hole of >> Shell Shock is NOT what the function is named, but the fact that >> arbitrary variable contents were being parsed. Once you plug that hole >> by sticking function import/export in a separate namespace, then there >> should be no problem in allowing ALL function names that have always >> been previously allowed. > > We have an opportunity to close up a potential problem here, at least > with respect to function names containing `/'. As I said in a later mail, I'm now definitely leaning towards your desire to exclude '/', and may I also add '=', as two characters that will be blacklisted from valid function names both in the shell and during import/export, because they are just too risky. I haven't yet come up with any reason to blacklist any other non-metacharacter, and you already reject any metacharacter that requires quoting. > I'm not really interested in the function-importing-by-default discussion > right now. Maybe sometime later. It's more of a break with backwards > compatibility than I'm willing to go at this point. That's a fair stance. I don't mind waiting and revisiting that discussion later; I agree that the first priority is to plug the namespace issue. >>> (And I'm not interested in rehashing decisions that were made 25 years >>> ago, and I am completely aware that this "violates" Posix. That's why it >>> doesn't do this in posix mode.) >> >> I don't see function export/import as a violation of posix; > > Yeah, but what I was talking about was allowing non-identifiers as valid > function names. Where does POSIX forbid the use of a non-identifier as a valid function name? My understanding is that: a:b () { ... } is unspecified by POSIX (and NOT expressly required to be a syntax error), which has two implications: 1. Strictly-conforming shell scripts will not attempt to use it, and 2: we are allowed to support it as an extension while still remaining POSIX compliant. I'd need to see an example of some script that would be parsed one way with bash's function name extensions and a different well-defined way by a strict reading of POSIX before stating that /bin/sh mode must behave differently at having a smaller subset of valid function names. -- Eric Blake eblake redhat com +1-919-301-3266 Libvirt virtualization library
signature.asc
Description: OpenPGP digital signature | https://lists.gnu.org/archive/html/bug-bash/2014-09/msg00275.html | CC-MAIN-2022-21 | refinedweb | 637 | 59.23 |
Created on 2012-09-25 23:20 by rhettinger, last changed 2012-12-13 17:14 by asvetlov. This issue is now closed.
Since inheritance is more commonplace and more easily understood than __metaclass__, the abc module would benefit from a simple helper class:
class ABC(metaclass=ABCMeta):
pass
From a user's point-of-view, writing an abstract base call becomes simpler and clearer:
from abc import ABC, abstractmethod
class Vector(ABC):
@abstractmethod
def __iter__(self):
pass
def dot(self, other):
'Compute a dot product'
return sum(map(operator.mul, self, other))
Notice that this class seems less mysterious because it inherits from ABC rather than using __metaclass__=ABCMeta.
Also note, it has become a reasonably common practice for metaclass writers to put the __metaclass__ assignment in a class and have it get inherited rather than requiring users do the metaclass assignment themselves.
+1
Agreed.
It looks slightly better, but it would also violate "there is one obvious way to do it".
In practice this is indeed how most users of met a classes do it. E.g.
Django. So, +1.
--Guido van Rossum (sent from Android phone)
On Sep 30, 2012 11:36 AM, "Antoine Pitrou" <report@bugs.python.org> wrote:
>
> Antoine Pitrou added the comment:
>
> It looks slightly better, but it would also violate "there is one obvious
> way to do it".
>
> ----------
> nosy: +gvanrossum, pitrou
>
> _______________________________________
> Python tracker <report@bugs.python.org>
> <>
> _______________________________________
>
This solution hides the risk of metaclass conflicts, as the user did not explicitly set the metaclass. IMO, this risk should be clearly told in the Doc.
Bruno: do you want to propose an idea for the doc part? Or even a full patch for this request?
Éric, here is a full patch. I hope the doc isn't too confuse. I think we lack a word meaning 'has XXX as metaclass', we should imagine a term for that.
+1 The patch looks fine.
Éric do you want to apply it?
LGTM
Feel free to commit the patch Andrew. You may want to document the new ABC class before the ABCMeta, as we expect that subclassing will become the preferred way.
New changeset 9347869d1066 by Andrew Svetlov in branch 'default':
Issue #16049: add abc.ABC helper class.
Done. I prefer to leave existing class order in documentation.
In general I agree with Eric that ABC should be before ABCMeta in the doc but now it has formalized as helper for metaclass with very short documentation.
To put ABC first we need to transplate almost all content of ABCMeta doc int ABC.
If somebody want to do it — please create new issue and feel free to make a patch.
Thanks, Bruno. | http://bugs.python.org/issue16049 | CC-MAIN-2014-42 | refinedweb | 446 | 72.66 |
Fetching Crypto Price with React
Before we dive into the code, let’s talk a bit about the project we’re going to do and few requisites.You’ll need the knowledge on:
- HTML: Only very basic knowledge.
- JavaScript: Intermediate level to write functions (ES6).
- CSS: Optional but preferred. We won’t talk about why it looks so and so. That’s where CSS comes to play. You can start with the provided starter template which includes all required CSS.
- Familiarity with any API, Node or react will be a great advantage as you follow the tutorial.
Setting Up the tools:
NodeJS: Install from here. LTS version is recommended. We won’t be running any JavaScript for the node, but we need Node to run the react app.
Make sure to verify npm is also installed with it. You can also use yarn, an npm alternative, if you are familiar with it. This tutorial will use npm!
npm -v
node -v
If both commands return a version number, you’re good. The numbers might be different from the ones appearing in the image above.
What are we going to make?It’s easy to use than to explain with words.
Setting up the react App
One complicated thing with React is beginning. It’s incredibly difficult to set it up without knowledge of multiple tools which are usually used by intermediate-expert level JavaScript developers. Facebook came up with a tool that can make this task easy. This package is called create-react-app.
This tool configures environment so that we can get directly to React, without dealing with complex tools. On the better side, it also allows separating the react app from itself so that we can have a complete control over it. That’s a win-win with both set up and control.
**To install the create-react-app globally:**$ npm install -g create-react-app
**To create an app using this package:**$ create-react-app crypto-reactdev
crypto-reactdev is our app name.
I got an error saying ‘create-react-app’ is not recognized. If you get the same error, there are two solutions. Use one of these:
- Add the node_modules directory to path. The default path is C:\Users\USERNAME\AppData\Roaming\npm\node_modules
Or use a slightly different command:npx create-react-app crypto-reactdev
I used the second one.
It’ll create a new directory, crypto-reactdev with required files and folders.
What each file and folders are for?
package.json contains the list of modules that application uses. Each module performs a function or a set of functions.node_modules stores all packages that are listed in package.json.src contains all React source code files.public contains static files such as stylesheets and images.
Now, you've got a working React application. Setting up was easy, wasn’t it?
Open the directory in the terminal, many editors come with the built-in terminal. You may utilize that as well. Following screenshots will be from VS Code, integrated with Git Bash terminal. A single command will start the server:$ npm start
The default port is 3000, it will ask to try 3001 if it’s busy! It’ll also open the URL on web browser.The output on the browser should look like this
It’ll automatically reload when you modify files, thanks to create-react-app.
Into the React
The public directory is accessible and rendered to the browser.
The base file is index.html. It has the following line:
<div id="root"></div>
This is the div where we inject the React. We won’t touch this file at all.In the src directory, have a look at index.js file.
Look at this line:ReactDOM.render(<App />, document.getElementById('root'));
- It gets root div from the index.html file.
- Injects App component in that div.
You may also use querySelector instead, it’s just used to select this block!
Let’s remove the serviceWorkers as we won’t be using them in this project. Remove the import registerServiceWorker and registerServiceWorker();from index.js. Also remove registerServiceWorker.js file from srcdirectory.
What are all these imports on the top?
In react, every rendered piece is a component.
React is required to process JSX. The html-like code you see is not html, it’s JSX.When creating a div, it (babel) transpiles the code to React.createElement().This needs React. You can refer to babel documentation for details regarding babel.
import React, { Component } from 'react' imports both React and a method from React called Component. React.Component refers to Component within the React.When we refer Component it refers to Component imported as {Component}. Using Component is my personal preference.Removing {Component} and using React.Component instead does not reduce the import cost. It works exactly same both ways and doesn’t show any difference in performance
- ReactDOM is used to handle the dom that contains all elements on page. This used to be a part of React once and has been split to a different one. This package provides DOM-specific methods that can be used at the top level of your app.
Let’s get to the main file, src/App.js`
The content you see in the browser comes from this file.Remove everything under return so that it looks something like below.
Did you notice the change on the app running in the browser? Look at the changes.
Please ignore my editor settings injected into code in the screenshot.Size of the import on right of the import statement and ‘edited by You…’ are injected by extensions and are not part of the code.Refer to the actual code on this GitHub repository. Keep an eye on commits, I keep committing frequently on small every change. If you don’t have local setup, you can use it on.
The return statement has a few conditions:
- It can return only one element: that could be one div or one p element.
- If you’ve to return multiple elements, create a parent div and return the parent div instead.
- Return must be included in parenthesis () when multi-line. Parenthesis are optional when returned in a single line.
Since I need multi-line return, I’ll use parenthesis.
The class in html translates to className in JSX because class conflicts with JavaScript class. Classes App and App-header are pre-defined in the App.css file that we imported in the App.js.
There isn’t much styling in this app. Since it is about react, we won’t discuss about CSS. If your app doesn’t look like ours as you follow along you can always replace styles from App.css from the repository. We strongly recommend to start with provided starter files, get them here.
Back to React!
React consists of components that fit together. These components are kept as small as practical.
Let’s break down the react application into components:
- Individual crypto currencies.
- Parent component to handle data for all individual components.
Keeping the project organized is a better idea so create a directory named components inside src.
Create two files inside components:
Crypto.js and Crypto.css.
Crypto.css
.crypto { list-style-type: none; padding: 0; display: inline-flex; }
Before jumping into Crypto.js, we must talk about functional components React.There are two ways to define the components in React. We have done one in the App.js using class App extends Components, that kind of components are called pure or stateful components. They look like:
Class ClassName extends Component { Render () { Return ( <ComponentName> Any text or resource! </ComponentName> ) }
There is a new modern way of declaring components, these are called stateless components. The stateless functional components give a better performance and are less clunky to write. It’s not the lines of code that is written, which is almost same.
It’s declared like an ES6 function. Stateless functional components are useful for presentational components. That means they can’t use the states, state refers to the object owned by the component where it is declared. It is limited to the current component. It has data that component can keep track of. The state can be initialized or data can be changed on the fly within the component.
Any component that does not use the state should be declared in the stateless fashion. Arrow functions are more compact and offer a concise syntax for writing function expressions.
Const MyComponent = (props) => { Return ( <Component> {prop.myProperty} </Component> ) }
Save the stateless vs stateful topic for another discussion, let’s continue with the app crypto-reactdev!
Crypto.js
We’re importing React, and Component on the first line. Then we’re importing stylesheet file.
We’re making a class Crypto and exporting it as the default class so that it can be imported at another location to be used with other components.
Create a constructor in the Crypto component so that our data is set when we create an element. We’re using dummy data for setting up the state so idand price are fixed. These values will be obtained from API later. super()needs to be called as Crypto extends a parent class and super calls constructor from a parent class, it is mandatory by JavaScript rules.
Every component must have a function named render. Define render in the Crypto class, outside the constructor.
render () { return ( ) }
Return will contain whatever the class will return.
Let’s fill up with some code…
render () { let crypto = this.state.data.map ( (currency) => { <li key={currency.id}> <h3>{currency.id} </h3> <h4>$ {currency.price}</h4> </li> }) return ( <div className="crypto-container"> <ul className="crypto">{crypto}</ul> </div> ) }
In the render, we map the values. This is the same JavaScript map function, introduced in ES6. The key is defined to keep track of the li we need to update as the price changes. It contains other data such as id and price on the screen.
Curly braces in the React {} refer to the JavaScript code. {crypto} refers to crypto variable.The return statement returns a single crypto component inside a container. className is provided for styling.Now our Crypto component is ready, but the output screen does not change because we have not rendered anything yet.
The rendered Component is App. We import Crypto in App using:import Crypto from './components/Crypto'
Include the <Crypto/> component in App as shown below.
The browser should output something like this.
Adding More Components
Our App is all set for more child components to handle each crypto-currency. This will enable us to use same component with specific features and styles for each one.Inside components folder, use two files Currency.js and Currency.css. I’ve added some CSS to Currency.css, find it here.
Since the Currency.js won’t be using states, we should declare this component as functional (or stateless).
const Currency = props => {return ()}export default Currency
This is how it is declared. It doesn’t need render function.
Before returning, we need the variables set, so get variables from props using object destructuring. All variables required are inside data in the result. I’ll get this from CoinMarketCap API.
Also keep note that declaring this as ES5 function instead of using arrow functions is possible but you might frequently run into binding issues with react. I recommend arrow functions, they are less confusing!
const { id, name, symbol, price_usd, percent_change_1h, percent_change_24h, percent_change_7d, } = props.data
We want to return a single currency so return
<li className= {'currency ' + id}><p className="currency-name">{name} ({symbol})</p><h1>${(+price_usd). toFixed (2)} </h1><p>{percent_change_1h} % 1hr</p><p>{percent_change_24h} % 24hrs</p><p>{percent_change_7d} % 7days</p></li>
This return data represents a single currency.Since we need more data fields now, I added the dummy data fields to Crypto.js
This data can be used in Currency component. We must import Currencycomponent in the Crypto.js. We need to render this component instead of li with h3 and h4.
const crypto = this.state.data.map (currency => (<Currency data={currency} key={currency.id} />))
This iterates through all data in the state.
A single object inside data is received as currency in the map function. This is passed as data in the Currency component. We also pass key to keep track of the component.
What do we get?
Excellent output, except for the data.
Getting the data for react components!
There are multiple ways to get data and using a package to help us is probably the least complicated method of achieving this.
I do not expect you to be familiar with react life-cycle methods, you could solely use that too!
I’ll be using the Axios, it is easy to use asynchronous REST API.Axios doesn’t come with create-react-app. We add to our app using:
$ npm install axios –save
Import axios in Crypto.js, that’s where we’ll be fetching data.import axios from 'axios'
Now, we fetch the currency data through API. We create a function in Cryptoclass to achieve this.
fetchCurrencyData = () => { axios .get('') .then(response => { const wanted = ['bitcoin', 'ethereum'] const result = response.data.filter(currency => wanted.includes(currency.id), ) this.setState({data: result}) }). catch(err => console.log(err)) }
The fetchCurrencyData() is the required function. We filter the result data set for Bitcoin and Ethereum only. We also set the state data to the result after obtaining result.
Since the data is modified, react will reflect the changes in the Currencycomponent.
If you check the browser now, you won’t see any changes. This is because we defined function but never called it.We want to call this when the component loads and every minute thereafter.
React has a thing called lifecycle methods, there are some 8 methods. These are like built in functions. We’ll talk about only one here.
We’ll use componentDidMount method. This will execute the code when component is in view.Inside the Crypto component, add this method as:
componentDidMount () {this. fetchCurrencyData ()this.interval = setInterval (() => this. fetchCurrencyData (), 60 *1000)}
This fetches currency data using our previously declared function. It also uses setInterval to run the same every 60 seconds to get new data.
Now, we should get a working Bitcoin and Ethereum and bitcoin ticker.
Cleaning up the react app!
There’s always something that can be corrected, here’s what we can clean up in this project.Check the console in the browser and remove the unused components.
Remove logo import from App.js, and {Component} from Currency.js
Expanding the currencies
We have Bitcoin and Ethereum tickers, we can expand it to more currencies.
We’re using the REST API URL from this location to get the data. You can see the available ids. We have bitcoin, ethereum, ripple, bitcoin-cash, eos, litecoin, stellar, cardano, iota, tron in order.
Add some of these to the wanted list in Crypto.js.
Here’s my output
The data should automatically refresh.
If it does not update, wait for a while. CoinMarketCap updates the data every 5 minutes and we fetch data every minute. It might take up to 6 minutes to get new data.
Closing Notes:
If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇
Encode, Stream, and Manage Videos With One Simple Platform | https://hackernoon.com/fetching-crypto-price-with-react-3a49f41bf80c?source=rss----3a8144eabfe3---4 | CC-MAIN-2022-33 | refinedweb | 2,556 | 60.82 |
Good evening everyone ,
I am writing this post to ask you guys if you can help me on this very basic program .
I am still a student in programming and a beginner with arrays and i am asked to create a program that creates random elements of arrays between 0 and 9 , and inside every box of these arrays a random number between 0 and 100 and finally to calculate the sum of these numbers , example
6 random elements of an array are generated , inside each one of these elements a certain value is created , then i shall add these value and print the value.
Now as i said i am still a beginner in java so i know this program is messed up but at least i tried i hope you guys can help me , thank you :
Code java:
public class arrays { public static void main(String[] args) { double x = 0 ; double [] numbers = {x*(Math.random()*10)}; double result = sumLessThanAverage(numbers); System.out.println(result); } public static double sumLessThanAverage(double[]a){ double x = 0; double sum = 0; double count=0; x = x * Math.random()*101; for ( int i = 0 ; i<= a.length-1 ; i++){ a[i] = x; sum += x; x = x * Math.random()*101; count ++; } return sum; } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/34141-problem-arrays-printingthethread.html | CC-MAIN-2018-05 | refinedweb | 208 | 55.78 |
Working with Ionic Native - Contact Fixer
This post is more than 2 years old.
I've blogged a few times now about Ionic Native, but if you're new to it, you can think of "Angular2/Ionic2 Friendly Wrappers" for many different Cordova plugins. Today I'm sharing what may be my coolest demo yet. No, wait, seriously, it is, honest! This demo does something I think every phone should have built in, and if I can get off my lazy butt, I'll be submitting this to the App Store this week. So what did I build?
I noticed recently that both both iOS and Android will provide a contact picture even when you haven't selected a unique one for them. I believe, in both cases, it won't use the default picture when you get a call from them, but in the contacts app it will display it. So that's cool. I know it isn't new, but I like the fact that I can see someone's face when I get a phone call or text message from them.
However - I don't always have time to snap pictures of people when I'm adding them to my contacts. This made me curious. Given that we have a Contacts plugin and a Contacts Ionic Native wrapper, could I actually set a picture for contacts that didn't have them?
Turns out that yes, you can! And of course, that means only one thing. I could build an app to "fix" those contacts and give them better pictures. Here's how 3 of the default iOS simulator contacts are displayed:
And here are the fixed versions:
In case it is a bit too small, here is a closeup on the awesomeness:
I'm going to be so rich when I put this in the App Store. Ok, let's take a look at the app itself. First, the UI, which is incredibly simple since the app does one thing and one thing only.
On startup, we display some text explaining what we're about to do:
You then click the button, it presents a 'working' message, and when done, shows you a result:
And that's it. I could maybe actually show all the contacts and their new pictures, but honestly, this felt like it was enough. Let's look at the code. First, the view.
<ion-header> <ion-navbar> <ion-title> Contact Fixer </ion-title> </ion-navbar> </ion-header> <ion-content padding> <p> This application will scan your contacts and find ones without a contact picture. For each one it finds, it will fix that problem by selecting a random cat picture. This is a <strong>one way</strong> operation that cannot be undone - use with caution! </p> <button ion-button color="danger" (click)="fixContacts()" full round>Make It So!</button> </ion-content>
And now the real meat of the app, the code behind this view.
import { Component } from '@angular/core'; import { NavController, AlertController, LoadingController } from 'ionic-angular'; import { Contact, Contacts, ContactField } from 'ionic-native'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, public alertCtrl:AlertController, public loadingCtrl:LoadingController) { } getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } randomCat() { let w = this.getRandomInt(200,500); let h = this.getRandomInt(200,500); return `{w}/${h}`; } //Credit: toDataUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { var reader = new FileReader(); reader.onloadend = function() { callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.send(); } fixContacts() { let loader = this.loadingCtrl.create({ content: "Doing important work...", }); loader.present(); let fixed = 0; let proms = []; Contacts.find(["name"]).then((res) => { res.forEach( (contact:Contact) => { if(!contact.photos) { console.log('FIXING '+contact.name.formatted); //console.log(contact); proms.push(new Promise( (resolve, reject) => { this.toDataUrl(this.randomCat(), function(s) { var f = new ContactField('base64',s,true); contact.photos = []; contact.photos.push(f);(); }); }); } }
Things get kicked off when the button is clicked on the view and
fixContacts() is fired. I turn on a loading component to present something to the user to let them know the app is doing something.
Next, I ask the Contacts API to return every contact. I have to pass a 'search field', even though I'm not actually passing a search value. That's a bit wonky, but that's how the plugin works, it isn't a bug in Ionic Native's implementation.
I then iterate over every contact. The photos property is empty when no pictures exist for the contact. When I find that, I kick off a process to make a new picture using the Placekitten service. I simply generate a random size and that will give me a random cat. I conver that to a base64 string and then store it in the contact.
Because this process is asynchronous, I use an array of promises I can then call
then() on to know when they are all done.
Finally, I report what I did to the user using the Alert component. And that's that. Here's output from my real device. First, Max, who already had a picture.
And here is Alex, who did not have a picture, but who now does, and is much improved:
You can find the complete source code here:
So - who would pay 99 cents for this?
Archived Comments
I would probably pay if I could customize what the actual image is, and you used @ionic/storage to remember which contacts it changed so it is reversible.
Well part of the idea is to not make you select an image for each, because then that's probably not much better than you doing it yourself, know what I mean? I could see offering options from the various different image placement services.
maybe get it from gravatar if the contact has email account, or from a social network (if possible).
BTW, I want 10% if you use my idea
Oh - Gravatar is a damn good idea, but do folks still use that? It seems like it was big 5+ years ago or so, but I never hear people talking about, nor see sites really using it.
I don't know, I probably configured mine 5 years ago, but some sites are still picking my image from there. I don't think people have deleted their account, so if they registered long time ago, you can still pick their old picture even if they don't use it anymore.
Hello
I'm trying run this example and this error show in console:
EXCEPTION: Uncaught (in promise): TypeError: navigator.contacts is undefined
Did you install the plugin?
Yes, the plugin is intalled.
ionic plugin add cordova-plugin-contacts
And you are running it via the emulator?
Runing in Firefox Navigator with ionic serve command.
Don't. :) Run in the iOS/Android emulator or a device.
Ok. Thaks. I'll try it.
Dont work on emulator.
Do you get the exact same error? Did you modify my code?
I don't modify yuor code :-(.
Alert dialog says:
Unfortunately, fixcontacts has stopped.
What do you see when you remote debug?
Yes.
Genymotion.
I'm trying to run in device Android later.
Thanks. | https://www.raymondcamden.com/2016/12/12/working-with-ionic-native-contact-fixer | CC-MAIN-2021-39 | refinedweb | 1,204 | 66.33 |
Dynamic-static typing
In this post I try to abstract away details of type checking, such that the resulting type system can no longer be categorized on dynamically/statically typed axis.
I guess it's a good opportunity to pick on Harper's blog post where he shat on people using dynamically typed languages by proposing that we stick to our languages due to clever marketing rather than a rationale.
In the post Harper finds it important to be able to state and enforce invariants. Dynamically typed languages are usually dynamic enough to not allow checking that any invariants hold.
Either way, the invariants may or may not be there. Even dynamically typed programs tend to collect useful invariants as they are written. It is harmful that you cannot programmatically ensure that those invariants actually are there.
Dynamic typing avoids an equally hideous situation of excessive invariants though. In my opinion excessive invariants are a much worse problem than inability to check invariants because the later usually forces or at least guides you to write more code to keep the invariant. This is not only true to C, but also to languages such as ML with type inference because the inference itself tends to introduce more invariants in order to work through the code.
In the same post Harper admits that...
languages that admit both modes of reasoning enable you and liberate you from the tyranny of a single type.
It would seem that we agree on this one. But it appears as if Harper had completely disregarded the motivation for having dynamic typing in the first place. I think he meant for something else than what you're about to see next.
Introduction
The main task to "admit both modes of reasoning" here is to find the correspondences between dynamic and static object spaces.
Assume we'd have the following script:
a = [1, 2, "hello"]
print(type(a))
We want to print out the type of the list we just
constructed. The desired output of this
would be
List(Integer | String).
I know you already see some problems that seem intractable here.
- Both types and values exist in the same object space. Type theorists tend to treat these as if they were in different universes entirely.
- We cannot know whether the type annotation is conclusive. Append
1.5into the list and the type annotation should change to
List(Integer | Rational | String).
- How do the internals of dynamic types correspond to static types?
When I started writing this post, I did not know the answer to the last question here. I think it's the potentially the most interesting one. The answer comes from higher-order type operators. It is also the reason for writing the whole post in the first place.
The second problem is likely something we have to live with, but it can be made much smaller by making module contents immutable. At first it would seem counterintuitive to have a dynamically typed language with immutable modules, but this actually makes a lot of sense.
The types and values in same object space would seem to be a showstopper at first. On closer inspection it doesn't seem to matter at all. All right, values and types are from different universes, and you may get types of types that are again from an another universe. They can still share the same namespace without a problem.
Immutable modules
Programs no longer follow Unix-process model in design. Modern software consists of many small tasks that operate at the same time. There is an operating system inside and outside a process. Setting modules immutable allows different tasks to use the same modules without interacting inadvertently.
When modules are immutable we would appear to lose the live programming capabilities of dynamically typed languages, but actually the opposite happens. The only reliable way to do live programming is to save the state, shut down and restart with a new program loading the previous state.
Additional type information makes it easier to do live programming. The verified task boundaries make it reliable and safe. When these aspects are combined, live programming becomes a commonplace and accepted software development technique.
People who have done some live programming know that it's incredibly effective when something interactive should be written. The development time may drop hundredfold if you can see the immediate feedback for every change you do.
Constructors
So that they make sense both dynamically and statically typed, how should the data constructors work?
We might have data constructors defined like this:
data Foo(a) =
foo(bool, Foo(a))
bar(int, a)
woot
You could create objects like this:
a = foo(true, woot)
b = foo(false, bar(3, "h"))
c = bar(4, 2)
With types such as these:
a :: Foo(?)
b :: Foo(String)
c :: Foo(Integer)
We get to the type constructor
Foo(a) later, first lets
discuss what the types of the data constructors should be:
foo :: Constructor(Foo(_), (Integer,Bool))
bar :: Constructor(Foo(a), (Integer,a))
woot :: Constant(Foo(?))
Constructors are pattern matchers and callables. Constants
are instances of
Foo(?) while they're also valid pattern
matchers.
class Constructor(a, b)
Pattern(a, b)
Call(b -> a)
class Constant(a)
Pattern(a, unit)
Two builtin methods are implemented for patterns:
matching :: (Pattern(a,_), a) -> bool
deconstruct :: (Pattern(a,b), a) -> b
And they are used to implement the case clauses such as:
show(a):
case a
on foo(a,b)
print("foo", a, b)
on bar(c,d)
print("bar", c, show(d))
on woot
print("woot")
show :: Foo(Stringify) -> Unit !
I have not decided how to represent
coeffects/exceptions/IO,
but those have to be provided on the type annotations.
The data constructors come from the representation selected for a type. Tagged unions have this kind of constructors and record types would have different kind of constructors.
Proper exception handling may require that tagged and openly extensible tree hierarchies can be created.
Operators
The base utilities in the language are provided by abstract operators that any object in the system may implement. Here are some interesting ones with their associated types:
call :: Operator((Call(a -> b):a -> b)
(==) :: Operator((a,b) -> c)
eq [a|b] (a,b) -> c
(+) :: Operator((a,b) -> c)
add [a|b] (a,b) -> c
hash :: Operator(Hashable -> Integer)
type :: Operator(Typeable -> Scheme)
Some of these operators select a method by picking it based on the type. The operators with relations in them, such as the equality and addition, select a method by a type constructor.
Type constructors have a coercible-relation set for them. This relation describes acceptable forms of implicit conversions and the function that does the conversion.
For example, to resolve the
eq [a|b] (a,b) -> c, the type
constructors are collected from the
a and
b arguments.
x,y in selector
exist unique y. forall x {x!=y}. coercible(x, y)
convert every element to y, select operation from y.
This approach allows the type system to infer the types, but also gives enough leeway to provide very sufficient means for representing algebra in code.
Kinds with subtyping
Just like with Haskell, we are going to need kinds. The kinds have to recognize covariance, contravariance, bivariance and some forms of abstract invariance.
So we have slightly more kinds here. They are not used in typeclasses, rather, these are needed for determining what the shapes of the types are and how to construct valid types.
bool ................ +
list ................ ± -> +
builtin ............. F -> +
record_immutable .... R+ -> +
record_mutable ...... R± -> +
singleton ........... O -> + (module or ffi library)
linalg .............. (+, I, I) -> +
product ............. (+...) -> +
map ................. (±, ±) -> +
Likely in a real usecase these would seem slightly different:
Foo :: Interface((vp) -> vp)
Foo(a) :: vp
The purpose for representing types would be to issue explicit type conversions and annotate objects for type checking.
What's the type of
Interface or
vp? I guess the issue
could be skipped by treating these as representation for
the idea of a type. And you could always just leave them
untyped as well. Some functions, such as those that are
involved when creating new types, may become difficult to
type inference anyway.
The
type() operation will be run for every element when a
module is created, but it doesn't have to succeed for every
element in a module.
CFFI-viewpoint
A working C-FFI that interacts in a meaningful way with the type inferencer is the one of the most obvious points where large gains can be made.
If C-libraries are typed well-enough, they are relatively safe to use in a high-level, type-inferenced environment.
An optimizing compiler can be made that takes in the functions and their type inference results, then produce well-optimized code as a result.
I took the interfaces from an existing FFI library I've written and wrote how they correspond to types in the new system:
api.headers ....... module-like constructs
ffi.library
ffi.array ......... obvious type constructors
ffi.bitmask
ffi.cfunc
ffi.pointer
ffi.struct
ffi.union
ffi.signed
ffi.unsigned
ffi.wrap .......... wrapped type, type constructor
ffi.handle ........ instances of a type
ffi.mem data constructors
ffi.callback
ffi.pool .......... semi-automatic pool allocation for trivial uses.
a data constructor {often hidden}
Finally
There are some details I left out, and details that I am not aware about yet. But I hope this is interesting enough.
During the next week I'll be writing a subtyping type inferencer in RPython. At first I thought about writing it in the language itself, but I haven't figured out the whole syntax, and this is so important part of the language that I can't leave it last.
I will release a working prototype of this language sometime during this year. | http://boxbase.org/entries/2018/apr/30/dynamic-static-typing/ | CC-MAIN-2018-34 | refinedweb | 1,622 | 54.93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.