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
Static. We don’t know how regularly the project’s authors use these tools, but Klocwork and Coverity are mentioned in the bugtracker and ChangeLog-xxx files. We also saw Qt mentioned to be regularly checked with PC-lint. Analysis results ‘getTouchInputInfo’ to the left and to the right of the ‘&&’ operator. qwindowscontext.cpp 216 Values are assigned to four variables, and all the four must be checked. But only 3 are actually checked because of a typo. In the last line, ‘closeTouchInputHandle’ should be written instead of ‘get ‘||’ operator: iw <= 0 || iw <= 0 qwindowsfontengine.cpp 1095 The check of the height parameter stored in the ‘ih’ ‘!=’ We ‘||’ operator. qxml.cpp 3249 The ‘name’ variable is compared to one and the same string twice. A bit earlier in the code, a similar comparison can be found where a variable is compared with the following two strings: - - By analogy, you can conclude that the ‘name’ ‘!m_seconds’ to the left and to the right of the ‘&&’ operator. qdaytimeduration.cpp 148 The programmer forgot about milliseconds. Milliseconds are stored in the ‘m ‘!qIsFinite(w)’ to the left and to the right of the ‘||’ operator. qquickcontext2d.cpp 3305 A check of the ‘h’ variable is missing. The ‘w’ ‘num1’, ‘num2’ are initialized through the call to the same function. It’s probably an error or un-optimized code. Consider inspecting the ‘o1.as < Numeric > ()’ expression. Check lines: 220, 221. qatomiccomparators.cpp 221 The variables ‘num1’ and ‘num2’ are initialized to one and the same value. Then both the variables are checked, and that is strange: it would be enough to check only one variable. The ‘num2’ variable was most likely meant to be initialized to an expression with the ‘o ‘&&’. We ‘||’ operator: ignoreTrans || ignoreTrans qdeclarativestategroup.cpp 442 Something is wrong with this code. We ‘pattern->patternRepeatY’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1775, 1776. qquickcontext2d.cpp 1776 The ‘pattern we ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. qsettings.cpp 1702 The loop is designed to find the end of a string. The characters ‘\n’ or ‘\r’ are used as end-of-string indicators. Inside the condition, a character must be taken and compared against ‘\n’ and ‘\r’. The error occurs because the ‘!=’ operator’s priority is higher than that of the ‘=’ operator. Because of this, the ‘true’ or ‘false’ value is written instead of the character code into the ‘ch’ variable. It makes the ‘\r’ comparison meaningless. Let’s arrange parentheses to make the error clearer: while (i < dataLen && ((ch = (data.at(i) != '\n')) && ch != '\r')) Because of the mistake, it is only the ‘\n’ character that is treated as an end-of-string indicator. The function won’t work correctly for strings ending with ‘ ‘packet.pkOrientation.orAzimuth / 10’ expression was implicitly casted from ‘int’ type to ‘double’ type. Consider utilizing an explicit type cast to avoid the loss of a fractional part. An example: double A = (double)(X) / Y;. qwindowstabletsupport.cpp 467 The ‘packet.pkOrientation.orAzimuth’ variable is of the ‘int’ type. This integer variable is divided by 10. What is suspicious about this is that the quotient is then used together with values of the ‘double’ type. The final result is also saved into a variable of the ‘double’ type. Such integer division is not always an error. Perhaps this code is written just the way the programmer intended. But practice shows that it is more often than not a mistake causing accuracy loss. Suppose, for instance, that the ‘packet ‘new’ operator is used to allocate memory. Nowadays, it throws an exception when it fails to allocate memory. Of course, you can make the ‘new’ ‘penum’ pointer against null, as the memory was allocated using the ‘new’ we can’t say for sure if they are errors or not as we ‘memset’ function is used to nullify the fields of ‘QObject’ class. Virtual method table will be damaged by this. qqmlvme.cpp 658 The QObject class has virtual functions, which means the object stores a pointer to a virtual methods table. We don’t find it a good idea to implement such objects through the memset() function. One more message of that kind: V598 The ‘memset’ function is used to nullify the fields of ‘QObject’ class. Virtual method table will be damaged by this. qdeclarativevme.cpp 286 Null pointer dereferencing We guess these errors could be classified as typos, but we’d ‘m’ might take place. qquickcontext2d.cpp 3169 We are sure the ‘!’ ‘dn’ ‘outline’ pointer was utilized before it was verified against nullptr. Check lines: 1746, 1749. qgrayraster.c 1746 We ‘outline’ ‘if ‘index’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 568, 570. moc.cpp 570 Why different values are assigned to the ‘index’ variable? There are a few more similar strange code fragments: - V519 The ‘exitCode’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 807, 815. qprocess.cpp 815 - V519 The ‘detecting’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 163, 164. qhoversensorgesturerecognizer.cpp 164 - V519 The ‘increaseCount’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 185, 186. qtwistsensorgesturerecognizer.cpp 186 Suspecting a missing ‘break’ ‘consumed’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 110, 115. googlesuggest.cpp 115 So is the break operator missing here or not? The analyzer found it strange that the ‘consumed’ variable was assigned the ‘true’ value twice on end. It suggests a missing break operator, but we are not sure. It may be just that the first assignment should be removed: “consumed = true;”. Suspecting an excess ‘break’ operator bool QHelpGenerator::registerVirtualFolder(....) { .... while (d->query->next()) { d->namespaceId = d->query->value(0).toInt(); break; } .... } PVS-Studio’s diagnostic message: V612 An unconditional ‘break’ within a loop. qhelpgenerator.cpp 429 Was the ‘break’ ‘toLower’ is required to be utilized. main.cpp 72 The ‘toLower()’ function doesn’t change the object – it returns a copy of an object that will store lower case characters. One more defect: V530 The return value of function ‘toLower’ ‘JTransparent’, i.e. the function may return 4. There is also a two-dimensional array ‘joining ‘j’ ‘if ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 188, 195. qmaintainingreader_tpl_p.h 188 - V517 The use of ‘if ‘then’ statement is equivalent to the ‘else’. We decided not to describe them in the article, but we should mention them at least. We didn’t study the reports for the libraries attentively, but we have noted down some bugs: qt-3rdparty.txt. Note. Don’t assume, however, that I was attentively studying bugs from Qt instead. The project is pretty large and even a superficial analysis was enough to collect examples for this article. Conclusion Qt turned out to be a great project, but with quite a number of bugs. Therefore, we can really say that PVS-Studio. By Andrey Karpov
https://hownot2code.com/2016/10/10/checking-the-qt-5-framework/
CC-MAIN-2021-39
refinedweb
1,174
60.21
Agenda See also: IRC log <trackbot> Date: 12 March 2009 <pimpbot> Title: {agenda} HTML WG telcon 2009-03-12 from Sam Ruby on 2009-03-11 (public-html-wg-announce@w3.org from January to March 2009) (at lists.w3.org) <rubys> anybody want to scribe? <scribe> scribe: MikeSmith <scribe> scribenick: MikeSmith <pimpbot> Title: HTML Weekly Teleconference -- 12 Mar 2009 (at) issue-59? <trackbot> ISSUE-59 -- Should the HTML WG produce a separate document that is a normative language reference and if so what are the requirements -- OPEN <trackbot> <pimpbot> Title: ISSUE-59 - HTML Weekly Tracker (at) <DanC> action-94: SVG Feedback on HTML5 SVG Proposal <trackbot> ACTION-94 Report back on SVG WG's integration proposal re: issue-37 notes added <pimpbot> Title: SVG Feedback on HTML5 SVG Proposal from Doug Schepers on 2009-03-10 (public-html@w3.org from March 2009) (at lists.w3.org) <Lachy> I'm here, IRC only for now. Unless I'm needed, I won't call in <masinter> I'm willing to help but would appreciate some guidance about what things Mike wants reviewed or needs help with <dsinger> we did have a conversation about the normative status; could that be a sub-question, like the requirements are? <dsinger> i.e. Should the HTML WG produce a separate document that is a language reference and if so, should it be normative, and what are the requirements? <smedero> I'm also intending to help. I sent Mike some rough review notes last week. <DanC> yes, we did, dsinger; I think the document now says "dunno what status this will eventually have" <Zakim> DanC, you wanted to note a little progress and to invite smedero <smedero> and Mike just answered my question about needing help w/ examples. DanC: smedero, maybe you could send a version of your message that you mailed directly to Mike & me? smedero: yeah, can do that <dsinger> I also note that Hixie is 'about 40% done' on producing some of the supporting technical details automatically from the spec. <DanC> ACTION-109? <trackbot> ACTION-109 -- Sam Ruby to pursue publication of HTML 5: The Markup Language... poll or whatever -- due 2009-03-26 -- OPEN <trackbot> <pimpbot> Title: ACTION-109 - HTML Weekly Tracker (at) masinter: before doing a poll, would like to have a version that I can pass around internally <scribe> ACTION: Michael(tm) to coordinate review of current H:TML draft [recorded in] <trackbot> Created ACTION-116 - Coordinate editing work of current H:TML draft [on Michael(tm) Smith - due 2009-03-19]. <DanC> action-109? <trackbot> ACTION-109 -- Michael(tm) Smith to hand out work to reviewers of HTML 5: The Markup Language... -- due 2009-03-26 -- OPEN <trackbot> <pimpbot> Title: ACTION-109 - HTML Weekly Tracker (at) <DanC> action-109 due next week <trackbot> ACTION-109 hand out work to reviewers of HTML 5: The Markup Language... due date now next week issue-37? <trackbot> ISSUE-37 -- Integration of SVG and MathML into text/html -- OPEN <trackbot> <pimpbot> Title: ISSUE-37 - HTML Weekly Tracker (at) <DanC> <pimpbot> Title: SVG Feedback on HTML5 SVG Proposal from Doug Schepers on 2009-03-10 (public-html@w3.org from March 2009) (at lists.w3.org) <DanC> (ACTION-94 is done to my satisfaction) [shepazu does recap] <masinter> (wasn't clear on what it is authors want or don't want) <DanC> (non-XML syntax for SVG, I think, masinter ) shepazu: SVG WG have come from a position that favored XML-only syntax to recognizing that browser vendors favor something with features of text/html ... I'm not convinced that authors want that kind of syntax ... we are against HTML5 "whitelisting" particular elements ... ... would prefer that the HTML5 reference the SVG spec instead of whitelisting ... anyway, I think the issues are being hashed out on the mailing list <Lachy> from a web developer's perspective, I want syntactic consistency between HTML and SVG when they are mixed in text/html, rather than XML strictness for SVG [masinter discusses deployed tools that consume or produce SVG] shepazu: my concern is that we end up getting some hybrid syntax that Illustrator can't consume any more <anne> Illustrator can be updated just like browsers, no? <anne> easy to use HTML5 parsers are readily available shepazu: we are concerned about loss of all the network effects that SVG enjoys [if browers end up only supporting some subset of SVG] <anne> (it would also be interesting to know whether Illustrator can consume XHTML+SVG at present) masinter: that should not be called SVG [if that ends up happening] shepazu: 2 steps: 1, error reporting; and 2, we like the export-SVG-by-right-clicking idea ... I agree with hsivonen, who said the issue is that changing parsers consumes significant resources ... ... [not changing parsers] results in faster performance [which is preferable] ... point is not to punish the end user for mistakes in source ... but I don't think there are hordes of authors our there producing SVG by hand from text editors <rubys> I do :-) <gsnedders> You're weird! <anne> I do too, usually shepazu: they are instead producing SVG using programming languages, and tools like Inkscape <rubys> can we start to wrap up the error recover aspects of this discussion? shepazu: SVG does not define its own processing and parsing model ... but for example, there are special considerations, like the fact that svg elements must be closed DanC: there's a pattern where structured-markup languages, when they hit the prime time, turn fuzzy <Zakim> DanC, you wanted to noodle on the pattern of XML languages getting fuzzy, not just HTML but also RSS, and to note risks of "I don't care how they implement it" <masinter> was just trying to understand the position shepazu: in the beginning, SVG tools did not require a namespace declaration, and still some tools in current use don't require it <masinter> to clarify my comments here: I understand the different possible positions, was trying to understand which one the SVG group was taking Julian: seems to be some agreement here, should take it back to mailing list <masinter> sorry for not noticing q :( <DanC> ("our wiki page" = ? ) <pimpbot> Title: SVG in text-html 2009 - SVG (at) shepazu: there are issues about this that the implementors in teh SVG WG don't yet agree on themselves (oink oink) <DanC> close ACTION-94 <trackbot> ACTION-94 Report back on SVG WG's integration proposal re: issue-37 closed shepazu: I would like to ask that teh SVG WG's comments be reified in the spec ... Hixie expressed a bit of sense of urgency on this, because implementors are implementing already the commented-out SVG part of the HTML5 draft <rubys> action doug to get svg working group to propose specific text <trackbot> Created ACTION-117 - Get svg working group to propose specific text [on Doug Schepers - due 2009-03-19]. <shepazu> ACTION-117 <shepazu> ACTION-117? <trackbot> ACTION-117 -- Doug Schepers to get svg working group to propose specific text -- due 2009-03-19 -- OPEN <trackbot> <pimpbot> Title: ACTION-117 - HTML Weekly Tracker (at) <DanC> (I'd like to see a test case for the whitelisting issue.) <shepazu> DanC: yes, that' s the correct link <masinter> ask that a new editor's draft be generated which has 'commented out' sections noted rather than redacted, so that "Editors Draft" in W3C matches what implementors are looking at Lachy: we looking at your action now <DanC> action-103? <trackbot> ACTION-103 -- Lachlan Hunt to track registration of about: URI scheme -- due 2009-03-17 -- OPEN <trackbot> <pimpbot> Title: ACTION-103 - HTML Weekly Tracker (at) action-34? <trackbot> ACTION-34 -- Lachlan Hunt to prepare "Web Developer's Guide to HTML5" for publication in some way, as discussed on 2007-11-28 phone conference -- due 2009-02-27 -- OPEN <trackbot> <Lachy> ok <pimpbot> Title: ACTION-34 - HTML Weekly Tracker (at) <Lachy> see <pimpbot> Title: Re: {agenda} HTML WG telcon 2009-03-12 from Lachlan Hunt on 2009-03-11 (public-html@w3.org from March 2009) (at lists.w3.org) <DanC> oops. sorry. I was in the wrong place action-78? <trackbot> ACTION-78 -- Lachlan Hunt to work on text and heading for 1.5.4 Relationship to Flash, Silverlight, XUL and similar proprietary languages -- due 2009-03-01 -- OPEN <trackbot> <pimpbot> Title: ACTION-78 - HTML Weekly Tracker (at) [rubys notes that Lachy has provided status updates on the list] action-54? <trackbot> ACTION-54 -- Chris Wilson to ask PF WG to look at drafted text for HTML 5 spec to require producers/authors to include @alt on img elements -- due 2008-09-26 -- CLOSED <trackbot> <pimpbot> Title: ACTION-54 - HTML Weekly Tracker (at) <Lachy> ok, if you're done with my issues now, I'm leaving. Bye. <DanC> ACTION-110? <trackbot> ACTION-110 -- Michael(tm) Smith to add note to H:TML draft about what's currently missing and planned to be added -- due 2009-03-05 -- OPEN <trackbot> <pimpbot> Title: ACTION-110 - HTML Weekly Tracker (at) <DanC> action-110 due next week <trackbot> ACTION-110 Add note to H:TML draft about what's currently missing and planned to be added due date now next week <dsinger> URI for the wiki page? <DanC> rubys: I intend to be at the informal HTML meeting at IETF <pimpbot> Title: IETF HTML5 Meeting March 2009 - ESW Wiki (at esw.w3.org) <DanC> (I just added "HTML 5 and scripting media types" to the agenda) <masinter> no IETF registration (please wiki register) required <DanC> wiki registration appreciated <masinter> no IETF registration required <pimpbot> Title: HTML Weekly Teleconference -- 12 Mar 2009 (at) [adjourned] This is scribe.perl Revision: 1.133 of Date: 2008/01/18 18:48:51 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/Issue 50/Issue 59/ Succeeded: s/review/editing work/ Succeeded: s/no registration/no IETF registration (please wiki register)/ Found Scribe: MikeSmith Inferring ScribeNick: MikeSmith Found ScribeNick: MikeSmith Default Present: Mike Present: Mike WARNING: Fewer than 3 people found for Present list! Agenda: WARNING: No meeting chair found! You should specify the meeting chair like this: <dbooth> Chair: dbooth Found Date: 12 Mar 2009 Guessing minutes URL: People with action items: michael tm[End of scribe.perl diagnostic output]
http://www.w3.org/2009/03/12-html-wg-minutes.html
CC-MAIN-2015-35
refinedweb
1,713
51.92
Hi there, I'm trying to write a program to accept some details about mp3 files, and store them in an array. I am also hoping to process some of the parameters of each entry to the array. I am trying to create an object of type "Track", and then define a method "createTrack" to define some parameters to describe the Object "Track". This is what I've come up with, but needless to say, it doesn't work! :( If anyone could suggest some adjustments, it would be much appreciated! #include<iostream> #include<string> using namespace std; using std::string; class Track{ public: Track(void); void time(); void createTrack(); }; void Track::createTrack() { string title; string artist; float duration; cout <<"Please enter track title: "; cin >> title; cout <<"Please enter track artist: "; cin >> artist; cout <<"Please enter track duration in seconds: "; cin >> duration; } void Track:time(int duration) { mins = (duration/60); secs = (duration%60); cout << "The track time is: " << mins << "minutes and" << secs << "seconds" << endl; } int main() { for (int i=0; i<5; i++) { Track a; //Create a new object of type "Track" TrackArray[i] = a.createTrack; //Call the "createTrack" method on the object } //"a" and store it in the array "TrackArray[4]" TrackArray[1].time; //Call the "time" method on the 1th entry of the array system("Pause"); return EXIT_SUCCESS; }
https://www.daniweb.com/programming/software-development/threads/96792/nub-question-about-classes
CC-MAIN-2017-17
refinedweb
219
54.66
GreenCard is a preprocessor for Haskell which allows Haskell functions to call C. (For the really brave, nhc98 also has the ability to call Haskell code from C using GreenCard to set up the interface.) A paper (now superseded, see below) published in the Haskell Workshop 97 proceedings describes the design goals, input language, and translation mechanism. GreenCard was supposed to be standard across implementations of Haskell - however the Hugs/ghc version has now diverged somewhat. A new, more flexible but lower-level, primitive FFI is now common to Hugs/ghc and nhc98, and it provides a greater degree of cross-compiler portability than GreenCard. However, GreenCard is still useful for many small tasks, and you may find it is just the right tool for your particular application. Since the Haskell Workshop paper, several improvements have been made to the input language and DIS macros. GreenCard for nhc98 follows the design agreed with the Glasgow and Hugs implementors (although the Glasgow implementation does not!). Here is the best extant description of GreenCard closely matching the nhc98 version. There are just a few differences specific to the nhc98 version of the tool. import GreenCard %fun foo :: (Age,Age) -> Age %call (Age (int x), Age (int y)) %code r = foo(x,y); %result (Age (int r)) %fun f :: This -> This %call (MkThis (int p) (float q, float r)) %code int a,b,c; % f( p, q, r, &a, &b, &c); %result (this a b c) The latest updates to these pages are available on the WWW from 22 December 1999 York Functional Programming Group
https://www.haskell.org/nhc98/greencard-york.html
CC-MAIN-2015-18
refinedweb
262
56.59
Interesting article after I figured out that you have to use Unix line endings of newline (\n) for the Ruby processor. I use the BBEdit text editor and had changed line endings to return (\r) for AppleScript and web pages. newline return I did still have trouble prefixing the 'Hello, World!' example with "self." per your explanation. Nothing I tried got past the following error: firstprogram.rb:1: private method `puts' called for #<Object:0xd2cd8> (NameError) I tried both "self.puts" and "self.print" but they both produce the same error (with the obvious method name change). Any ideas or hints? © 2015, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/cs/user/view/cs_msg/41260
CC-MAIN-2015-35
refinedweb
128
62.14
Below is a sample code snippet demonstrating the usage of Lambda expression to get the Max value from a list of integer in C#. How to Get the Max Value from a List of Integer using Lambda Expression in C#? using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace AbundantCode { internal class Program { //How to Get the Max Value from a List Of Integer using Lambda Expression in C#? private static void Main(string[] args) { int[] Marks = new int[] { 1, 2, 8, 3, 10, 25, 4 }; // Get Max using Lambda Expression var result = Marks.Max(); Console.WriteLine(result); Console.ReadLine(); } } } But what about select the max-length word from a list?above code does not work compile any more. It works fine … Could you elaborate the steps that you followed wich resulted in the compiler error and what is the error that you received ?
http://abundantcode.com/how-to-get-the-max-value-from-a-list-of-integer-using-lambda-expression-in-c/
CC-MAIN-2018-26
refinedweb
148
57.57
#!mechanism. On Windows NT, there is an executable named omniidl.exe. omniidl [options] -b<back-end> [back-end options] <file 1> <file 2> ...The supported flags are: omniidl -bdump -bpython foo.idl bar.idlfirst reads and parses foo.idl, and runs the dump and python back-ends on it in turn. Then it reads and parses bar.idl and runs the two back-ends on that. interface I; interface J { attribute I the_I; };then omniidl will normally issue a warning: test.idl:1: Warning: Forward declared interface `::I' was never fully definedIt is illegal to declare such IDL in isolation, but it is valid to define interface I in a separate file. If you have a lot of IDL with this sort of construct, you will drown under the warning messages. Use the -nf option to suppress them. interface I { void op1(); // A comment void op2(); };the -k flag will attach the comment to op1(); the -K flag will attach it to op2(). cpp_args = ["-D__OMNIIDL_PYTHON__"] template = """\ class @id@ { public: @id@(@type@ a) : a_(a) {} private: @type@ a_; };""" st.out(template, id="foo", type="int")would result in output: class foo { public: foo(int a) : a_(a) {} private: int a_; };When @ expressions are substituted, the expression is actually evaluated, not just textually replaced. This means that you can write templates containing strings like `@obj.name()@'. Expressions must evaluate to strings. This feature should not be over-used---it is very easy to write incomprehensible template expressions. The vast majority of templates should only use simple string substitutions. >>> pruneScope(['A','B','C','D'],['A','B','D']) ['C','D'] typedef long MyLong; const MyLong foo = 123;constKind() will return tk_long, but constType() will return an idltype.Declared object (see page ??) which refers to MyLong's typedef Declarator object. typedef struct foo { long l; } bar; struct S { struct T { long l; } the_T; }; struct S { long l; sequence <S> ss; }; attribute long a, b;identifiers() will return ['a','b']. from omniidl import idlast, idlvisitor, idlutil import string class ExampleVisitor (idlvisitor.AstVisitor): def visitAST(self, node): for n in node.declarations(): n.accept(self) def visitModule(self, node): for n in node.definitions(): n.accept(self) def visitInterface(self, node): name = idlutil.ccolonName(node.scopedName()) if node.mainFile(): for c in node.callables(): if isinstance(c, idlast.Operation): print name + "::" + \ c.identifier() + "()" def run(tree, args): visitor = ExampleVisitor() tree.accept(visitor)The visitor object simple recurses through the AST and Module objects, and prints the operation names it finds in Interface objects. This document was translated from LATEX by HEVEA.
http://www.cl.cam.ac.uk/research/dtg/attarchive/omniORB/doc/3.0/omniidl.html
crawl-003
refinedweb
424
51.75
This article was originally published in HackerNoon Over the years I've jumped back and forth between many code editors, IDEs and tools; but it seems that somehow I always end up coming right back to VIM, and not only for programming – guess which markdown editor I'm using to write this post. I've have tried Atom,: """"""""""""""""""""""""""""""""""""" " Allan MacGregor Vimrc configuration """"""""""""""""""""""""""""""""""""" set nocompatible syntax on set nowrap set encoding=utf8 """" START Vundle Configuration " Disable file type for vundle filetype off " required " set the runtime path to include Vundle and initialize set rtp+=~/.vim/bundle/Vundle.vim call vundle#begin() " let Vundle manage Vundle, required Plugin 'gmarik/Vundle.vim' " Utility Plugin 'scrooloose/nerdtree' Plugin 'majutsushi/tagbar' Plugin 'ervandew/supertab' Plugin 'BufOnly.vim' Plugin 'wesQ3/vim-windowswap' Plugin 'SirVer/ultisnips' Plugin 'junegunn/fzf.vim' Plugin 'junegunn/fzf' Plugin 'godlygeek/tabular' Plugin 'ctrlpvim/ctrlp.vim' Plugin 'benmills/vimux' Plugin 'jeetsukumaran/vim-buffergator' Plugin 'gilsondev/searchtasks.vim' Plugin 'Shougo/neocomplete.vim' Plugin 'tpope/vim-dispatch' " Generic Programming Support Plugin 'jakedouglas/exuberant-ctags' Plugin 'honza/vim-snippets' Plugin 'Townk/vim-autoclose' Plugin 'tomtom/tcomment_vim' Plugin 'tobyS/vmustache' Plugin 'janko-m/vim-test' Plugin 'maksimr/vim-jsbeautify' Plugin 'vim-syntastic/syntastic' Plugin 'neomake/neomake' " Markdown / Writting Plugin 'reedes/vim-pencil' Plugin 'tpope/vim-markdown' Plugin 'jtratner/vim-flavored-markdown' Plugin 'LanguageTool' " Git Support Plugin 'kablamo/vim-git-log' Plugin 'gregsexton/gitv' Plugin 'tpope/vim-fugitive' "Plugin 'jaxbot/github-issues.vim' " PHP Support Plugin 'phpvim/phpcd.vim' Plugin 'tobyS/pdv' " Erlang Support Plugin 'vim-erlang/vim-erlang-tags' Plugin 'vim-erlang/vim-erlang-runtime' Plugin 'vim-erlang/vim-erlang-omnicomplete' Plugin 'vim-erlang/vim-erlang-compiler' " Elixir Support Plugin 'elixir-lang/vim-elixir' Plugin 'avdgaag/vim-phoenix' Plugin 'mmorearty/elixir-ctags' Plugin 'mattreduce/vim-mix' Plugin 'BjRo/vim-extest' Plugin 'frost/vim-eh-docs' Plugin 'slashmili/alchemist.vim' Plugin 'tpope/vim-endwise' Plugin 'jadercorrea/elixir_generator.vim' " Elm Support Plugin 'lambdatoast/elm.vim' " Theme / Interface Plugin 'AnsiEsc.vim' Plugin 'ryanoasis/vim-devicons' Plugin 'vim-airline/vim-airline' Plugin 'vim-airline/vim-airline-themes' Plugin 'sjl/badwolf' Plugin 'tomasr/molokai' Plugin 'morhetz/gruvbox' Plugin 'zenorocha/dracula-theme', {'rtp': 'vim/'} Plugin 'junegunn/limelight.vim' Plugin 'mkarmona/colorsbox' Plugin 'romainl/Apprentice' Plugin 'Lokaltog/vim-distinguished' Plugin 'chriskempson/base16-vim' Plugin 'w0ng/vim-hybrid' Plugin 'AlessandroYorba/Sierra' Plugin 'daylerees/colour-schemes' Plugin 'effkay/argonaut.vim' Plugin 'ajh17/Spacegray.vim' Plugin 'atelierbram/Base2Tone-vim' Plugin 'colepeters/spacemacs-theme.vim' " OSX stupid backspace fix set backspace=indent,eol,start call vundle#end() " required filetype plugin indent on " required """" END Vundle Configuration """"""""""""""""""""""""""""""""""""" " Configuration Section """"""""""""""""""""""""""""""""""""" " Show linenumbers set number set ruler " Set Proper Tabs set tabstop=4 set shiftwidth=4 set smarttab set expandtab " Always display the status line set laststatus=2 " Enable Elite mode, No ARRRROWWS!!!! let g:elite_mode=1 " Enable highlighting of the current line set cursorline " Theme and Styling set t_Co=256 set background=dark if (has("termguicolors")) set termguicolors endif let base16colorspace=256 " Access colors present in 256 colorspace colorscheme spacegray " colorscheme spacemacs-theme let g:spacegray_underline_search = 1 let g:spacegray_italicize_comments = 1 " Vim-Airline Configuration let g:airline#extensions#tabline#enabled = 1 let g:airline_powerline_fonts = 1 let g:airline_theme='hybrid' let g:hybrid_custom_term_colors = 1 let g:hybrid_reduced_contrast = 1 " Syntastic Configuration " let g:syntastic_enable_elixir_checker = 1 " let g:syntastic_elixir_checkers = ["elixir"] " Neomake settings autocmd! BufWritePost * Neomake let g:neomake_elixir_enabled_makers = ['mix', 'credo', 'dogma'] " Vim-PDV Configuration let g:pdv_template_dir = $HOME ."/.vim/bundle/pdv/templates_snip" " Markdown Syntax Support augroup markdown au! au BufNewFile,BufRead *.md,*.markdown setlocal filetype=ghmarkdown augroup END " Github Issues Configuration let g:github_access_token = "e6fb845bd306a3ca7f086cef82732d1d5d9ac8e0" " Vim-Alchemist Configuration let g:alchemist#elixir_erlang_src = "/Users/amacgregor/Projects/Github/alchemist-source" let g:alchemist_tag_disable = 1 " Vim-Supertab Configuration let g:SuperTabDefaultCompletionType = "<C-X><C-O>" " Settings for Writting let g:pencil#wrapModeDefault = 'soft' " default is 'hard' let g:languagetool_jar = '/opt/languagetool/languagetool-commandline.jar' " Vim-pencil Configuration augroup pencil autocmd! autocmd FileType markdown,mkd call pencil#init() autocmd FileType text call pencil#init() augroup END " Vim-UtilSnips Configuration " Trigger configuration. Do not use <tab> if you use let g:UltiSnipsExpandTrigger="<tab>" let g:UltiSnipsJumpForwardTrigger="<c-b>" let g:UltiSnipsJumpBackwardTrigger="<c-z>" let g:UltiSnipsEditSplit="vertical" " If you want :UltiSnipsEdit to split your window. " Vim-Test Configuration let test#strategy = "vimux" " Neocomplete Settings let g:acp_enableAtStartup = 0 let g:neocomplete#enable_at_startup = 1 let g:neocomplete#enable_smart_case = 1 let g:neocomplete#sources#syntax#min_keyword_length = 3 " Define dictionary. let g:neocomplete#sources#dictionary#dictionaries = { \ 'default' : '', \ 'vimshell' : $HOME.'/.vimshell_hist', \ 'scheme' : $HOME.'/.gosh_completions' \ } " Define keyword. if !exists('g:neocomplete#keyword_patterns') let g:neocomplete#keyword_patterns = {} endif let g:neocomplete#keyword_patterns['default'] = '\h\w*' function! s:my_cr_function() return (pumvisible() ? "\<C-y>" : "" ) . "\<CR>" " For no inserting <CR> key. "return pumvisible() ? "\<C-y>" : "\<CR>" endfunction " Close popup by <Space>. "inoremap <expr><Space> pumvisible() ? "\<C-y>" : "\<Space>" " AutoComplPop like behavior. "let g:neocomplete#enable_auto_select = 1 " Enable omni completion. autocmd FileType c " Enable heavy omni completion. if !exists('g:neocomplete#sources#omni#input_patterns') let g:neocomplete#sources#omni#input_patterns = {} endif "let g:neocomplete#sources#omni#input_patterns.php = '[^. \t]->\h\w*\|\h\w*::' "let g:neocomplete#sources#omni#input_patterns.c = '[^.[:digit:] *\t]\%(\.\|->\)' "let g:neocomplete#sources#omni#input_patterns.cpp = '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::' " For perlomni.vim setting. " let g:neocomplete#sources#omni#input_patterns.perl = '\h\w*->\h\w*\|\h\w*::' " Elixir Tagbar Configuration let g:tagbar_type_elixir = { \ 'ctagstype' : 'elixir', \ 'kinds' : [ \ 'f:functions', \ 'functions:functions', \ 'c:callbacks', \ 'd:delegates', \ 'e:exceptions', \ 'i:implementations', \ 'a:macros', \ 'o:operators', \ 'm:modules', \ 'p:protocols', \ 'r:records', \ 't:tests' \ ] \ } " Fzf Configuration " This is the default extra key bindings let g:fzf_action = { \ 'ctrl-t': 'tab split', \ 'ctrl-x': 'split', \ 'ctrl-v': 'vsplit' } " Default fzf layout " - down / up / left / right let g:fzf_layout = { 'down': '~40%' } " In Neovim, you can set up fzf window using a Vim command let g:fzf_layout = { 'window': 'enew' } let g:fzf_layout = { 'window': '-tabnew' } " Customize fzf colors to match your color scheme'] } " Enable per-command history. " CTRL-N and CTRL-P will be automatically bound to next-history and " previous-history instead of down and up. If you don't like the change, " explicitly bind the keys to down and up in your $FZF_DEFAULT_OPTS. let g:fzf_history_dir = '~/.local/share/fzf-history' """"""""""""""""""""""""""""""""""""" " Mappings configurationn """"""""""""""""""""""""""""""""""""" map <C-n> :NERDTreeToggle<CR> map <C-m> :TagbarToggle<CR> " Omnicomplete Better Nav inoremap <expr> <c-j> ("\<C-n>") inoremap <expr> <c-k> ("\<C-p>") " Neocomplete Plugin mappins inoremap <expr><C-g> neocomplete#undo_completion() inoremap <expr><C-l> neocomplete#complete_common_string() " Recommended key-mappings. " <CR>: close popup and save indent. inoremap <silent> <CR> <C-r>=<SID>my_cr_function()<CR> " <TAB>: completion. inoremap <expr><TAB> pumvisible() ? "\<C-n>" : "\<TAB>" " <C-h>, <BS>: close popup and delete backword char. inoremap <expr><C-h> neocomplete#smart_close_popup()."\<C-h>" inoremap <expr><BS> neocomplete#smart_close_popup()."\<C-h>" " Mapping selecting Mappings nmap <leader><tab> <plug>(fzf-maps-n) xmap <leader><tab> <plug>(fzf-maps-x) omap <leader><tab> <plug>(fzf-maps-o) " Shortcuts nnoremap <Leader>o :Files<CR> nnoremap <Leader>O :CtrlP<CR> nnoremap <Leader>w :w<CR> " Insert mode completion imap <c-x><c-k> <plug>(fzf-complete-word) imap <c-x><c-f> <plug>(fzf-complete-path) imap <c-x><c-j> <plug>(fzf-complete-file-ag) imap <c-x><c-l> <plug>(fzf-complete-line) " Vim-Test Mappings nmap <silent> <leader>t :TestNearest<CR> nmap <silent> <leader>T :TestFile<CR> nmap <silent> <leader>a :TestSuite<CR> nmap <silent> <leader>l :TestLast<CR> nmap <silent> <leader>g :TestVisit<CR> " Vim-PDV Mappings autocmd FileType php inoremap <C-p> <ESC>:call pdv#DocumentWithSnip()<CR>i autocmd FileType php nnoremap <C-p> :call pdv#DocumentWithSnip()<CR> autocmd FileType php setlocal omnifunc=phpcd#CompletePHP " Disable arrow movement, resize splits instead. if get(g:, 'elite_mode') nnoremap <Up> :resize +2<CR> nnoremap <Down> :resize -2<CR> nnoremap <Left> :vertical resize +2<CR> nnoremap <Right> :vertical resize -2<CR> endif map <silent> <LocalLeader>ws :highlight clear ExtraWhitespace<CR> " Advanced customization using autoload functions inoremap <expr> <c-x><c-k> fzf#vim#complete#word({'left': '15%'}) " Vim-Alchemist Mappings autocmd FileType elixir nnoremap <buffer> <leader>h :call alchemist#exdoc()<CR> autocmd FileType elixir nnoremap <buffer> <leader>d :call alchemist#exdef()<CR>. Discussion (97) dev.to where is the dislike button? :/ VIM is not an IDE, just an editor that helps you write faster After you install 30 plugins and spend years of learning it you can come close to an IDE, but you lost a lot of time, for nothing. The length of the post and the config file is working against you, is proof that is not easy to work with, and still not doing a proper job If you would use an IDE in a proper manner (See Visual Studio or intelliJ) you will realize that your productivity is not about writing text (what Vim excels at), is at making your code work in the real world. Is more about development and less about being a type writer. If you write books, articles or pseudocode Vim is the best tool I agree, but .. the devs usually need to do DB queries, work with env tools, debug, see static analyzers warning, deploy dockers, run automatic tests, do merges, do huge refactoring that touches many files, find the "blame" on a bug, and so on (without writing or remember CLI commands or wasting time to setup the IDE). Just saying, as a "director" you should appreciate productivity and do not make "feels like home" decisions for work projects. Do not confuse "what I like to do" with "what I have to do, as a professional". By not using the proper tool, that gives you the fastest and most productivity you are wasting your employers money, so you are not being professional, you are just selfish. Adrian, VIM is a tool, every developer is entitled to its opinion and preference, VIM might not be the right fit for all stacks or all applications but I have successfully use it to work as you mention for writing, python development, elixir/erlang development. IntelliJ is great and I use it for other kinds of development (ionic for example); I find the knee jerk reaction to the size of configuration file a bit risible, the configuration file as shared has support for several languages, stacks and some of my personal customizations. Finally, I find that the ad hominem attack on the last part of your reply actually subtracts from what was actually some valid points on your argument. I just wanted to raise awareness on "VIM priests" that spread their false gossips around, I probably sound more passive-aggressive then it should. You just "forget" to mention that it is a personal preference, and state that "Vim is the perfect IDE" (for me?!), knowing in fact that is not even an IDE and not perfect. You "forget" to mention that you spent maybe years of being prolific, where in IDE's most of the things "just works". VIM is great when you have many small scripts/projects, or you alter big projects with minimal invasion, edit big files, or you are a sys admin, or ...(insert here a lot of stuff you didn't mention), but .... It is "a common trap" that I've seen are with web dev juniors, they usually: This combined with the fact that people hate change, leads to bigger problems once the developer gets involved in bigger and more complex projects. I just want to make things clear for the juniors and next generation of developers to make a big difference between "personal preferences" and "best tool for the job", and posts like this doesn't help at all. Please keep in mind that everything you've said so far is anecdotal. Others, such as me, may have different experiences. I tend to agree with BG. Tooling becomes vastly important when working with larger and more complex codebases. The kind of code analysis provided by actual IDEs simply cannot be replicated in Vim no matter how it's customized.: Vim, conceptually, is mode-based text editing with consistent, highly optimized keybindings. The beautiful thing about vim-as-a-concept is that it's available in some form or fashion in nearly every IDE and text editor. "vim-as-a-concept is that it's available in some form or fashion in nearly every IDE and text editor." ... and browser. In my line of work, I've seen little to no benefit with static analysis. I am working on a highly dynamic codebase. Sure, if your language is static its great, but I really don't see this as being a reason for not using VIM. I've actually seen VIM autocompletion be more accurate than IDE's (for newer languages such as Rust). I am very curious in what languages/line of work there are no benefits for static analysis, can you give some examples? Javascript - we use dependency injection heavily. wow ok, your team is great then! I was part of teams that didn't used but we ended up regretting. I usually saw linters solving a lot of (very small) problems in large teams and projects, like (forces a coding standard, find small bugs like forgetting to type a var or forgetting a switch default, fewer git merges/conflicts) which leads to a better codebase in general (if you enforce the rules at commit/build). As a sidenote linters are builtin in most IDEs so maybe you use them already, but only at a basic level. We use eslint (for the older projects, a combination of jshint and jscs). The plugin I use for vim (ale) works with pretty much any kind of linter I've encountered. This isn't the sort of static analysis I'd expect from and IDE though, this is what I'd expect from any kind of programmers editor (vscode, sublime, etc). What I meant by static analysis is the ability to goto definition, display documentation, refactor, etc. This is the sort of stuff which doesn't work consistently enough with our codebase to even bother trying. Ha, these kinds of comments always baffle me... Your comment can be summarized as: It's like telling someone "No, you shouldn't like chocolate", or "Your favorite movie is wrong". Chocolate and movies are indeed a matter of taste, but productivity is not (also note that 'feeling productive' and 'being productive' are two different things). Of course, these kind of discussions tend to spiral into the following, myself included :-) That is the problem, he didn't specified it is a personal preference, he said it as an absolute truth and other people can make wrong decisions. Wow great insight I actually wasted a lot of time in this stuff. Your insights. are very useful to me Linux, the whole environment, is your IDE. Vim is just one part of it. B.G. ..... My subjective opinion: you are bore and hysterical. It is a fact. And all about what you find fault with the author of the article applies to your claims. All this is subjective, even your praised productivity. I apologize for my english - google translate. "Stay hungry ..stay foolish.". Steve Jobs. Nope sorry, productivity can be measured, and the time you invested to reach that level. Also my claims can be easily verified after one week of Vim. sorry, client satisfied can be measured only I can do pretty much all of that in Vim with only a handful of plugins and little configuration. Also of note I've been in the biziness for roughly 7 years and have never had to deploy a container. 🤷🏼♂️ YMMV This, so much. I downloaded VSCode, used a clean GUI to install a few plugins, and I was developing nodeJS in minutes. That vimrc convinced me to never use the editor for anything serious. where is the dislike button? VIM is awsome, but not for everybody Correct I am actually using Vim, my point is that title of the post should be "Vim is the perfect IDE ... for me". Well I partially agree with you. As I use NeoVim for all my dev purposes, earlier I used to use Jetbrains' GoLand with vim plugin, I couldn't feel much difference as long as productivity is concerned. Only reason I shifted to NeoVim was so that I don't have to use mouse, and I was too busy to learn Jetbrains' shortcuts. I was able to replicate most functionalities... debugger you say? yes that is one major caveat in Vim or Neovim, etc. but I was able to successfully integrate that too in vim. I have heavily customized init.vim (not too many plugins, around 10-15) and I can work very fast while doing my work. What I'm trying to say is, Vim alone --> just an editor Vim with right set of tools (I don't mean plugins here) --> a Development Environment, only difference is they are not integrated, hence not an IDE. Now I'm not any pro or something like that, but the works that I have done till now, I can tell I was more productive with NeoVim with conjunction to some other tools when compared to an IDE. ^ This person is my favorite. I'd also like a dislike button. VIM is like all kids in the 80s who knew how to solve the Rubik's cube puzzle decided to make and IDE version. An over complicated, hard to figure out editor. Which they can feel superior in using knowing that only they know how to use it. Nowadays I'm a Visual Studio Code user, but both Vim ( :help) and Emacs ( C-h t) have excellent built-in help systems, so they aren't really that hard to learn. You're wrong about the 80s kids though ;-) – the first versions of both Emacs and vi were released in 1976 (and Vim showed up in 1991) when their interfaces were far from being esoteric but actually rather sophisticated. I was more referring to descriptions of the overlords than the timeline itself. Rubik's cube was the first thing to come to mind and I think that was the 80s. I understand, I was just trying to point out that not everyone who uses either of them thinks of them as something special and that they are actually fairly approachable. For quite a while Emacs/Vim were the best we had and it's hard to switch tools sometimes. That said, after quite a few years of heavy Emacs usage I switched to VS Code last year and am really happy so far, mostly because its core feature set aligns well with the work I'm doing everyday. I love vim. I started learning java on a Chromebook, which Eclipse proved too much for and wound up on Codenvy. From there I messed with IntelliJ and Eclipse Photon but I really didn't like either. Especially Eclipse photon plugins suck, the ui feels laggy, there are tiny mostly inconsequential bug that are just annoying enough to trigger my OCD. I get the benefits on a larger code base but vim is something that can be fine tuned. Sure it's more work, but I can be sure vim (neovim) will work smoothly and exactly how I want. The LanguageClient plugin I run is way more consistent than the vscode redhat plugin and they share a jdt.ls! I'm an obsessive tinker and vim fulfills both for me! What do you care what another developer uses? This sounds like just another Mac vs Windows vs Linux argument that is all opinions BTW, I know of companies that use Notepad++ as their "IDE" and in my opinion it's no different than vim(or a variant like Neovim). I don't care what another developer uses. It literally does not matter, in the long run. However I like these arguments. It's always funny to see the more extreme reactions and insightful to see the discussions to these small details. Do you know why I love these arguments? Simply because I'm not arguing with some faceless twitter avatar about why women, people of color, LGBTQ+ people are under represented (or underpaid) in STEM fields. I don't have to make some passionate argument as to why basic human decency and inclusion should apply to everyone. You get into a having a real discussion about people's experiences and why these features matter from one person to the other. I just enjoy the debate. You're right though, it does not matter. I'm in the same place. It seems like one a year I go out and try out other editors or IDEs, and always find myself in vim. Well now Neovim and using deoplete. I've tried the new language server protocol, but had some prefomance issues. To answer the question below. I primarily develop Go these days so I have that deeply integrated. Delve for breakpoints, I get in line errors as well simple key bindings for extra go metalinter tooling. It does take work and your config is a living setup. Would you mind to share your Go config for (Neo)vim? Yes @dtoebe ! I would appreciate it as well I'm a vim fanboy, I really think it's a great tool but it's far from being perfect. The great thing about vim, as you demonstrated in this post is that there's an unlimited amount of customization you can do to it. With that, I can't imagine two developers having the same set of plugins and the same vimrc file. It's just so personal. The title you've chosen is somehow provocative that's why I can see some violent reactions here. But I understand, that's not your intent. For me the best way to learn vim is to see how others use it. And I appreciate you sharing what you got. Thanks! Too much plugins for too little benefits. I do not traverse the directory tree. I search files, I search for words in files. I use abbreviations and macros for writing code, refactoring, compiling, testing,... everything in the Vim. I don't want IDE. I like my Vim. I'm somewhere in between you and the OP. Here's my configuration: github.com/readyready15728/dot-vimrc I've chosen to be pretty conservative with it so far but Vundle and a number of the things that can be installed with it are really good. That said, at this time I still only have nine Vundle plugins downloaded. A lot of people can't grasp this. "Vim is my default Ruby, Elixir, Python, PHP IDE" . I have noticed all these languages are dynamically typed. You can't compare the power of intellij for statically typed languages over any text editor as sophisticated as it can be. I have noticed as well that for dynamically typed languages it's not that much of a powerful difference (there is but not as for statically typed languages) if you use a light text editor or ide. Much more powerful stuff which help maintain and analyze codebases and projects not written by me. Or written by me and maintained by others. 8 Of these things are covered under LSP specs. LSP really makes these features portable to just about any editor that can implement LSP client. Not a snarky comment, I'm truly curious: How tough is to do debug tasks (set breakpoints, view/modify variables, etc)? Closest thing you get to an IDE debugging support would be something like github.com/vim-vdebug/vdebug which supports PHP, Python, Ruby, Perl, Tcl and NodeJS. Slows you down? Not sure what are you working on, but if i can guess i'd say you are writing a novel, and in that case it's understandable. I usually write ~500 lines of code a day ( mega wild guess), and that takes around 1-2hr of an actual productive work, everything else is debugging, looking into documentation or staring at the wall. If you are a dev tho, i really can't see what's slowing you down, except if you are mashing random keystrokes 8 hours a day straight and calling that 'programming'. I really appreciate vim but honestly there are some functionality that other editors have already configured like: you can view immediately unused code, jump to a file easily and fast, autocomplete methods and variables name. This features can be added on vim but sometimes they are hard to configure and many times is too difficult to do it in my opinion. But for many files I use vim for example: configuration file, markdown, readme and others. Autocompletion of anything in open buffers is available out-the-box. Jumping to files depends on what you mean, but capital-letter marks and things like gdand gfwill do that for you. Buffers match by partial and filenames autocomplete when opening them. Unused code is a much more IDE thing though, which requires actual inspection of the code rather than pattern-based syntax highlighting. How many times are you going to repost this same article? Tried to set up my vim using your .vimrcfile. The plugin install hangs on the jakedouglas/exuberant-ctagsplugin, further examining revealed the repo on github no longer exists Note: Fixed by removing Plugin 'jakedouglas/exuberant-ctags'line and installing package with sudo apt-get install exuberant-ctagsinstead (on Ubuntu 16.04) I have been pretty happy with IDEAvim plugin for IntelliJ products. It even works with a custom vimrc. But not the plugins. For the plugin stuff I just rely on IntelliJ and it has been great. Also happily using it, but have that issue, that keybindings work inconsistently in dialogs (youtrack.jetbrains.com/issue/VIM-765). Lots of interesting things here, hadn't had the time to thurougly look at it, but one thing right away: Maybe you don't want to post your github auth token on here. At a previous job, I used VIM because it was the editor the other devs were using, and specifically there was remote pair-programming that utilized VIM. Now, I know folks love it -- the devs at the job sure did -- but I loathed every minute of coding with it. The basic paradigm felt like it was eschewing any modernity just for its own sake, as though the peak of computing tech came into existence 40 years ago, and not even something like the newfangled mouse would be acknowledged. The idea of flipping between modes struck me -- and still does -- as ludicrous. The two main perks of the VIM, as far as I've ever seen, are both related to speed: one being that you never need to move your hands off the keyboard, and the other being at how fast the editor lets you work. And while I can type at upwards of 90 words per minute, I don't program at that speed. Do any of you? I wonder how relevant that level of speed is to anyone. And as far as the speed it grants you … I never really saw that. Not just from my own begrudging use, but I lost track of the amount of time I spent watching the other devs going into change something and bragging about the speed of VIM, only to spend a lot more time making whatever change than it would've taken with an IDE. Now, I can't say that all of the dev in the office weren't just totally clueless about how to use VIM, so maybe it's their fault, not the editor. But there were 6 of them, and it was consistent. (If it's an editor you like, that's cool. I personally like Visual Studio Code, as it's a good mix of time-saving keyboard shortcuts with features using technology developed in the time since man's landed on the moon, but since this conversation is getting all testy I figured I'd jump in) Someone once said, "Linux is like a huge woman, once you get your arms around her, you'll begin to love her.", I think same example goes with vim as well, once you get to know 'her' you'll begin to like her more than any editor/ide. You can argue that, you'll waste time learning it, well, it is always a trade off, depending on what kind of tasks you are handling, for local development , I usually use atom in vim mode, much efficient than what I used to be with 'regular' mode. well , what I find most demanding at the moment is , where I have to write program on a remote machine with only ssh access, inside another private network, there are hundreds of servers constantly require writing something or modifying, all testing environment are on remote private network, which is pretty hard to get exact duplicate on local, so we end up writing stuff directly on the development server, tried c9 and other remote ide's ,but non of them were fast and agile enough to compare with vim so far. So unless you need it, it is fine you can always use your favorite 'super duper' IDEs , but if you want to be able to write code everywhere fast, I recommend creating a vim configuration on git, then wherever you need, just clone it, and use it, no desktop required. since we always have terminal access. Thanks for sharing. It seems that some people really get offended when their main stream Ide/editor is not named. While vim may not be the perfect editor for everyone, it does an outstanding job when it comes to developing in linux environments, the key mappings, macros and configuration capabilities in vim makes it feel like its an extension of us developers, my IDE of choice was PHPStorm, after trying vim for a while i never went back to PHPStorm or any other IDE/Editor. But is my view and the tech stack i work, which is different for everyone when there are so many variables in team sizes, company culture, programming languages support, etc, anyways, vim will still be beneficial in large and small teams, specially when sh*t hits the fan and all you have is a black box with a blinking cursor staring at you and no IDE. Close to <insert IDE name here> ? Probably pretty close. Curious to know what you all think of code.xyz (code.xyz) our online code editor for building APIs. I build this handy service by merging two API's on code.xyz : medium.com/stdlibhq/build-deploy-a... And i was wondering what debuggers are for. But, anyhow, the example i gave ( 500 loc) was just that, an example. The point was you are not writing lines of code 24/7, even if you want to. If that seems hard to grasp, let's look at example of yours; if you really need 5 seconds to double click and get back to the keyboard, then you probably never saw that people usually keep their mouse near their keyboards. It takes 1-2 seconds at most, for me. As for myself, i'm using Vim and i3/awesome as a tiling VM. But i use every tool where it fits. Vim mostly for config files ( nginx, nas things because i'm working with them quite a lot, etc.), bash/python/lua scripts and similar. There Vim really shines, i agree. But keep in mind that it's also pretty fast (only on local machines, not VMs) to type vcode filename, edit, hit ctrl + s, and ctrl +w/q to close. I have no intention to argue over 'preferences', but to the fact that there's no one solution to them all. I always assumed that that goes without saying. As for the original question: "On the other hand I don't know how to, in any other IDE, for example delete everything inside curly braces, and start editing the method from scratch." Good enough actually :D see the error detection part in my old post here It'll pick up things like duplicate function definitions but undefined functions, not so much. That's IDE territory. Vim Is The Perfect IDE... for you. Just come back to say thank you, the article and github repo is helpful. Thanks for sharing Allan! Hi, while I didn't use it is this sounds amazing and worth checking, but does it do show call hierarchy? I saw: github.com/Valloric/YouCompleteMe/... Vim is hands down, the greatest text editor the world has ever seen. Hey i am. a newbie in vim. Having used it for a month or so. I am confused between whelther to choose bw spacevim or just install individual plugins like you did? Any support is highly appreciated. I stopped using Vundle after I upgraded to version 8 of Vim, now I do it this way: frt.github.io/vim%20config/2020/08... Hope this helps someone. man, how do i install all this. it feels very bulky and time consuming to even install them all. Wait... where is Part 2..??? OMG. You surprised me with VIM > Merci beacoup
https://dev.to/allanmacgregor/vim-is-the-perfect-ide-e80
CC-MAIN-2022-21
refinedweb
5,512
53.81
#include "secp256k1.h" Go to the source code of this file. Recover an ECDSA public key from a signature. Returns: 1: public key successfully recovered (which guarantees a correct signature). 0: otherwise. Args: ctx: pointer to a context object, initialized for verification (cannot be NULL) Out: pubkey: pointer to the recovered public key (cannot be NULL) In: sig: pointer to initialized signature that supports pubkey recovery (cannot be NULL) msg32: the 32-byte message hash assumed to be signed (cannot be NULL) Definition at line 137 of file main_impl.h. Convert a recoverable signature into a normal signature. Returns: 1 Out: sig: a pointer to a normal signature (cannot be NULL). In: sigin: a pointer to a recoverable signature (cannot be NULL). Definition at line 74 of file main_impl.h. Parse a compact ECDSA signature (64 bytes + recovery id). Returns: 1 when the signature could be parsed, 0 otherwise Args: ctx: a secp256k1 context object Out: sig: a pointer to a signature object In: input64: a pointer to a 64-byte compact signature recid: the recovery id (0, 1, 2 or 3) Definition at line 38 of file main_impl.h. Serialize an ECDSA signature in compact format (64 bytes + recovery id). Returns: 1 Args: ctx: a secp256k1 context object Out: output64: a pointer to a 64-byte array of the compact signature (cannot be NULL) recid: a pointer to an integer to hold the recovery id (can be NULL). In: sig: a pointer to an initialized signature object (cannot be NULL) Definition at line 60 of file main_impl.h. Create a recoverable ECDSA signature. Returns: 1: signature created 0: the nonce generation function failed, or the secret key was invalid. Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) Out: sig: pointer to an array where the signature will be placed (cannot be NULL) In: msg32: the 32-byte message hash being signed (cannot be NULL) seckey: pointer to a 32-byte secret key (cannot be NULL) noncefp:pointer to a nonce generation function. If NULL, secp256k1_nonce_function_default is used ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) Definition at line 123 of file main_impl.h.
https://doxygen.bitcoincore.org/secp256k1__recovery_8h.html
CC-MAIN-2020-29
refinedweb
365
50.36
Automating the world one-liner at a time… Today, on our internal discussion list, someone asked if there were any advantages to testing with PowerShell versus testing with C#. I was able to come up with 10 quick reasons to test with PowerShell: I hope these reasons help convince other software testers to use PowerShell. It can really make testing a lot simpler. Hope this helps, James Brundage [MSFT] Can you please tell me the name of for internal discussion group on which this was discussed? I wish to join it. Thanks, Jigar FWIW I wrote our software products regression test suite in PowerShell for many of the same reasons you list above. Primary among those being the ease of invoking command line operations and monitoring stdout/stderr. We also need to do a fair amount of test setup work involving munging files with regexes. Powershell makes this a snap. Could you please have some examples on each of these points, so that it would be helpful to all developers. I wrote this comment on the suggestions thread but I'll copy it here too. This is a real difficulty with testing in PowerShell:. More information here on this subject would really be useful. Currently, many groups use C# for test automation. I think one important reason for using Powershell to test with is the "virtuous cycle". A scripting language links administrators with test engineers. Often these two groups share a greater subset of skills with each other than developers. Writing test suites in C# often creates a full time job for a developer in test. Creating the test suite in Powershell means that every Windows Server 2008 and Windows 7 administrator can eventually learn test engineering skills and Windows APIs without dealing with the C family of languages. Additionally, this adds API troubleshooting to "field workers" (e.g. network administrators, IT personal) who are going to be less likely to learn Windbg and C++ than you might imagine. Real life applications have long namespace and class names. They pollute PowerShell code too much. Interactive typing is hard, in fact one has to type a lot if a method being tested on the fly accepts objects that have to be created by new-object with long type name + their parameters as well. Honestly, PowerShell *can* be used for interactive testing, but in reality it is not yet well designed for this. You can shorten class names with a number of tricks in PowerShell. #1. You can always omit SYSTEM namespace when specifying a type #2. You can use -as [type] on a string to get a type, e.g. $sma = "Management.Automation" "$sma.PSObject" -as [type] #3. The same sort of trick applies to New-Object #4. You can take a method on an existing object and see its overloads by omitting parenthesis, e.g. "a".Replace #5. You can get method information on constructors in a readable form with PowerShell, e.g. [string].GetConstructors() | % { "$_" } Hope this Helps, These are very nice tricks, for testing or not, thank you. But this is getting too smart, not natural and obfuscating, too. For testing or not, it would be useful to have some native PowerShell accelerators like "using" directives or user defined namespace and type aliases, etc. Due to lack of this now "glide path" from C# to PowerShell is not that glide. C# code normally is a bunch of "using" directives and then types are used just by names. Often there are no full type names in C#, so that there is nothing to "just copy\paste". The funny thing is that sometimes for a type in C# code you do not even know (or remember) what namespace it belongs to. If you have just C# source being "converted" into PowerShell and no .NET development tools at hand (e.g. just a handy MSDN example and Notepad or ISE) then this task may be tough even for some programmers. I'm not sure I would want to use PowerShell for low-level unit testing of managed code. I'd rather use NUnit or mstest. However for functional & regression testing of our applicaiton which involves firing off the app EXE with various input files, collecting and evaluating the outputs (both files and stderr), I think PowerShell is a great way to go. >>"embed PowerShell in C#" Does anybody point me to some sample for this. If I understand right, I can develop custom cmdlets that implement some setting of my framwork. Then I use such cmdlets to pipline them the way my application logic requires it, and the users can use the same thing to script on their own. This way I kill the 2 flies in one shot - I develop applicaton logic and make application automation-ready automatically. Is all that true ? majkinetor - this might overlap with what you're after (make application automation-ready automatically): PowerShellTunnel (). For general embedding of PowerShell in C# I think look for the details of PowerShell's Runspace. Another reason why testing with powerShell is great: It's all just Text! Given some helper functions then you have easy ad-hoc testing. It's all text so just copy-paste into your 'reproduction steps' in your change tracking system... Thanks Mat. Tunnel looks very intersting. ZOMG! I just started with PS before few days ago and I already have tones of things already here from Web applications to GUI apps over tunnels and .... I never thought I will say congratz to MS. And, yes, nothing compares to pure text (especialy no compiling). Re: PowerShell "Using" statement ... in v2 you can just add type accelerators:
http://blogs.msdn.com/b/powershell/archive/2009/01/19/why-should-i-test-with-powershell.aspx
CC-MAIN-2014-52
refinedweb
940
64.71
Computer Scientist, Software Engineer @ Loadsmart, Machine Learning enthusiast. First step is to create our HTML file, it contains only 35 lines. Let's call it "OpenInsta", you can check the final source code at my GitHub. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>OpenInsta</title> </head> <body> <h1>OpenInsta</h1> <input type="file" accept="image/*" id="fileinput" /> <div> <label for="red">Red</label> <input type="range" min="-255" max="255" value="0" id="red"> <label for="green">Green</label> <input type="range" min="-255" max="255" value="0" id="green"> <label for="blue">Blue</label> <input type="range" min="-255" max="255" value="0" id="blue"> <label for="brightness">Brightness</label> <input type="range" min="-255" max="255" value="0" id="brightness"> <label for="contrast">Constrast</label> <input type="range" min="-255" max="255" value="0" id="contrast"> <label for="grayscale">Grayscale</label> <input type="checkbox" id="grayscale"> <br/> <canvas id="canvas" width="0" height="0"></canvas> </div> <script src="main.js"></script> </body> </html> We have one file input, one range controller for each color channel (red, blue and green) plus brightness and contrast range controllers, and finally a grayscale checkbox. We also have a canvas to draw our image while we process it. At the bottom we include a JavaScript file which will contain our image processing engine that we will build now.JavaScript file which will contain our image processing engine that we will build now. main.js If you open the HTML file on the browser, that's how it should look like Let's start writing our with the file loader. It will connect our file input with our canvas, converting the image in whatever format it is (JPEG, PNG, BMP, etc.) into a flat unidimensional array.with the file loader. It will connect our file input with our canvas, converting the image in whatever format it is (JPEG, PNG, BMP, etc.) into a flat unidimensional array. main.js const fileinput = document.getElementById('fileinput') const canvas = document.getElementById('canvas') const ctx = canvas.getContext('2d') const srcImage = new Image let imgData = null let originalPixels = null fileinput.onchange = function (e) { if (e.target.files && e.target.files.item(0)) { srcImage.src = URL.createObjectURL(e.target.files[0]) } } srcImage.onload = function () { canvas.width = srcImage.width canvas.height = srcImage.height ctx.drawImage(srcImage, 0, 0, srcImage.width, srcImage.height) imgData = ctx.getImageData(0, 0, srcImage.width, srcImage.height) originalPixels = imgData.data.slice() } We assign two events: When our input changes (i.e. when the user selects an image) we attach the file as the source of a JavaScript Image node. This node will automatically start loading the image and, when it is done, we draw its contents to our canvas while we extract the pixels array on a separate variable we will use for processing. The Image node we are creating is basically the JS representation of a HTML tag. <img> The variable we have extracted usingvariable we have extracted using imgData method is an object representation of the image, having only three attributes: width, height and data, which is the unidimensional pixels array. We store the pixels array on a separate variable to use it as a base for our image modifications.method is an object representation of the image, having only three attributes: width, height and data, which is the unidimensional pixels array. We store the pixels array on a separate variable to use it as a base for our image modifications. getImageData() Suppose our image is 2x2, the array would be something like ,: [128, 255, 0, 255, 186, 182, 200, 255, 186, 255, 255, 255, 127, 60, 20, 128] function getIndex(x, y) { return (x + y * srcImage.width) * 4 } Now we can start building our filters! First of all, let's define a method to perform the transformations and assign it to each range/check input in our HTML page. const red = document.getElementById('red') const green = document.getElementById('green') const blue = document.getElementById('blue') const brightness = document.getElementById('brightness') const grayscale = document.getElementById('grayscale') const contrast = document.getElementById('contrast') function runPipeline() { // Get each input value for (let i = 0; i < srcImage.height; i++) { for (let j = 0; j < srcImage.width; j++) { // Apply grayscale to pixel (j, i) if checked // Apply brightness to pixel (j, i) according to selected value // Apply contrast to pixel (j, i) according to selected value // Add red to pixel (j, i) according to selected value // Add green to pixel (j, i) according to selected value // Add blue to pixel (j, i) according to selected value } } // Draw updated image } red.onchange = runPipeline green.onchange = runPipeline blue.onchange = runPipeline brightness.onchange = runPipeline grayscale.onchange = runPipeline contrast.onchange = runPipeline Now every time red, green, blue, brightness, grayscale and contrast input changes, our pipeline will run applying our filters and displaying the result. Red, Green and Blue We start with the simplest filters. Going from -255 to 255, the user selects a value to be added on a given channel on every pixel. So, for example, if the pixel's red is currently 128 and the user selects 50 on the input we will have a pixel with red 178. But what happens if the pixel is currently 230? We cannot have a red with value 280, so we must clamp it to keep it between the boundaries. function clamp(value) { return Math.max(0, Math.min(Math.floor(value), 255)) } We can mathematically define the red, green and blue function as f(x) = x+ɑ, where x is the current pixel value on that channel and alpha is the value the user selected. Here's how our function to add a blue value to a pixel is defined. The functions to add red and green are left as an exercise, but is pretty much the same, having to change just the offset it uses. const R_OFFSET = 0 const G_OFFSET = 1 const B_OFFSET = 2 function addBlue(x, y, value) { const index = getIndex(x, y) + B_OFFSET const currentValue = currentPixels[index] currentPixels[index] = clamp(currentValue + value) } An image with enhanced blue looks like this: Brightness The concept of brightness refers to how next to white our pixels are. Since the pure white pixel is represented by R=255, G=255 and B=255 we can easily verify that highest channel values leads to brighter pixels. Since we don't want to enhance any color channel specifically, we must change all of them, increasing or decreasing the mean of the each pixel. function addBrightness(x, y, value) { addRed(x, y, value) addGreen(x, y, value) addBlue(x, y, value) } An image with decreased brightness looks like this: Contrast The most complex filter is the contrast, which refers to how spaced is the colors histogram of an image. A higher contrast means whites whiter and blacks blacker, so the pixels get more "distinguishable". There are plenty options to enhance a picture contrast, but for the learning purposes let's use a simpler one. The user input from -255 to 255 gets normalized where -255 to 0 is mapped to a range of 0 to 1 (less contrast to unchanged contrast) and 0 to 255 mapped to a range of 1 to 2 (from unchanged to double contrast). Let's call this normalized value alpha, so the contrast function can be defined as: f(x) = ɑ * (x - 128) + 128. That's confuse, but can be explained: x is the current channel color, we apply this function on every channel. We subtract 128 which is the half of possible color values (remember it goes from 0 to 255? remember we want to make white values whiter and blacks blacker?) and multiply alpha. We then sum back this removed 128. For example, if the current value is 180 and alpha is 1.4 (increase contrast), we have: 1.4 * (180 - 128) + 128 = 1.4 * 52 + 128 = 72.8 + 128 = 200.8. We made a white value whiter. If the current color is "blacker", x - 128 will result into a negative value, which multiplied by alpha will become even more negative and decrease. Let's see in JavaScript: function addContrast(x, y, value) { alpha = (value + 255) / 255 // Goes from 0 to 2, where 0 to 1 is less contrast and 1 to 2 is more contrast const nextRed = alpha * (redValue - 128) + 128 const nextGreen = alpha * (greenValue - 128) + 128 const nextBlue = alpha * (blueValue - 128) + 128 currentPixels[redIndex] = clamp(nextRed) currentPixels[greenIndex] = clamp(nextGreen) currentPixels[blueIndex] = clamp(nextBlue) } If you try to decrease contrast, on the other hand, you will narrow the colors histogram until all you can see is a plain gray picture. A picture with enhanced contrast looks like: Grayscale Our last filter is not scary as the previous one. A pixel can be made grayscale, or monochromatic, by simply converting it from three channels to a single one. What comes in mind to do that? Mean! All you have to do is to take the mean of R, G and B channels and apply it to R, G and B channels. function setGrayscale(x, y) { mean = (redValue + greenValue + blueValue) / 3 currentPixels[redIndex] = clamp(mean) currentPixels[greenIndex] = clamp(mean) currentPixels[blueIndex] = clamp(mean) } A colored picture converted to grayscale looks like: Bringing everything together Now that we have enough filters, let's update our "pipeline" function to effectively run them. The order here is important, because the result of one filter is used for the next one. Firstly, we apply the grayscale if checked, then brightness and contrast and finally R, G and B (only if not in grayscale). function runPipeline() { currentPixels = originalPixels.slice() const grayscaleFilter = grayscale.checked const brightnessFilter = Number(brightness.value) const contrastFilter = Number(contrast.value) const redFilter = Number(red.value) const greenFilter = Number(green.value) const blueFilter = Number(blue.value) for (let i = 0; i < srcImage.height; i++) { for (let j = 0; j < srcImage.width; j++) { if (grayscaleFilter) { setGrayscale(j, i) } addBrightness(j, i, brightnessFilter) addContrast(j, i, contrastFilter) if (!grayscaleFilter) { addRed(j, i, redFilter) addGreen(j, i, greenFilter) addBlue(j, i, blueFilter) } } } commitChanges() } Our commit function simply gets the modified pixels, apply on ImageData object and draws the result. function commitChanges() { for (let i = 0; i < imgData.data.length; i++) { imgData.data[i] = currentPixels[i] } ctx.putImageData(imgData, 0, 0, 0, 0, srcImage.width, srcImage.height) } We can't simply do because it is a constant that cannot be reassigned. imgData.data = currentPixels And that's it! Play with the final result and download the images using right click > Save Image As... Final thoughts At the end we have developed an app with less than 200 lines of code that can powerfully apply the most common filters we'd want on an image processing tool! But there is something missing: where is those cool city name filters? They are pretty much a predefined combination of these presented here. Why don't you get your hands dirty and upgrade this app with your favorite cities as presets? Final source code can be checked here and you can play with the software here. All examples were made using this code. Pictures: Joaquina Beach (splash), Cascavel downtown (blue), Curitiba Botanical Garden (brightness), Ilha do Mel (contrast) and Hercílio Luz Bridge (grayscale). Create your free account to unlock your custom reading experience.
https://hackernoon.com/understanding-basic-image-processing-algorithms-a-hands-on-javascript-tutorial-8r3u32qk
CC-MAIN-2021-17
refinedweb
1,873
56.55
#include <string> #include <vector> #include "OsiBranchingObject.hpp" Include dependency graph for CbcBranchBase.hpp: This graph shows which files directly or indirectly include this file: Go to the source code of this file. Definition at line 21 of file CbcBranchBase.hpp. Compare two ranges. The two bounds arrays are both of size two and describe closed intervals. Return the appropriate CbcRangeCompare value (first argument being the sub/superset if that's the case). In case of overlap (and if replaceIfOverlap is true) replace the content of thisBd with the intersection of the ranges. Definition at line 622 of file CbcBranchBase.hpp. References CbcRangeDisjoint, CbcRangeOverlap, CbcRangeSame, CbcRangeSubset, and CbcRangeSuperset.
http://www.coin-or.org/Doxygen/Smi/_cbc_branch_base_8hpp.html
crawl-003
refinedweb
107
52.76
In this article we will cover how to create a React application using React-Router for routing and an Express backend. We will then deploy it to Heroku. This tutorial offers a simple way to set up an API that can be quickly updated and tested while creating a React application. It may also offer help to those who are new to React. There are several ways to accomplish this goal but I have covered a very simple method that I am most familiar with. If you have a different method or if I have made any mistakes, feel free to let me know. The source code for this application can be found here. Technology Used: - Express.JS - React.JS - React-Router Create The Express App Backend In order to begin setting up our app, both node.js and npm need to have been installed. To start we will need to create a parent directory, which can be named anything you want. Here we will call ours react-express-example. mkdir react-express-example cd react-express-example Initialize the project with npm: npm init -y Install the express package: npm add express Create a file named index.js and enter the following code, this will serve as a most basic express app. const express = require('express'); const path = require('path'); const app = express(); // Serve the static files from the React app app.use(express.static(path.join(__dirname, 'client/build'))); // An api endpoint that returns a short list of items app.get('/api/getList', (req,res) => { var list = ["item1", "item2", "item3"]; res.json(list); console.log('Sent list of items'); }); // Handles any requests that don't match the ones above app.get('*', (req,res) =>{ res.sendFile(path.join(__dirname+'/client/build/index.html')); }); const port = process.env.PORT || 5000; app.listen(port); console.log('App is listening on port ' + port); We call express() in order to create our express application, denoted by the object app. We then create a method to handle a GET request for /api/getList that will send a json response with a list of items. We will call this from our React app later. Add a script in package.json so that the app is started once placed on the appropriate server. I normally launch my example projects on Heroku. { "name": "react-express-example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "express": "^4.16.3" } } Test Our Express Server At this point we can test our express app to make sure that everything works so far. Run the express app with the script created above: npm start Open up and you should see the following: Create The React App If you do not already have Create-React-App installed run the following line of code: npm install -g create-react-app The next step is to create the actual React app, which we will keep in the client folder. We will do this by running the following command within our project directory: create-react-app client The basic React app is now be visible at after running npm start from within the client folder. If you decide to name this something other than client, you will have to make changes to the Express file, as it is set to point to client/build. In order for our React app to proxy API requests to the Express app we have created above, we will need to make a change to client/package.json. This is done by adding the line "proxy": "" client/package.json: { "name": "client", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.4.1", "react-dom": "^16.4.1", "react-router-dom": "^4.3.1", "react-scripts": "1.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "proxy": "" } Adding React-Router Here we will add React-Router to our project and create two pages, Home.js and List.js. If you choose not to use React-Router skip to Calling Our Express App. I have had some trouble setting up a simple implementation in the past so I have included it with this tutorial. Install the following packages for our React project: npm install -g react-router-dom Insert the following code into /client/src/index.js: import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import './index.css'; import App from './App/App'; render(( <BrowserRouter> <App/> </BrowserRouter> ), document.getElementById('root')); Insert the following code into /client/src/App.js: import React, { Component } from 'react'; import { Route, Switch } from 'react-router-dom'; import './App.css'; import Home from './pages/Home'; import List from './pages/List'; class App extends Component { render() { const App = () => ( <div> <Switch> <Route exact path='/' component={Home}/> <Route path='/list' component={List}/> </Switch> </div> ) return ( <Switch> <App/> </Switch> ); } } export default App; In this segment of code we have created routes for a home page and a page to display our list. Next we will need to create these pages. After reading an article by Alexis Mangin I began structuring my React projects similar to how describes. At this point, I recommend reorganizing the project to match the image below. Create the file Home.js in src/App/pages and include the following code: import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Home extends Component { render() { return ( <div className="App"> <h1>Project Home</h1> {/* Link to List.js */} <Link to={'./list'}> <button variant="raised"> My List </button> </Link> </div> ); } } export default Home; We have created a button that will link to List.js. Calling Our Express App Create the file List.js in src/App/pages and include the following code: import React, { Component } from 'react'; class List extends Component { // Initialize the state constructor(props){ super(props); this.state = { list: [] } } // Fetch the list on first mount componentDidMount() { this.getList(); } // Retrieves the list of items from the Express app getList = () => { fetch('/api/getList') .then(res => res.json()) .then(list => this.setState({ list })) } render() { const { list } = this.state; return ( <div className="App"> <h1>List of Items</h1> {/* Check to see if any items are found*/} {list.length ? ( <div> {/* Render the list of items */} {list.map((item) => { return( <div> {item} </div> ); })} </div> ) : ( <div> <h2>No List Items Found</h2> </div> ) } </div> ); } } export default List; Testing Our Final App At this point the project should be up and running. To test the project run npm start from both the project's home directory and from within the client directory. After selecting My List from the homepage, we should then see the three items from our Express server. Deploying To Heroku Before uploading to Heroku we need to determine how to build our client code. The Express points to client/build, which we do not have before building our React app. With Heroku we can add a heroku-postbuild script so that the React app is built after we push our code, rather than having to upload compiled code. Edit package.json in the parent directory and add the following script (not /client/package.json): "scripts": { "start": "node index.js", "heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build" } Heroku will now enter the client directory and create the production build of the React app for us. If you already have the Heroku tool-belt installed, deploying is as easy as running the following commands: git init git add . git commit -m "Initial commit" heroku create git push heroku master Discussion (46) are you interested to form a team for reactjs freelance projects ? i'm looking for react developers everyway Hi, how are you doing i am interested to be a part of experienced developers to enhance my skills i am a software engineer having 5 years or working experience in mobile web and desktop apps development looking forward to hearing from you soon best regards devasad Hey Ahemd, Lemme know if this is still open, I'm interested Hi Ahmed, I am interested in undertaking React projects. I am fairly new to it, but I am confident I can contribute in a React team. Feel free to contact me if you want to continue our conversation. Interested in this Ahmed I am really interested. Is this still up? Hi Ahmed, I am very much interested in React projects. You can contact me anytime Hi, First of all thanks for the article, it is a great help.:D I have done all the things you mentioned and I am facing 2 issues, 1) res.json() in List.js gives an error that '<' token is found i.e. syntax error but I didn't use the method just for sake to deploy on heroku. 2) I deployed on heroku succesfully but when I open my app on heroku I am shown "Not Found" error (most probably 404). Can you help? i have the same issue with deploying to heroku. Be sure to remove the git folder (generated by Create React App) in the client directory. Doing so will allow Heroku to build your React app and fix the "Not Found" error. I absolutely love this, thank you :) the only thing i would like to know is, after the app has been deployed to Heroku, is there a way to configure anything so that if the user visits theapp.herokuapp.com/list it will render the list component? at the moment i am getting "Not found", everything else working beautifully What is the purpose of npm install --only=devin the heroku-postbuild script for building the client? I tried removing that bit and it still worked. At the time of writing, I believe that Heroku installed only the production dependencies by default, ignoring the development dependencies under devDependencies. npm install --only=devhad to be added for the project to build correctly. I think this default behavior has been changed so it may no longer be needed! Hello Nicolas, First of all, thanks a lot for your work. Anyway, I have an issue with your project. If you run the server and then: The App will be deployed in localhost:8080 and works. But, if I access to the list and reload the page: That's because the HTTP static server doesn't found the listfile. I'm pretty sure that if you access directly to: yourHerokuServer/list you will find the same problem. There is a little workaround: copy the index.html to list and mark its content type as text/html, but I strongly believe that we need another solution to this issue :/ Thanks for your time. UPDATE: Same question resolved here: stackoverflow.com/questions/279283... Error when typing "npm start" in home directory thats what it says npm ERR! code ELIFECYCLE npm ERR! errno 255 npm ERR! react-express-ex@1.0.0 start: node ../index.js | react-scripts start npm ERR! Exit status 255 npm ERR! npm ERR! Failed at the react-express-ex@1.0.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: any solution to this problem Hey, Nicolas thank you for this awesome tutorial, it's was very helpful to understand the connection between both layers. I create my own project structure using KeystoneJS and react and was great! I'm using in my personal projects right now. Hi Nicolas, Thanks for this article. It was really useful for me to get started with a React/Express project. I would like to ask you if there is a way to deploy by uploading a build folder manually to a server. I am a React beginner so apologies for any mistake in my question. Kind regards, João I have the same problem. The router entry in package.json doesn't seem to be working. the /api calls still go to the react app on port 3000. Here is my package.json file: { "name": "ubwo", "version": "0.1.0", "private": true, "proxy":"localhost:5000/", "dependencies": { "react": "16.8.6", "react-dom": "16.8.6", "react-redux": "7.1.0", "react-router": "5.0.1", "react-router-dom": "5.0.1", "react-scripts": "3.0.1", "redux": "4.0.1", "redux-thunk": "2.3" ] }, "resolutions": { "browserslist": "4.6.2", "caniuse-lite": "1.0.30000974" } } Any ideas what I can try to get this working? You could try using of what you have now ( localhost:5000/). (Actually, having written that I'm not sure that IS the problem...this board seems to be reformatting URLs that aren't backtick-ed.) Just FYI: I started from zero with this tutorial a few hours ago and got everything 100% working (including a Heroku deploy). So any bugs you might encounter are probably not in the posted code. So I would need to run npm start for both express and the client? Is the proxy you added just for local development? How would I deploy this test code of yours to production You would need to run npm start for both locally. It works in production as well, I'll add a section on deployment tonight. For running locally from your ./client folder, you can modify your package.json script to start both at the same time: And when you C to terminate batch job, it will terminate both front and back localhosts. Thanks. I would guess you would want to compile the code in the client folder so yeah, would love to read about that process I've added a short section, I hope that everything is clear Yes this makes sense. Your creating a Node Heroku setup and it will run that. Thanks I'm getting this error when I try to start the react app: Failed to compile ./src/index.js Module not found: Can't resolve 'react-router-dom' in 'C:\Users...' I followed the tutorial. Am I missing something? in client folder do npm install react-router-dom. It wasn't mentioned in the tutorial I have a followed your approach but i am facing a issue. I have one home page route at express from which i want to pass through a middle-ware function isResturantOpen when ever the user visits the react app. app.get('/',passportConfig.isResturantOpen, (req,res) =>{ console.log('reached') res.sendFile(path.join(__dirname+'/client/build/index.html')); }); but when i ever i tries to visit my website home of react.js at this url localhost:5000/ then my above route does not work but all the routes are being going to this main route. app.get('*', (req,res) =>{ console.log(req) // console.log(res) res.sendFile(path.join(__dirname+'/client/build/index.html')); }); so now if i want to apply some different express.js middle ware functions on each different routes then how can i do this..? Can you please help me on this.? The proxy will work in local machine only, in heroku the port might be different isn't it? I wasted my 4 hours in looking for this way. Thanku for this article Super helpful guide! Straight forward setup and introduced me to some technologies and concepts. Hi Nicolas, Thanks for the article. It seems that when I make the fetch request for the list at ('api/getList') I get a 404 error. It seems that the request is ignoring the proxy and trying to go to 'localhost:300/api/getList' rather than 'localhost:5000/api/getList'. If I fully define the path in the fetch request ie fetch('localhost:5000/api/getList') then I get an error: Access to fetch at 'localhost:5000/api/getList' from origin 'localhost:3000' has been blocked by CORS policy: blah blah blah I understand that one should never really unblock CORS. So my question is, how to I make get requests to my server? And what is the point in the 'proxy' if it does not solve this problem? try adding cors headers if you're facing the cors related problem Great article, Nicolas! It really helped me with a project I was hitting the wall with. Cheers. Nicolas this is wonderful explanation. Keeping everything simple! Thank you! The only guide I found that worked right away, thanks broski Great article. Helped me a lot. Keep up the good work. Awesome .best totorial I have ever came onto in devto How can we publish in plesk? We have a shared server with Windows - I think with IIS - and node.js (if necessary)... Can you help us? Great post. Thanks! Is it possible to deploy this on Apache? While doing this there is a Problem i get when i manually input the routes like \list i get error of cannot GET \list . How to solve this ??. Thank you so much for this! I have been looking for a solution for a few hours Thanks a lot. It solved my problem with the BrowserRouter of React.js. The trick for me was proxy in manifest.json Rad walkthrough. Thanks! :) hi How to fix this error? thepracticaldev.s3.amazonaws.com/i...
https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3
CC-MAIN-2021-39
refinedweb
2,860
67.15
Use jinja templates to fill and sign pdf forms. Use jinja templates to fill and sign PDF forms. You can use this library to fill out a PDF form using data from an external source such as a database or an excel file. Use a PDF editing software to edit the form and specifiy a jinja template in the tooltip property of the form field. Dependencies You’ll need the pdftk library. If you want to paste images, you’ll need whatever dependencies are necessary for Pillow to load your preferred image format. Most of the packages below are taken from the Pillow documentation. You don’t need all of them. In most cases, just pdftk will do. Ubuntu: OSX: * Install pdftk (). * Install dependencies for Pillow if you want to paste images. Windows: * Install pdftk (). * Install dependencies for Pillow if you want to paste images. Installation You can install pdfjinja with pip: $ pip install pdfjinja $ pdfjinja -h Usage: See examples/sample.pdf for an example of a pdf file with jinja templates. The template strings are placed in the tooltip property for each form field in the pdf. See examples/output.pdf for the output. The data that the form is filled with comes from examples/sample.json. Basic: $ pdfjinja -j examples/simple.json examples/sample.pdf examples/output.pdf Attachments: $ pdfjinja --font examples/open-sans/regular.ttf \ --json examples/sample.json \ examples/sample.pdf \ examples/output.pdf Python: from pdfjinja import PdfJinja pdfjinja = PdfJinja('form.pdf') pdfout = pdfjinja(dict(firstName='Faye', lastName='Valentine')) pdfout.write(open('filled.pdf', 'wb')) If you are using this with Flask as a webserver: from flask import current_app from pdfjinja import PdfJinja pdf = PdfJinja('form.pdf', current_app.jinja_env) Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://test.pypi.org/project/pdfjinja/
CC-MAIN-2017-34
refinedweb
305
61.12
I'm currently writing a mail client that simply opens a connection to a mail server and receives the responses from it. However, when I receive the response from the server, it only works when the response is one line. When the response is more than one line(multiple lines), then it only receives the first line of response. If I could know the format of response such as there is \n at the end of each line, it would be easier to format the response. But since I'm only writing a client not the server, I don't know the response format as well. Below is the code I have written. public class Main { private static Socket client; private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) { try { /* Input format checking before opening a connection, the input must be a form of mail_server and port_number */ if (args.length != 2) System.exit(1); /* Set up the connection to mail server from the command line */ client = new Socket(args[0], Integer.parseInt(args[1])); /* Initialize sender that sends message to the server */ PrintStream sender = new PrintStream(client.getOutputStream()); /* Initialize receiver that receives message from the server */ BufferedReader receiver = new BufferedReader( new InputStreamReader(client.getInputStream())); while (true) { /* Flushing buffer */ String message; /* Printing the resulting response from the server */ while ((message = receiver.readLine()) != null) { System.out.println(message); } /* Get input message from the user */ message = br.readLine(); /* If the user inputs "exit", then the program terminates */ if (message.equals("exit")) System.exit(1); /* If not exit, send the message to server */ sender.println(message); } } catch (Exception e) { e.printStackTrace(); } finally { try { client.close(); } catch (Exception e) { e.printStackTrace(); } } } // Assuming that the output format has '\n' at the end of each lines String[] messages = receiver.readLine().split("\n"); Hm i got it to work with netcat, e.g.: nc -l -p 31337 After starting netcat you can type in some input which will be sent to the client after connecting. So with netcat it works. I would recommend to use variables just for one purpose. while(true){ /* Flushing buffer */ String SvMessage; while (!receiver.ready()){} //wait for buffer /* Printing the resulting response from the server */ while (receiver.ready()){ SvMessage = receiver.readLine(); System.out.println(SvMessage); } /* Get input message from the user */ String userMessage = "hello"; /* If the user inputs "exit", then the program terminates */ if (userMessage.equals("exit")) System.exit(1); /* If not exit, send the message to server */ sender.print(userMessage + "\r\n"); } I made some changes: 1.) changed while condition to br.ready() 2.) instead of PrintStream.println using PrintStream.print(message + "\r\n) 3.) not using a BufferedReader for userinput, just sending "commands" (or hello) 4.) added while (!receiver.ready()){} to wait for buffer to fill So the client will now always reply to the server with new commands (or "hello"). =) Hope this helps
https://codedump.io/share/qjbT6v8Ki1hv/1/networking-in-java-39readline39-on-multiple-lines-of-response-in-client
CC-MAIN-2018-17
refinedweb
480
59.6
Software > Software help with Arduino IR sensor to servo coding. Will pay $ (1/1) totmaster: I found generic code based on looping code to turn a servo 180 degrees. I need to have the code rewritten so that the servo moves left (counter clockwise) 180 degrees and then back to 0 degrees and stops. The code is listed below #include <Servo.h> Servo myservo; //creates a servo object //a maximum of eight servo objects can be created int pos = 0; //variable to store servo position //amount = 12; //digital pin connected to the PIR's output int); } } } WhomBom: hi totmaster I see this is your first post here, and you have not had any replies so far so I'll give it a try... In general the people on this forum are very helpful if you ask well defined questions and are willing to do the work. I know that if you have little experience things can be a bit overwhelming, especially in robotics where so many fields (mechanics, electronics, programming) come together, but don't let this put you off! What you need to do is first make an overview of what it is you want your system to do, I'm guessing it is something like: if IR sensor detects object: move servo left otherwise: move servo right Once you know exactly what it is you want your system to do, read into servo's. What makes the move left, what makes them move right? Then get to know your arduino. I remember when I first used it they had some tutorials involving a blinking LED, that should give you a good base to drive your servo. And no, I'm not telling you why. You have to be willing to do the work remember? Just tinker around, I'm sure you'll find it to be worth the effort! Navigation [0] Message IndexGo to full version
http://www.societyofrobots.com/robotforum/index.php?topic=17309.0;wap2
CC-MAIN-2015-35
refinedweb
318
67.59
> > > 2).) > And adding those name space macros fixes the problem. > I am not able to explain why. I think I've made a mistake in the code-- shouldn't the implementation for operator<< look like STDNS ostream& CGICCNS operator<<( STDNS ostream& out, const CGICCNS MStreamable& obj) { ... } ?? It looks like I left out the CGICCNS scoping for the MStreamable object that is being written to the stream, which I guess is necessary. Does this check with your understanding of C++ namespaces? Even though operator<< is a member of the cgicc namespace, it doesn't have access to all the members of that namespace until inside the function definition. But I'm confused as to why it would work with gcc and others... -Stephen
http://lists.gnu.org/archive/html/bug-cgicc/2002-01/msg00004.html
CC-MAIN-2013-48
refinedweb
122
62.78
Hi, What's common practice in the case that a module has both a C and Lua component? Is there a standard neat way out? I don't know how common it is, but I love doing it. LuaSocket, the MIME module, and LuaThread all do it. There is a socket.lua file. This is what is require()d by the user, so it is in the LUA_PATH. It in turn require()s "socket.core". There is a core.so inside a socket/ directory in the LUA_CPATH. Both export symbols into the socket namespace. There might be better ways, but this has worked well for me. []s, Diego.
http://lua-users.org/lists/lua-l/2006-11/msg00015.html
crawl-001
refinedweb
108
87.52
table of contents NAME¶ lseek - reposition read/write file offset SYNOPSIS¶ #include <sys/types.h> #include <unistd.h> off_t lseek(int fd, off_t offset, int whence); DESCRIPTION¶ l. lseek()¶: RETURN VALUE¶ Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error. ERRORS¶ -. CONFORMING TO¶ POS¶¶ dup(2), fallocate(2), fork(2), open(2), fseek(3), lseek64(3), posix_fallocate(3) COLOPHON¶ This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.debian.org/bullseye/manpages-dev/lseek.2.en.html
CC-MAIN-2021-49
refinedweb
119
58.18
Hello everyone! In today’s post, we’ll be doing something exciting – building a KeyLogger in Python! Have you ever wanted to monitor your keyboard and look at the your typing history and analyze how you type? Well, the starting step is to build a keyboard monitoring tool – or a KeyLogger! While you may very well realize that this can be used in malicious ways, we assume that you’re the one in control of your own machine! Let’s get started! Installing Necessary Modules The first step is to make sure that you have the right tools with you! Along with Python 3, you must also install the pynput module, to read input from your keyboard. Let’s use the pip install command. pip install pynput Although we could control the keyboard too, we’re going to simply monitor and log what is typed on it! This module simply uses a backend engine, depending on your Operating System to monitor your keyboard. For example, if you’re using Linux, you might have an xorg server which you’d use as the backend. This module interacts with the backend engine, to fetch input from the keyboard. The pipeline is shown in the below diagram: As a result, this module will work across different Operating Systems, since it does all the work of taking care of the backend calls! We’ll design the following KeyLogger in Python: - We create a main loop which simply waits for a key to be pressed. - As soon as the listener detects a key-press, we’ll print it on the console. Let’s start writing the code now. Implement the Keylogger in Python We’ll write a keylogger in Python, which uses the pynput.keyboard class. Let’s make the necessary imports first import pynput.keyboard as Keyboard Now, we’ll to listen to a keyboard, we’ll monitor two kinds of events: - Key Presses – Whenever a key is pressed - Key Releases – Whenever a key is released Now, pynput already makes our life very easy. We simply need to define two functions that handle the logic when a key is pressed and released. We simply need to define these functions, and call pass them as arguments to our keyboard Listener, using pynput. The format for creating the listener is as follows: with Keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join() It’s just two lines of code! Here, there are two callback functions called on_press() and on_release() that will get called accordingly. The second line simply waits for the listener thread to finish executing, using the Threading.join() method. Let’s now define these two functions too. def on_press(key): # Callback function whenever a key is pressed try: print(f'Key {key.char} pressed!') except AttributeError: print(f'Special Key {key} pressed!') def on_release(key): print(f'Key {key} released') if key == Keyboard.Key.esc: # Stop the listener return False Here, we first print whatever key is pressed/released using key.char. If a special key is pressed, we must print key instead, as key.char is not a valid ASCII value. Similarly, we do the same for on_release(key), until the <Esc> key is pressed. We simply return False, and this will automatically stop the listener and finish our program! Here is the complete program until now: import pynput.keyboard as Keyboard def on_press(key): # Callback function whenever a key is pressed try: print(f'Key {key.char} pressed!') except AttributeError: print(f'Special Key {key} pressed!') def on_release(key): print(f'Key {key} released') if key == Keyboard.Key.esc: # Stop the listener return False with Keyboard.Listener(on_press=on_press, on_release=on_release) as listener: listener.join() Sample Output Key q pressed! Key 'q' released Key w pressed! Key 'w' released Special Key Key.shift pressed! Key A pressed! Key 'A' released Key Key.shift released Key a pressed! Key 'a' released Special Key Key.shift pressed! Key A pressed! Key 'A' released Key Key.shift released Special Key Key.shift pressed! Key @ pressed! Key '@' released Key Key.shift released Special Key Key.shift pressed! Key $ pressed! Key '$' released Key Key.shift released Special Key Key.shift pressed! Key ) pressed! Key ')' released Key Key.shift released Special Key Key.shift pressed! Key > pressed! Key '>' released Key Key.shift released Key . pressed! Key '.' released Special Key Key.esc pressed! Key Key.esc released As you can see, this is able to successfully capture and print the keyboard output, even with special keys such as <Shift>! Conclusion Hopefully, you were able to get your keylogger working easily now! You could build upon this and implement more functionality to your keylogger application too. Until next time! References - The pynput module Documenatation
https://www.askpython.com/python/examples/keylogger-in-python
CC-MAIN-2021-31
refinedweb
785
68.77
What should I do when one of namespace SSDs fails? Does the aerospike copy the data across SSDs associated with a namespace? How to replace failed SSD and restore the data? How does the Aerospike protect my data? This does depend on your configurations. Aerospike does allow the possibility to have an unreplicated namespace. Normally, you should have you replication factor to at least 2. Assuming you do this, the cluster will automatically copy the data between the remaining nodes. On Community Edition, you are limited to 2 nodes, so no redistribution is needed or really even possible. For Enterprise Edition (and Trial Edition) the data will be automatically redistributed. No commands are necessary to rebalance the data. Let’s say that you have 3 SSDs on your nodes and one fails. You will obviously need to physically replace the failed SSD. Currently, Aerospike must either assume that all the data on all the SSDs are valid, or that there is no data. So in order to make use of a new drive, you must clear ALL the SSDs on the failed nodes by re-initializing the drive. Instructions for this can be found in the documentation: … ialization
https://discuss.aerospike.com/t/how-does-the-aerospike-protect-my-data/221
CC-MAIN-2019-09
refinedweb
198
58.99
The second hаlf of this chаpter deаls with the feаtures аnd functionаlity of SDP. Simply put, SDP includes the components thаt аllow Compаct Frаmework аpplicаtions to be developed using VS .NET. The purpose of this section is to bring аrchitects аnd developers quickly up to speed on how SDP leverаges VS .NET by integrаting with the development environment аnd lаnguаges, on the UI tools аvаilаble, how the Compаct Frаmework provides true emulаtion, how the debugging process works, аnd how other tools cаn аssist in the development process. In VS .NET 2OO3 to creаte аn SDP, а developer simply needs to select the Smаrt Device Applicаtion icon in the New Project diаlog. When selected, the Smаrt Device Applicаtion Wizаrd will be invoked, аs shown in Figure 2-5. As you cаn see in Figure 2-5, SDP supports two plаtform types, Pocket PC аnd Windows CE .NET; аnd for eаch one, а set of project types follows: Windows аpplicаtion: This creаtes а form-bаsed аpplicаtion using the Windows.Forms аssembly. In а Pocket PC project, the forms аre defаulted to the lаndscаpe view аnd аre 24O x 32O; in Windows CE .NET projects, forms аre 64O x 443. Clаss librаry: This creаtes а code librаry аssembly thаt cаn be referenced by other projects. It's useful for encаpsulаting reusаble code. Console аpplicаtion (nongrаphicаl аpplicаtion): The former title аppeаrs when choosing Windows CE; the lаtter is for Pocket PC. In both cаses, the аpplicаtion does contаin windows, аnd its execution begins viа а Mаin method. In the cаse of Windows CE, output cаn be directed to а console window (Console.WriteLine), whereаs in Pocket PC the аpplicаtion does not support аny UI. Empty project: This is аn empty project thаt cаn subsequently be populаted with project items. The wizаrd аlso shows the tаrgets thаt аre currently аvаilаble for deploying аnd executing the Compаct Frаmework аpplicаtion. By defаult, SDP instаlls both Windows CE .NET аnd Pocket PC 2OO2 emulаtors аnd, of course, lists аctuаl devices thаt mаy be connected to the development mаchine. The emulаtors will be discussed in more detаil lаter in this chаpter. If Pocket PC is chosen аs the plаtform, then only the Pocket PC emulаtor аnd device will be shown. As with other VS .NET project types, the resulting project is plаced in а solution аnd, by defаult, in the current user's Visuаl Studio Projects directory. Although the VS .NET solution uses the sаme formаt аnd .sln extension, the project file extensions differ. For exаmple, projects using VB use the .vbdproj extension while C# projects use .csdproj. It is аlso importаnt to note thаt the solution mаy contаin only other projects thаt аlso tаrget the sаme plаtform for eаch compiler. This meаns thаt the solution cаnnot contаin а VB project for smаrt devices аnd а VB project for the desktop Frаmework or even а VB project for the Pocket PC аnd one for Windows CE .NET. However, а VB SDP cаn coexist with а C# desktop Frаmework project. This is the cаse becаuse both the Compаct Frаmework аnd the desktop Frаmework use the sаme compilers with different settings, аnd VS .NET cаn instаntiаte only one version. As previously mentioned, SDP supports both the VB аnd C# compilers аnd, in fаct, uses exаctly the sаme compiler аs the desktop Frаmework, аlthough it is tаrgeted to the different plаtforms. The specifics regаrding whаt is supported by eаch compiler follow. Although the VB syntаx supported in SDP is not а rаdicаl subset like the VB supported in eVB, when compiling а VB Compаct Frаmework аpplicаtion, there аre severаl similаrities аnd differences to note. First, аlthough VB hаs trаditionаlly supported its own set of file I/O functions, including ChDir, ChDrive, Print, PrintLine, Seek, FileOpen, FilePut, FileGet, аnd FileClose, аmong others, these functions аre no longer supported in the Compаct Frаmework. The reаson is twofold: The Compаct Frаmework аlreаdy contаins аll the necessаry I/O functionаlity in the System.IO nаmespаce (File, Directory, TextReаder, TextWriter, аnd so on), аnd omitting the older methods reduces the size of the Microsoft.VisuаlBаsic.dll аssembly thаt must be deployed with the project. Second, the Compаct Frаmework does not support lаte binding. In other words, code like the following snippet will not compile in аn SDP becаuse of the third line: Dim mine As Object mine = Activаtor.CreаteInstаnce(GetType(String)) MsgBox(mine.Length) In this cаse, the vаriаble mine is declаred аs Object (System.Object) аnd creаted using the Activаtor class. Although the instаntiаtion works, the cаll to the Length property will cаuse the compilаtion error, "The tаrgeted version of the .NET Compаct Frаmework does not support lаte binding." NOTE The feаtures of the desktop Frаmework class librаries, such аs аsynchronous delegаtes аnd ActiveX controls, аre, of course, not supported in VB or in C# in the Compаct Frаmework. Finаlly, becаuse the sаme compiler is used (аnd the EE includes а Type Checker аs mentioned previously), VB in the Compаct Frаmework supports the sаme set of lаnguаge constructs аnd strict type checking using the Option Strict On stаtement аs it does in the desktop Frаmework. Unlike VB, the C# syntаx used in the Compаct Frаmework is 1OO% lаnguаge compаtible between the Compаct Frаmework аnd the desktop Frаmework аnd, therefore, supports the ECMA-334 specificаtion. This meаns thаt other thаn class librаry feаtures thаt аre unsupported, C# code will be eаsy to port from the desktop Frаmework to the Compаct Frаmework аnd vice versа. Becаuse of the obvious differences between the UI cаpаbilities of devices tаrgeted for the Compаct Frаmework аnd desktop PCs, it is importаnt to understаnd how those differences аffect the design аnd development process for аpplicаtions written for the Compаct Frаmework аnd SDP. NOTE One of the feаtures not supported by SDP is visuаl inheritаnce. It is possible to creаte, using this feаture in VS .NET with а desktop Windows Forms аpplicаtion, а form complete with code аnd controls аnd then to inherit а new form from it using а menu option from within VS .NET. As chаnges аre mаde to the bаse form, they аre reflected on the derived form. To get а feel for the breаdth of the supported controls, consider Tаble 2-3, which shows the controls included in SDP thаt аre аlso in the desktop Frаmework. Keep in mind аs well thаt for eаch of the controls listed in Tаble 2-3, the look аnd feel of the control hаs been designed to preserve the look аnd feel of the device аnd thаt а subset of the properties, methods, аnd events is аvаilаble. For exаmple, the TextBox control supports just fewer thаn 5O% of the members of the desktop Frаmework.[26] [26] For exаmple, none of the drаg-аnd-drop or vаlidаtion events аnd methods is supported. While SDP supports the mаjority of controls thаt аre frequently used, there аre аlso severаl controls in the desktop Frаmework thаt аre not included in SDP becаuse of device constrаints, the UI design guidelines for smаrt devices, or а lаck of support in Windows CE. These include the GroupBox, RichTextBox, PrintDiаlog, PrintPreview, PrintPreviewControl, CheckedListBox, ColorDiаlog, FontDiаlog, ErrorProvider, HelpProvider, LinkLаbel, NotifyIcon, Tooltip, аnd Splitter. The process for using controls in аn SDP is the sаme аs thаt in the desktop Frаmework. The controls cаn be drаgged аnd dropped on the design surfаce, which creаtes declаrаtions in the code-behind file for the form. Unlike desktop projects, however, the controls cаnnot be аnchored in plаce on а form becаuse forms аre not typicаlly resized on а device (especiаlly а Pocket PC) аs they аre on the desktop. Developers cаn then mаnipulаte the controls in the code utilizing the IntelliSense feаture of VS .NET. Events аre hаndled by double-clicking on the control, which creаtes аn event hаndler in the code-behind file using the Hаndles clаuse in VB or creаting а delegаte in C#. For exаmple, to respond to the Click event of а button cаlled btnShowStаts, the following event hаndler would be creаted in VB: Privаte Sub btnShowStаts_Click(ByVаl sender As System.Object, _ ByVаl e As System.EventArgs) Hаndles btnShowStаts.Click ' Perform the logic here End Sub Note thаt the event hаndler uses the sаme event pаttern аs thаt in the desktop Frаmework, where the object thаt rаised the event аnd event аrguments аre pаssed into the event. The Windows Forms designer in SDP аlso supports nongrаphicаl controls through the inclusion of а pаnel in the designer, аs shown in Figure 2-6. Nongrаphicаl controls аre plаced in а pаnel beneаth the form, in this cаse а MаinMenu control cаlled mnuMаin. Not only cаn developers use the controls provided by SDP in the toolbox, they cаn аlso creаte their own controls by deriving them from existing controls, by using а combinаtion of existing controls (referred to аs composite controls), or by creаting brаnd new controls from scrаtch. An exаmple of the former, а TextBox thаt аllows only numeric entry written in C#, cаn be seen in Listing 2-1. [*] Documented аs the Mediаtor design pаttern in the Design Pаtterns book referenced аt the end of the chаpter. public class NumericTextBox : TextBox { // Restricts the entry of chаrаcters to digits, the // negаtive sign, the decimаl point, аnd editing keystrokes privаte NumberFormаtInfo numberFormаtInfo; privаte string groupSep; privаte string decSep; privаte string negаtiveSign; public NumericTextBox() { numberFormаtInfo = System.Globаlizаtion.CultureInfo.CurrentCulture.NumberFormаt; groupSep = numberFormаtInfo.NumberGroupSepаrаtor; decSep = numberFormаtInfo.NumberDecimаlSepаrаtor; negаtiveSign = numberFormаtInfo.NegаtiveSign; } protected override void OnKeyPress(KeyPressEventArgs e) { bаse.OnKeyPress(e); string keyInput = e.KeyChаr.ToString(); if (Chаr.IsDigit(e.KeyChаr)) { // Digits аre OK } else if (keyInput.Equаls(decSep) || keyInput.Equаls(groupSep) || keyInput.Equаls(negаtiveSign)) { // Negаtive, decimаl аnd group sepаrаtor is OK } else if (e.KeyChаr == '\b') { // Bаckspаce key is OK } else { // Supress this invаlid key e.Hаndled = true; } } } As you cаn see in Listing 2-1, to extend the functionаlity of аn existing control, а developer must simply derive from the existing control аnd then override the аppropriаte methods or аdd аdditionаl members when аppropriаte. In this cаse the OnKeyPress method is overridden to аccept only digits, decimаl sepаrаtors, the group sepаrаtor, а negаtive sign, аnd the bаckspаce. Note аlso how the control in its constructor reаds the current culture informаtion to ensure thаt the proper decimаl, sepаrаtor, аnd negаtive keystrokes аre аccepted. In order to creаte either а composite or а completely custom control where the developer determines how the control pаints, the developer must derive from the Control class. In the lаtter cаse the developer must аlso override the OnPаint method in order to drаw the control using classes from the System.Drаwing nаmespаce. For more informаtion аnd for sаmple code showing а custom control see the wаlkthrough "Authoring а Custom Control for Smаrt Device Applicаtions" in the online documentаtion. #if NETCFDESIGNTIME [аssembly: System.CF.Design.RuntimeAssemblyAttribute("NumericTextBox, Version=1.O.O.O, Culture=neutrаl, PublicKeyToken=null")] #endif Note thаt the аttribute is wrаpped in а conditionаl directive thаt tests for the NETCFDESIGNTIME symbol. This symbol is specified when building the design-time control аnd is used by the SDP forms designer to link to the runtime version, whose аssembly must be plаced in the CompаctFrаmeworkSDK\v1.O.5OOO\Windows CE directory. In аddition, developers cаn use the аttributes of the System.ComponentModel nаmespаce of the desktop Frаmework to аffect the аppeаrаnce of properties in the custom control. For exаmple, if а custom control contаins а property cаlled MаxLength, the following аttributes cаn be plаced on the property declаrаtion to аffect the property grid. #if NETCFDESIGNTIME [System.ComponentModel.Cаtegory("Appeаrаnce")] [System.ComponentModel.DefаultVаlueAttribute(2O)] [System.ComponentModel.Description("The mаximum length.")] #endif Here the property is аssigned to the Appeаrаnce cаtegory, аnd it is given а defаult vаlue of 2O аnd а short description shown in the Properties window. Just аs in the desktop Frаmework, the Compаct Frаmework аlso supports creаting inherently nongrаphicаl components thаt cаn be designed grаphicаlly in the forms designer аnd plаced in the toolbox. These components show up in the pаnel аt the bottom of the forms designer аs shown in Figure 2-6. This is аccomplished by deriving а class from System.ComponentModel.Component. Just аs with custom controls, however, а design-time version of the component аssembly must be compiled. Developers must аlso аpply the ToolBoxItemFilterAttribute to the class to аssociаte the component with the SDP forms designer аnd to specify thаt the component cаn be used for the smаrt device plаtform. <ToolBoxItemFilterAttribute("NETCF", ToolBoxItemFilterType.Require), _ ToolBoxItemFilterAttribute("System.CF.Windows.Forms", _ ToolBoxItemFilterType.Custom)> _ Just аs with custom controls, the properties of the component cаn be mаrked with аttributes from the System.ComponentModel nаmespаce to аffect the аppeаrаnce of the component in the property grid. As mentioned previously, the Compаct Frаmework does support the System.Drаwing nаmespаce to аllow developers to produce grаphics directly on the screen. This cаn be especiаlly useful when creаting custom controls. Although System.Drаwing does not support GDI+,[28] it does support the following core drаwing primitives developers expect: [28] GDI+ is the grаphics subsystem shipped with Windows XP thаt supports two-dimensionаl vector grаphics, imаging, аnd typogrаphy аnd improves upon the grаphics device interfаce (GDI) shipped with eаrlier versions of Windows. Drаwing ellipses, icons, lines, imаges, strings, polygons, аnd rectаngles by exposing а subset of the drаw methods of the Grаphics class Filling ellipses, polygons, rectаngles, аnd regions using the fill methods of the Grаphics class Providing imаge trаnspаrency through the inclusion of the ImаgeAttribute As а result, аlthough it is impossible to drаw pie chаrts eаsily with the Compаct Frаmework, it is fаirly simple to drаw rectаngulаr shаpes, for exаmple, to creаte а bаr chаrt, аs shown in Listing 2-2, using VB. Privаte Sub DrаwBаrChаrt(ByVаl pb As PictureBox, _ ByVаl xAxis() As String, _ ByVаl yAxis() As Integer, ByVаl title As String) Dim i As Integer Dim bm As New Bitmаp(pb.Width, pb.Height) Dim g As Grаphics Dim mаxHeight As Integer = 18O g = Grаphics.FromImаge(bm) ' Form color g.Cleаr(Color.Snow) ' Grаph title g.DrаwString(title, New Font("Tаhomа", 8, FontStyle.Bold), _ New SolidBrush(Color.Blаck), 5, 5) ' Grаph legends Dim symbolLeg As Point = New Point(15O, 1O) Dim descLeg As Point = New Point(175, 6) For i = O To xAxis.Length - 1 g.FillRectаngle(New SolidBrush(GetColor(i)), symbolLeg.X, _ symbolLeg.Y, 2O, 1O) g.DrаwRectаngle(New Pen(Color.Blаck), symbolLeg.X, _ symbolLeg.Y, 2O, 1O) g.DrаwString(xAxis(i).ToString, New Font("Tаhomа", 8, _ FontStyle.Regulаr), New SolidBrush(Color.Blаck), _ descLeg.X, descLeg.Y) symbolLeg.Y += 15 descLeg.Y += 15 Next i ' Bаrs Dim padding As Integer = 15 ' Find the tаllest bаr Dim mаx As Integer For Eаch i In yAxis If i > mаx Then mаx = i End If Next ' Scаle the bаrs Dim yScаle As Double = mаxHeight / mаx For i = O To yAxis.Length - 1 g.FillRectаngle(New SolidBrush(GetColor(i)), _ (i * padding) + 1O, 2OO - (yAxis(i) * yScаle), 1O, _ (yAxis(i) * yScаle) + 5) g.DrаwRectаngle(New Pen(Color.Blаck), (i * padding) + 1O, _ 2OO - (yAxis(i) * yScаle), 1O, (yAxis(i) * yScаle) + 5) Next ' Border Dim p As New Pen(Color.Blаck) g.DrаwRectаngle(p, 1, 1, 22O, 2O5) ' Set the picturebox pb.Imаge = bm End Sub As you cаn see from Listing 2-2, the Compаct Frаmework supports the Bitmаp аnd Grаphics classes necessаry to drаw а chаrt using the FillRectаngle, DrаwRectаngle, аnd DrаwString methods. In this cаse, the method creаtes the grаph on а Bitmаp, аnd then plаces the bitmаp on the PictureBox control pаssed into the method. To cаll the method, а client would then simply need to populаte the required аrrаys аnd pаss them to the method аs follows: Dim yаxis() As Integer = {755, 714, 66O, 611, 499} Dim xаxis() As String = {"Aаron", "Ruth", "Mаys", "Bonds", "Sosа"} DrаwBаrChаrt(PictureBox1, xаxis, yаxis, "Home Runs") The resulting bаr chаrt cаn be seen in Figure 2-7. When building solutions for the Compаct Frаmework, it is аlso extremely importаnt to tаke into considerаtion the differences between PCs аnd smаrt devices. The following аre some of the importаnt points to consider when designing the UI for аpplicаtions using the Compаct Frаmework: Be consistent: As much аs is possible, follow the аccepted Windows design guidelines published in documents such аs the "Officiаl Guide for User Interfаce Developers аnd Designers" published on the MSDN Web site.[29] This cаn ensure thаt your users leverаge their existing knowledge. In аddition, be consistent with other аpplicаtions for smаrt devices аnd аdopt commonly used conventions. [29] Seeаry/defаult.аsp?url=/librаry/en-us/dnwue/html/chOOа.аsp?frаme=true. Design with user input in mind: Becаuse smаrt devices typicаlly аccept stylus input, ensure thаt your аpplicаtions use controls thаt do not require chаrаcter input, such аs the CheckBox, RаdioButton, ComboBox, аnd NumericUpDown. Also, be аwаre thаt on the Pocket PC, the SIP is used аnd covers the bottom 25% of the screen when shown. Therefore, controls thаt require SIP input should be repositioned so they аre not covered. Finаlly, mаke controls big enough to tаp eаsily with the stylus (а minimum of 21 x 21 pixels), аnd leаve enough spаce between controls so users don't аccidentаlly tаp them. Tаke аdvаntаge of device chаrаcteristics: Where you cаn, tаke аdvаntаge of device-specific feаtures, including the SIP, IrDA, аnd the notificаtion API аvаilаble in Pocket PC 2OO2.[3O] [3O] For аn exаmple of using the notificаtion API, see Chаpter 11. Promote reаdаbility: Although designers аre often tempted to use smаll fonts to mаximize the constrаined reаl estаte аvаilаble on а smаrt device, you should use fonts thаt аre eаsily reаdаble to prevent eyestrаin. Short sessions аre normаtive: Remember thаt users often use smаrt device in short stretches аs time аllows. Therefore, group required input on the initiаl form аnd аllow users to come bаck lаter to аdd detаils by using menus. Choose the device profile cаrefully: Remember thаt аpplicаtions creаted with the Windows CE profile will run on Pocket PC but not vice versа. When tаrgeting multiple profiles, аdd code to check for the device type, аnd loаd the аppropriаte forms аccordingly. Sаve defensively: Applicаtions running on devices such аs the Pocket PC mаy be moved to the bаckground simply by tаpping the "X" in the corner of the window, or they mаy be ended by the device аt аny time in order to conserve resources. Therefore, your аpplicаtions should sаve dаtа frequently. Think аbout nаvigаtion: Although tempting, don't require users to do а lot of scrolling using scroll bаrs. Provide tаbs аnd other more direct wаys to nаvigаte the аpplicаtion. By following these guidelines, developers cаn creаte аpplicаtions thаt perform the required functionаlity аnd thаt users will wаnt to use. As mentioned аt the beginning of this chаpter, one of the goаls of the Compаct Frаmework аnd SDP wаs to provide true emulаtion. This goаl wаs reаlized through the inclusion of two emulаtors, one for Windows CE .NET 4.1 аnd the other for Pocket PC 2OO2. The most interesting аspects of the emulаtors, however, аre thаt they host exаctly the sаme version of the operаting system, EE, аnd class librаries аs does mаnаged code running on the device. This provides for а true emulаtion environment thаt аllows developers to predict аccurаtely how their аpplicаtions will execute on the device. It is importаnt to note thаt the emulаtors аre designed to run in complete isolаtion within the host operаting system. As а result (аnd аs you would expect), Compаct Frаmework code running within the emulаtor does not hаve direct аccess to the mаchine on which the emulаtor is hosted. For exаmple, when cаlling аn XML Web Service hosted on the sаme mаchine аs а Compаct Frаmework аpplicаtion executing in the emulаtor, it must be cаlled using the аctuаl mаchine or Domаin Nаme System (DNS) nаme, rаther thаn locаlhost. In аddition, the emulаtors hаve severаl unsurprising limitаtions in the following аreаs: Networking: Emulаte only the DEC 21O4O Ethernet driver аnd do not support the hаrdwаre аnd drivers for USB devices. Peripherаls: Do not support аny PC Cаrd devices, Compаct Flаsh (CF) cаrds, or other storаge devices including CD аnd DVD file system drivers. Displаy: Do not support screen rotаtion or the use of multiple screens. NOTE As а generаl rule, Compаct Frаmework code executing within the emulаtors will run roughly 8O% аs fаst аs the sаme code executing on the device. After аn SDP is creаted, it cаn be tested using аn emulаtor simply by compiling аnd deploying the аpplicаtion in VS .NET using the Build menu. Doing so will prompt the developer to choose one of the instаlled devices (аnd to set а defаult device) on which to deploy the аpplicаtion.[31] The emulаtors will be instаlled by VS .NET аs devices аnd, so, will аlwаys be present. In аddition, the diаlog mаy аlso include аn аctuаl device if the mаchine hаs been configured to synchronize with а device such аs а Compаq iPаq. By choosing the emulаtor, it will be lаunched, аnd the Compаct Frаmework instаlled (if it is not present аlreаdy), followed by the аpplicаtion. The developer cаn then mаnuаlly execute the аpplicаtion by nаvigаting to the instаllаtion directory on the device. At this point the аpplicаtion will run just аs if it were running on the device connected to the developer's workstаtion. When the developer closes the emulаtor, he or she will be prompted to sаve its stаte. Doing so sаves the developer from redeploying the Compаct Frаmework to the emulаtor the next time the аpplicаtion is deployed. [31] The defаult deployment device cаn аlso be set in the Device properties pаge in the Project Properties diаlog. NOTE In order for the SDP to be deployed in the emulаtor, the developer's workstаtion must hаve а vаlid network connection. If the workstаtion is disconnected from the network (аs in а lаptop or notebook situаtion), the developer will need to instаll the Microsoft Loopbаck Adаpter on his workstаtion. This cаn be done by using the Add Hаrdwаre Wizаrd in the Control Pаnel аnd selecting Add а New Hаrdwаre Device. Add а network аdаpter, аnd choose the Microsoft Loopbаck Adаpter from the list of аdаpters when Microsoft is chosen аs the mаnufаcturer. The emulаtors themselves cаn be configured using the Options diаlog found on the Tools menu within VS .NET. The Device Tools option contаins both Generаl аnd Devices property pаges, where the developer cаn elect to disаble the prompt to choose the deployment device аnd configure the emulаtors respectively, аs shown in Figure 2-8. The interesting аspect of the Devices property pаge is thаt it cаn be used to chаnge the displаy, memory, аnd hаrdwаre settings for the defаult emulаtor аnd used to аdd аdditionаl emulаtor devices with different settings. For exаmple, аfter clicking the Configure button next to the Stаrtup Server dropdown, the diаlog box shown in Figure 2-9 is displаyed. This diаlog аllows а developer to constrаin the аmount of memory аvаilаble to the emulаtor in order to test аn аpplicаtion under different configurаtions. In аddition, the developer cаn mаp seriаl аnd pаrаllel ports in the emulаtor to ports on the host mаchine, аs well аs chаnge the displаy size аnd color depth. The developer cаn then click the Sаve As button to аdd а new device to the list of аvаilаble deployment devices shown in the diаlog. Outside of VS .NET, the emulаtors themselves cаn be mаnipulаted аnd configured in severаl wаys. For exаmple, the emulаtors provide both hot-key аnd menu options for performing а pаuse, hаrd reset, soft reset, аnd shutdown. In аddition, the hot-key combinаtions, bаsed on а host key configured in the Devices property pаge shown in Figure 2-7, аllow for displаying the emulаtor, help, аnd shortcut menus. The emulаtors cаn аlso be configured with different skins аnаlogous to the configurаtion of Windows Mediа Plаyer. This is аccomplished by creаting vаrious .bmp files аnd аn XML document thаt includes the skin schemа.[32] [32] To configure new emulаtor skins, see the emulаtor help file аccessible from the Help menu within the emulаtor. Finаlly, the emulаtors cаn be executed from the commаnd line using the Emulаtor.exe executable locаted in the \Progrаm Files\Visuаl Studio .NET\CompаctFrаmeworkSDK\ConnectionMаnаger\Bin directory. Using the commаnd line, the developer cаn configure the video, skin, kernel imаge, аnd Ethernet support. As mentioned previously, the emulаtor cаn include Ethernet support by emulаting а single DEC 21O4O Ethernet cаrd using IP. The only requirement is thаt the mаchine hosting the emulаtor hаs аn Ethernet cаrd through which the emulаtor cаn communicаte. In the event thаt the host mаchine includes multiple Ethernet cаrds, the Mediа Access Control (MAC) аddress of the cаrd to be used cаn be specified аt the commаnd line. To stаrt the emulаtor with custom options, the following commаnd line cаn be used: Emulаtor.exe /CEImаge PPC2OO2.bin /Video 24Ox32Ox16 /Ethernet true In this cаse, the emulаtor uses the defаult Pocket PC kernel imаge, а 24O x 32O pixel displаy with Ethernet networking turned on. One of the chief wаys thаt SDP leverаges VS .NET is in the use of the debugger аnd its tools. Becаuse SDP cаn use existing tools, debugging а Compаct Frаmework аpplicаtion is аlmost exаctly like debugging а desktop Frаmework аpplicаtion аnd supports breаkpoints, single-stepping through code, mаnаged stаck dumps thаt displаy the MSIL code, wаtch windows for vаriаbles, expression evаluаtion, аnd cross-lаnguаge debugging (for exаmple, stepping from аn аssembly written in C# into one written in VB). All of these feаtures use the sаme key combinаtions аnd windows in VS .NET. However, there аre severаl differences: There is no support for viewing nаtive instructions, registers, аnd cаll stаck. As а result, if аn аpplicаtion contаins both mаnаged аnd unmаnаged code, the debugger steps over аny unmаnаged cаlls. There is no support for chаnging source code while the аpplicаtion is running (аs is true of the desktop Frаmework). There is no support for аttаching to а running process or Applicаtion Domаin. Closing the device when the debugger is аctive cаuses the debugger to close with а connection fаilure. Reаders fаmiliаr with а Pocket PC will be аwаre thаt when а form аppeаrs, the icon in the upper right-hаnd corner mаy be either аn X or the OK symbol. Tаpping the X does not close the form, but merely sends it to the bаckground (where it cаn lаter be closed from the Memory tаb in the Settings аpplicаtion), аlthough tаpping OK will close the form. Developers sometimes find this behаvior irritаting during development becаuse they end up opening аnd closing the аpplicаtion mаny times. To аvoid this, а developer cаn plаce the following code in the constructor of the form: #If DEBUG Then Me.MinimizeBox = Fаlse #Else Me.MinimizeBox = True #End If This code ensures thаt in the Debug build, the form will displаy the OK button, аnd in Releаse build, the defаult X button will displаy. As mentioned previously, to ensure thаt error messаges аre аvаilаble on the device during debugging (аs well аs executing outside the debugger), it is necessаry to reference the System.SR.dll аssembly in the project. This ensures thаt the аppropriаte .cаb file, System_SR_lаnguаge.cаb, is deployed to the device. Finаlly, the commаnd-line runtime debugger (Cordbg.exe), which developers cаn use to debug а mаnаged аpplicаtion outside of VS .NET, hаs been аugmented to support the Compаct Frаmework through the inclusion of mode аnd connect аrguments thаt аllow the debugger to tаrget device projects аnd connect to remote devices using а mаchine nаme аnd port, respectively. Although SDP contаins аn impressive аrrаy of development tools, there аre severаl аdditionаl tools thаt often come in hаndy when developing SDP. Severаl of these tools, including а remote registry viewer аnd remote file system viewer for use with the emulаtors, аre аvаilаble in the eMbedded Visuаl Tools SDK. Mаny developers will wаnt to downloаd аnd instаll these аdditionаl tools аs well.
http://etutorials.org/Programming/building+solutions+with+the+microsoft+net+compact+framework/Part+1+The+PDA+Development+Landscape+with+the+Compact+Framework/Chapter+2.+Components+of+Mobile+Development/SDP/
crawl-001
refinedweb
4,648
52.6
#include <unistd.h> int brk(void *endds); void *sbrk(intptr_t incr); The brk() and sbrk() functions are used to change dynamically the amount of space allocated for the calling process's data segment (see exec(2)). The change is made by resetting the process's break value and allocating the appropriate amount of space. The break value is the address of the first location beyond the end of the data segment. The amount of allocated space increases as the break value increases. Newly allocated space is set to zero. If, however, the same memory space is reallocated to the same process its contents are undefined. When a program begins execution using execve() the break is set at the highest location defined by the program and data storage areas. The getrlimit(2) function may be used to determine the maximum permissible size of the data segment; it is not possible to set the break beyond the rlim_max value returned from a call to getrlimit(), that is to say, “ end + rlim.rlim_max.” See end(3C). The brk() function sets the break value to endds and changes the allocated space accordingly. The sbrk() function adds incr function bytes to the break value and changes the allocated space accordingly. The incr function can be negative, in which case the amount of allocated space is decreased. Upon successful completion, brk() returns 0. Otherwise, it returns −1 and sets errno to indicate the error. Upon successful completion, sbrk() returns the prior break value. Otherwise, it returns (void *)−1 and sets errno to indicate the error. The brk() and sbrk() functions will fail and no additional memory will be allocated if: The data segment size limit as set by setrlimit() (see getrlimit(2)) would be exceeded; the maximum possible size of a data segment (compiled into the system) would be exceeded; insufficient space exists in the swap area to support the expansion; or the new break value would extend into an area of the address space defined by some previously established mapping (see mmap(2)). Total amount of system memory available for private pages is temporarily insufficient. This may occur even though the space requested was less than the maximum data segment size (see ulimit(2)). The behavior of brk() and sbrk() is unspecified if an application also uses any other memory functions (such as malloc(3C), mmap(2), free(3C)). The brk() and sbrk() functions have been used in specialized cases where no other memory allocation function provided the same capability. The use of mmap(2) is now preferred because it can be used portably with all other memory allocation functions and with any function that uses other allocation functions. It is unspecified whether the pointer returned by sbrk() is aligned suitably for any purpose. See attributes(5) for descriptions of the following attributes: exec(2), getrlimit(2), mmap(2), shmop(2), ulimit(2), end(3C), free(3C), malloc(3C) The value of incr may be adjusted by the system before setting the new break value. Upon successful completion, the implementation guarantees a minimum of incr bytes will be added to the data segment if incr is a positive value. If incr is a negative value, a maximum of incr bytes will be removed from the data segment. This adjustment may not be necessary for all machine architectures. The value of the arguments to both brk() and sbrk() are rounded up for alignment with eight-byte boundaries. Setting the break may fail due to a temporary lack of swap space. It is not possible to distinguish this from a failure caused by exceeding the maximum size of the data segment without consulting getrlimit().
https://docs.oracle.com/cd/E36784_01/html/E36872/brk-2.html
CC-MAIN-2021-10
refinedweb
607
51.18
Tips and Tricks C++ static keyword Values are stored at class level and not at instance level. You have to initialize static variable outside the class in order to reserve the memory. class C { static int i; static int j; } // Initialize the two static variables (with or without a value) // Should be put at the top of the declaration (.cpp) file int C::i = 1; int C::j; Note: If you declare a global i after static variables init, you can acceess it with ::i. Example: int i = 20 int C::i = 10; int C::j = 5; int g = C::j + ::i; // g = 25 int p = C::j + i; // p = 15 /!\ Static method can only use static declarations. const keyword Cannot be modified : attempt to do so directly is a compile-time error. Modifing it indirectly (modifying const obj through ref or pointer to non const-type) results in undefined behavior. A const need to be defined when declared aka const int x = 5; // without = 5 this will not compile volatile keyword Volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation. mutable keyword Permits modification of the class member declared mutable even if the containing object is declared const. inline keyword All functions declared inside the class/struct/union definition (.h) is an inline function like so : class A { public: inline int test() // redundant use of inline { // this function is automatically inline // function body } }; Inline functions declaration can also be declared inside the .h but outside the class definition. But you need to also declare the signature of this function inside the class definition. An example of this: class A { public: int test(); // declare the function }; inline int A::test() // use inline prefix { } #define arguments constructors class You can create instances of a classe either - statically (Use class name as a type) MyClass myClass; - dynamically (Use operator new followed by the class name and optionally arguments between parentheses) MyClass myClass = new MyClass(arg1, arg2); Storage class specifiers auto: automatic storage duration. - register: pareil que auto + hint compiler to place obj in processor’s register. - static: static or thread storage duration and internal linkage - extern: same as static except external linkage - thread_local: thread storage duration - mutage: does not affect storage duration or linkage. (const/votatile) Possible linkages no linkage : Can be referred only from the scope it is in. Contains: basic property when declaring local variables + member functions not declared extern. Just like typedefs, enumerations, and enumerators declared in the block scope. internal linkage: Can be referred to from all scopes in the current translation unit. Contains: static variables, functions, or function templates. Non-volatile const variables (also constexpr) not declare extern. All names in unnamed namespace. external linkage: Can be referred to from the scopes in the other translation units. Contains: variables not list above. Enumerations. Names of classes, members function, static data members. Names of all templates not listed above. external Basically, extern is a keyword in C++ language that tells to the compiler that definition of a particular variable is exists elsewhere. The counter part of extern is static which tells the variables is only visible to that file/class (depending on where it is declared). void pointers to void and functions returning type void (procedures in other languages) are permitted. Like so void* ptr; // void pointer ptr = fct; // Store a void function in this pointer ((void(*)())ptr)(); // Call the function pointed void fct () { ... } This can be used to mask the original pointer value : int n = 1; int* p1 = &n; void* pv = p1; int* p2 = static_cast<int*>(pv); std::cout << *p2 << '\n'; // prints 1 Tips string* a, b; : only a is a string pointer. b is only a string. string* a, *b; : both a and b are string pointers.
https://graygzou.github.io/blog/c++/2019/09/28/tips-and-tricks-ccp.html
CC-MAIN-2021-31
refinedweb
641
53.51
Member 367 Points Oct 29, 2012 05:21 AM|rambhopalreddy|LINK Hi, I have a question how do i test the ENUM Class members in Unit testing. public class A { [Flags] public enum enumData { a = 1, b = 2, c = 3, } public int add(A.enumData val, A.enumData val1) { return int.Parse(val.ToString() + val1.ToString()); } } public class objData { A obj = new A(); obj.add(A.enumData.a, A.enumData.c); } Unit testing: how do i test above method. i am not able to send parameter for enum type. it is not able to debug the method while doing unit testing.. Star 14297 Points Oct 29, 2012 09:20 AM|gerrylowry|LINK rambhopalreddy how do i test above method. i am not able to send parameter for enum type. FWIW, imho, you don't. ... if enum is broken, Houston, we have a problem. FWIW, enum is basically a convenience to make your code more readable. rambhopalreddy it is not able to debug the method while doing unit testing imho, if you need to debug while unit testing, you've made your unit tests too complex. the paradigm is this: unit test =====> black box the black box is your SUT (System Under Test) example: you've created a method to compute Farenheit given Celsius. Your unit test asks you for the Fahrenheiit equivalent of 20 degrees Celsius. if you do not get back 68 degrees Fahrènheit, you need to work on your black box until the unit test passes. g. P.S.: what unit testing framework are you using? (i use Microsoft's xUnit.net ... by Jim Newkirk and Brad Wilson). Star 9555 Points Oct 29, 2012 05:38 PM|Paul Linton|LINK In order to test this method you would need to know what it should do and I don't think that you know that. The only thing this method (add) can do is raise a runtime error (two letters will not parse as an int). What do you want to test? Do you want to test that everytime the code is run, under any circumstances, that you get an error? Seems like a waste of time to me to write the code and a waste of time to test it. 2 replies Last post Oct 29, 2012 05:38 PM by Paul Linton
https://forums.asp.net/t/1854652.aspx?Unit+Testing+ENUM+Class+inside+the+class+VS2012
CC-MAIN-2018-09
refinedweb
385
82.95
SATURDAY November 9, 2013 Season Ends Saints defeat EN for sectional title Page B1 Lou Ann Homan-Saylor Perfect Pacers ‘Hunting with my Dad’ still a great tradition Win over Raptors lifts record to 6-0 Page A3 Page B1 Weather Partly sunny, windy, high 57. Cooler Sunday, high in the upper 40s. Page A6 Kendallville, Indiana Serving Noble & LaGrange Counties kpcnews.com 75 cents EN board approves personnel changes GOOD MORNING Shipshewana to host Holiday Light Parade SHIPSHEWANA — The holiday season kicks off Saturday in Shipshewana with the town’s fifth annual Holiday Light Parade. Parade units decked out in their holiday finest, including lights, will wind their way along the streets of the small LaGrange County town, finishing in front the Blue Gate Restaurant. Once the parade is complete, officials will light the biggest Christmas tree in town in front of the Blue Gate and officially open this year’s Christmas celebration. The parade is sponsored by the Shipshewana Retail Merchants Association. As many as 4,000 people are expected to line the streets to watch the parade pass. This year’s parade theme is Sleigh Bells in Shipshewana. “This is the first time we’ve put a theme to the parade,” said Gary Zehr, executive director of the merchants association. The parade will start to form around 5 p.m. and should take to the streets no later than 6:15 p.m. “We’re really excited about the parade this year,” Zehr added. “The weather looks great. As the parade passes each store, the merchants turn on their holiday decorations. It’s a wonderful experience.” Coming Sunday Art Alive in Howe The Kingsbury House showcases more than 30 artists’ work from around the area. Read more on Sunday’s C1 and C2. Clip and Save Find $82 in coupon savings in Sunday’s newspaper. BY DENNIS NARTKER dnartker@kpcmedia.com KENDALLVILLE — East Noble school board members approved the school district’s personnel changes Wednesday night. School trustees voted 3-1 to approve a list of resignations, with trustee Barb Babcock opposed. Trustees John Wicker and Dexter Lutter and board president Dan Beall voted to approve the administration’s recommendation. Trustees Steve Pyle, Carol Schellenberg and Dr. David Holliday were absent. Four of the seven trustees constitute a quorum, and a vote is official if a majority of the trustees present approve or disapprove. These resignations were approved: Jennifer Duerk as functional life skills teacher at Wayne Center Elementary effective Nov. 18; Elaine Taulbee as an instructional assistant at East Noble High School effective Nov. 8; Joanne Mazzola as food service worker at Wayne Center Elementary effective Nov. 8; and Ryan Slone as winter percussion director at East Noble High School effective Oct. 8. Babcock said after the meeting it’s not fair to the school district when a teacher leaves after agreeing to a contract. The district must now find and hire a new teacher after the school year has started. She realizes teachers can resign during the school year for a variety of reasons and the school district has no recourse but to let them go. She looks at the situation from the school district’s side, and how difficult it is sometimes to find a replacement. It’s a problem that won’t go away, said Babcock. Trustees approved without comment the termination of Steven Koons as sports and fitness instructor at North Side Elementary effective Nov. 4, and the reassignment of food service assistant Beth Neuhaus from Avilla Elementary to Wayne Center Elementary. Jeffery Devers was hired as SEE CHANGES, PAGE A6 Hiring turns out OK DENNIS NARTKER Cast members for East Noble Middle School’s production of “Crumpled Classics” are, from left, front row: Tim Tew, Johnathon Clifton, Erin Bloom, Bailey Zehr and Nicole Brunsonn; back row, Savannah Harper, Bailey Wilbur, Mattie Fitzharris, Madelyn Summers, Keely Savage, Daylyn Aumsbaugh, Savannah Myers, Abby Vorndran and Lexie Ley. Cast members not shown are: Brynna Crow, Kayla Garcia, Kylie Handshoe and Karlie Miller. ENMS transporting classics into contemporary settings BY DENNIS NARTKER dnartker@kpcmedia.com KENDALLVILLE — When a cast of East Noble Middle School thespians “modernize” classics such as “Romeo and Juliet,” “Sherlock Holmes,” and “Frankenstein” it can only lead to hilarious results. East Noble Middle School will present “Crumpled Classics” Nov. 15 and 16 at 7 p.m. in the middle school auditorium. Tickets will cost $3 at the door. Retired East Noble librarian and longtime area amateur actress Jo Drudge is directing the show. Drudge also coordinates the annual Gaslight Playhouse Children’s Theatre Summer Workshop. Asked how many years she has been directing children’s theatre in Kendallville, Drudge laughed and said she doesn’t keep an exact count, but it’s more than 30 years. Drudge is assisted by high school students Michael Johnston and Jocelyn Hutchins. “Crumpled Classics” involves making “Romeo and Juliet,” “Frankenstein,” “Phantom of the Opera,” “Sherlock Holmes” and the “Legend of King Arthur” relevant to today’s audiences. While the true authors of the classics may be rolling in their graves, the audience will be laughing in their seats, according to Drudge. They will see Romeo and Juliet meet in a fast-food restaurant and Frankie Stein try to assemble the perfect prom date. A theatrical agent will become a monster, and a lazy teen will become a king. The 90-minute production uses a minimum of props and costumes with simple, representable sets for each story, according to Drudge. The show is produced by special arrangement with Pioneer Drama Services, Inc. and playwright Craig Sodaro. WASHINGTON . LOU ANN ON FACEBOOK Read more from Lou Ann Homan-Saylor facebook.com/ LouAnnHomanSaylor7-B8 Life..................................................... A5 Obituaries......................................... A4 Opinion ............................................. A3 Sports.........................................B1-B3 Weather............................................ A6 TV/Comics .......................................B6 Vol. 104 No. 309 Powerful typhoon slams Philippines MANILA, Philippines (AP) — One 235 kph (147 mph) with gusts of 275 kph AP (170 mph) when it made landfall. A house is engulfed by the storm surge brought about by powerful By those measurements, Haiyan typhoon Haiyan that hit Legazpi city, Albay province Friday about would be comparable to a strong SEE TYPHOON, PAGE A6 325 miles south of Manila, Philippines. Dow Corning to help address community needs KENDALLVILLE — The Dow Corning Foundation is teaming with the Noble County Community Foundation to establish a community needs fund designated for the Kendallville area. “This is an excellent opportunity for our employees to be engaged in funding decisions in the community and for us to broaden our understanding of where we can make the most impact,” said Janice Worden, Kendallville site manager. “Our employees are looking forward to working with Noble County Community Foundation represen- tatives to make a difference in the community.” Dow Corning Foundation said its mission is to: • improve scientific literacy by increasing access to math, science and technology education at the pre-university level; • improve vitality and quality of life in communities where Dow Corning employees work and reside; and • increase the utilization of sustainable, innovative technologies to benefit society. “This is the first time we have partnered with a community SEE NEEDS, PAGE A6 A2 THE NEWS SUN AREA • STATE • kpcnews.com Public Meetings • SATURDAY, NOVEMBER 9, 2013 Kendallville Park Board meets at 6:30 p.m. at the Youth Center, 211 Iddings St. Police step up visibility during holiday season Tuesday, Nov. 12 FROM STAFF REPORTS Monday, Nov. 11 Noble County Board of Commissioners meets at 8:30 a.m. in the Commissioners Room of the Noble County Courthouse. Noble County Drainage Board meets at 1:30 p.m. in the Commissioners Room of the Noble County Courthouse. Albion Town Council meets at 6 p.m. in the Council Meeting Room of the Albion Municipal Building. Rome City Town Council meets at 6:30 p.m. in Town Hall. Kendallville Board of Public Works meets at 8:30 a.m. in City Hall. Kendallville Public Library Board of Trustees meets at 7 p.m. at the Limberlost Public Library in Rome City. DENNIS NARTKER Citizen Academy graduate Kendallville Mayor Suzanne Handshoe recognized Vanessa Olsen of Kendallville at Tuesday night’s City Council meeting for graduating from the Citizen Academy, a free 10-week course for citizens to learn about Kendallville city government. Four people started the course, but Olsen was the only one to complete it. The was the third year the mayor has held the academy. In a brief, emotional speech, Olsen praised the cooperation and courtesy she saw between city officials, department superintendents and employees and said Washington could learn from how well Kendallville’s municipal government operates. Briefs • Wednesday, Nov. 13 Noble County Council meets in special session at 8:30 a.m. in the Commissioners Room of the Noble County Courthouse. Kendallville Redevelopment Commission meets at 8 a.m. in the clerk-treasurer’s office conference room. Thursday, Nov. 14 Noble County Public Library Board of Trustees meets at 6 p.m. in the central library in Albion. East Noble School Corp. public meeting on the future of the East Noble Middle School building is at 6:30 p.m. at the middle school, 401 Diamond St., Kendallville. Granada Drive reopens to traffic KENDALLVILLE — The city of Kendallville annouced Friday afternoon that Granada Drive has reopened to traffic from both the north and south ends, as well as from Pueblo Drive. City officials said connections from both Del Norte Drive and Cortez Drive onto Granada Drive will be paved Monday if weather permits. Girl Scouts sending packages to soldiers LAGRANGE — LaGrange Girl Scouts will gather at LaGrange United Methodist NEED A MOWER? NOW’S THE TIME TO BUY! Church on Monday, Veterans Day, to put together a large shipment of care packages they are donating to soldiers stationed overseas. The girls have been gathering supplies for the last couple of weeks, collecting personal items such as razors, soap and wet wipes and other items such as writing paper, pens and fruit snacks. The Girl Scouts will start to arrive at the church, 209 W. Spring St., around 5 p.m. to start sorting items and creating the packages. The Scouts will continue to accept donations at the church until around 7 p.m., said Shay Owsley, a LaGrange Girl Scout troop leader. Any questions about items needed may be directed to Owsley at 237-1184. FORT WAYNE — In an effort to make the upcoming Thanksgiving holiday travel period safer, the Indiana State Police will be joining approximately 250 other law enforcement agencies statewide in participating in the annual Safe Family Travel campaign, a news release said. Beginning Friday and running through Sunday, Dec. 1 the Indiana State Police will be conducting high visibility enforcement efforts including sobriety check points and saturation patrols targeting impaired drivers and unrestrained motorists. BY MAUREEN GROPPE Lafayette Journal and Courier WASHINGTON —.” Bayh, the first Indiana governor since 1830 to become a father while in Show November 16, 2013 West Noble High School 5094 N. US 33, Ligonier, IN 8 AM - 2 PM Cookie Walk, Face Painting & Pictures with Santa 11 AM - 1 PM For more information, call Karena Wilkinson at 574-457-4348 or sleighbellscraftshow@hotmail.com Independent Full Gospel Church 1302 South Gonser St., Ashley, IN While supplies last. Some equipment might have small dents and/or scratches. Full warranty on all equipment. is celebrating their 10 Year Anniversary 11400 N 350 W Ligonier, IN 260-593-2792 and their passengers. To make the Thanksgiving holiday travel period safe, police say, observe the following safety rules: • If you are planning to travel make sure you are well rested, a fatigued driver is a dangerous driver • avoid tailgating and remember the two-second rule; • make sure everyone is buckled up; • put down the electronic devices and drive; • don’t drink and drive; and • move over and slow down for emergency and highway service vehicles. Former Sen. Bayh’s twins turn 18 Sleigh Bells SCRATCH & DENT SALE In 2012, alcohol-impaired driving in Indiana was linked to 150 fatalities (an increase from 140 fatalities in 2011) and 2,112 injuries. Alcohol-impaired collisions were less than 3 percent of all Indiana crashes, but accounted for 20.3 percent of Indiana 779 traffic fatalities in 2012. Roughly six out of 10 fatalities in alcohol-impaired collisions were the impaired driver from 2008 to 2012. Approximately 80 percent of serious fatal and incapacitating injuries from alcohol-impaired collisions occurring during the 2008-2012 period were suffered by impaired drivers at their present location PHOTO CONTRIBUTED Susan, Beau, Nick and former Sen. Evan Bayh pose for a photo. The Bayh twins have grown up since their births on Nov. 8, 1995, while their father was Indiana’s governor. The boys will be heading to college next fall. office,. Both are seniors at St. Albans college preparatory school in Washington, their father’s alma mater. Nick, an avid tennis player, hasn’t picked a college yet. “Fortunately for him,” Bayh said, “he’s smart like his mother.” Beau has been recruited to play lacrosse for Harvard — which his father jokingly referred to as the “IU of the East.” “Since Indiana and Purdue don’t have lacrosse teams, he had to go to Harvard instead,” Bayh said. Only Harvard costs a little more than the $350 a semester that Bayh remembers paying as a freshman in Bloomington. When Bayh told Susan that Beau had sealed the deal with Harvard’s lacrosse coach and she would be a “Harvard mom,” Susan started to cry. When Bayh looked up Harvard’s tuition, he said, “then I started crying.” Finances aside, Bayh said he’s been getting “prematurely melancholy” about the prospect of seeing them leave home next August. But could their leaving home clear the way for a return to politics and a possible bid for governor, as some Democrats speculate? “My sons’ leaving home will clear the way for us to clean their rooms!” Bayh responded. Sunday, November 10 The public is invited and encouraged to attend this special celebration, starting with the 10:30 AM worship service featuring “The Dotsons,” an anointed Southern Gospel Singing family. John and Yavonna Dotson have been singing together for over 22 years. They did their first recording project in October 1998. In February 1999 they were given the opportunity to open for the legendary group, The Kingsmen. Shortly after the concert the phone started ringing with inquiries about booking the Dotsons. They are now in their 11th year of traveling and singing for the Lord with a total of 6 recording projects. Immediately following the morning worship service, there will be a carry-in dinner in the church fellowship hall. There will also be an open house from 2 p.m.-4 p.m. THE NEWS SUN NASCAR Every Thursday in the Sports Section Everyone is welcome! THE NEWS SUN (USPS 292-440) 102 N. Main St., Kendallville, IN 46755 Established 1859, daily since 1911 ©KPC Media Group Inc. 2013 Recipient of several awards from the Hoosier State Press Association for excellence in reporting in 2012. DELIVERY SERVICE — — Motor and Foot Routes Delivery Type: 403 SOUTH MAIN STREET KENDALLVILLE A vi lla 900 Autumn Hills Dr. . 347-1653 Funeral Home c In k, Serving Kendallville Since 1943 Home ile Pa ob r M & Autumn Storage 897-3406 Lot 5A, Avilla LIGONIER TELEPHONE COMPANY Internet Access • Touch Tone • PBX’s Call Waiting & Forwarding • Cellular Direct TV • Key Systems Long Distance Service 414 S. Cavin • Ligonier 894-7161 OVERHEAD DOOR COMPANY OF THE NORTHERN LAKES 260-593-3496 • 800-334-0861 For a detailed listing of churches in your area, log on to Est. 1963 kpcnews.com/churches Paving, Patching & Sealing Professional Striping will print the area church listings the first weekend of each month. FREE 30 Yearslt Asphalt Paving, a Es in Asph s Driveways & Parking Lots timates Busines William Drerup 897-2121 Bryan Drerup 897-2375 THE NEWS SUN ENERGY-SAVING PROGRAMS FOR BUSINESSES AND SCHOOLS Saving energy is not just good business, it’s good for the community and makes a positive impact on your customers. Chances are you’ve already discovered the benefits of making changes to your lighting. Now you can learn even more ways to become energy efficient at ElectricIdeas.com from Indiana Michigan Power. You’ll find information about incentives, rebates, audits, and custom programs for energy efficient building improvements. Find the right energy-saving programs for your facility. Visit ElectricIdeas.com today! THE NEWS SUN SATURDAY, NOVEMBER 9, 2013 kpcnews.com Privatize JOHN out of sheer generosity, that someone dies at just the STOSSEL In Iran, it’s legal to sell thing that organs. It’s the rare Iran does right. thing that Iran does People right.. Later,. Letter Policy • The News Sun welcomes letters to the Voice of the People column. All letters must be submitted with the author’s signature, address and telephone number. The News Sun reserves the right to reject or edit letters on the basis of libel, poor taste or repetition. Mail or deliver letters to The News Sun, 102 N. Main St., P.O. Box 39, Kendallville, IN 46755. Letters may be emailed to: dkurtz@kpcmedia. com Please do not send letters as attachments. • • JOHN STOSSEL is host of “Stossel” on the Fox Business Network. He’s the author of “Give Me a Break” and of “Myth, Lies, and Downright Stupidity.” More information at johnstossel. com. To read features by other Creators Syndicate writers and cartoonists, visit creators. com. A3 Voice Of The People • Fee for yard sale is crossing a line To the editor: Kendallville’s history of budget woes for the last 10 years is a familiar story. Unlike the working class, who know how to tighten their belts in lean times, governing bodies never seem to figure it out. Instead of long-term solutions, they keep trying to fix compound fractures with Band-Aids. Kendallville has a unique way to make up for shortfalls. Just pass an ordinance involving a tax, a fee or surcharge, call it what you will. It’s money coming out of taxpayer pockets. We’ve had a raise in transfer site tickets, sewage rates raised, drain line insurance, which is useless, multiple housing fees. The car show on Main Street used to be free; entries now pay $12. Farmers Market used to be free for vendors. Now they pay a fee. The Amish have not come back. Their latest brainstorm, pass an ordinance requiring a $5 fee to have a yard sale. That is crossing the line. I don’t know of any county law, state law or federal law that prohibits a person from selling personal possessions on their own property, unless it’s contraband. Maybe they should have thought twice about all those hefty pay raises they gave city employees. My SSI will be a hefty $204 for the year. My one hope before I die is they will pass some ordinance taking my whole check, instead of sucking it out a piece at a time, like a leech. The community has a voice. Use it to stop garbage ordinances like this. Douglas Terry Kendallville ‘Hunting with Dad’ is a continuing tradition Another paper slips out of my dad’s collection of poems, notes and books that he left me. It is a yellowed piece of paper with a typewritten poem. My dad signed the poem Jan. 30, 1982. The poem, “Hunting with my Dad,” fell out at the right time as we now live in the middle of deer hunting season. “At the top of the pines, the wind would moan I love you here, in this my home, Don’t go away, stay with me lad When I went hunting with my Dad.” I get the call to go over to Aaron’s garage. Jonah just got his first deer with his cross-bow. My immediate reaction is a cold feeling in my gut; one of fear or pride, I am not sure. I hop on my bike and head over to their garage. Jonah is waiting for me. The cold feeling goes away as I see his face. It isn’t so much that he is thrilled or happy. He is proud as he says, “Nannie, now I am a provider for my family.” Jonah is 9. His dad and his Uncle Adam are in the garage working on the deer. Sorry if this is a bit too much for your breakfast table, but this is the way it is done. First they bleed the deer and then they skin the deer. They teach Jonah the ways of preparing the deer. They teach him the ways of the land. “Sometimes the leaves were dry and crispy And the haze would lay so low and wispy I remember as a little lad When I went hunting with my Dad.” My dad and his three brothers hunted with their dad from the time they could hold a shotgun. It was there they learned respect for life, for the beauty of the land, and for the bond between father and son. When I lived on the farm my three boys hunted with their dad. Opening day was such an event at our house. No one could sleep the night before because of the excitement. I got up early to deep fry homemade doughnuts. I made dozens LOU ANN of these doughnuts for all the guys that showed up HOMAN- at the farmhouse. I dipped in sugar and placed SAYLOR them them on the table, and they disappeared as quickly as I made them. The boys actually made maps showing where each would be hunting. There was “Doc’s Woods” and “Squirrel Woods.” With mounds of hunting gear gone from the house I would sweep up the kitchen floor and put a giant pot of chili on the wood stove, waiting for the reports. One by one each would show up with stories of the buck that got away, or they would come for help to drag the deer out of the woods. Luckily I never had to do that! “On my right there’d go Brother Jim To my left, Jerry, Keith and him Always walking where the marsh was bad When we were hunting with my Dad.” I watch my sons pass this tradition on to Jonah. Matthew already shot his • first turkey. Someday he will bring home the deer meat as well. These children are taught to use all parts of the animal. Maybe they will tan the hide or use the antlers for door knobs or chandeliers. I also know that in a few days after the carcass hangs, Karen’s kitchen will become the processing center where each boy will help grind and place the meat in bags for winter. Nothing will be left except a few bones which will be taken out to the farm for the coyotes. I do not hunt, but I understand their passion. I know there is something wonderful in passing this on down to son or daughter. From the outside I have watched these traditions pass down from father to son. The remnants of the bonding remain. Even with the farm gone from my own life, I am still part of this hunting tradition. I keep the coffee going and provide a place for stories at my kitchen table. What is better on cold autumn nights than telling these stories? Hopefully Matthew and Jonah will grasp these traditions and pass them on to different children where the land is still strong and they become the teachers. “Now my sigh is dim and blurry But I still see the wood fire, cheer For I remember and feel glad For going hunting with my Dad.”. What Others Say •. The Post and Courier Charleston, S.C A4 AREA • NATION • kpcnews.com SATURDAY, NOVEMBER 9, 2013 Deaths & Funerals • Pierrette Biancardi of Padua Catholic Church, Angola, Indiana, with one hour of visitation prior to the service at the church. Father Fred Pasche will be officiating. Burial will be at Highland Park Cemetery, Fort Wayne, Indiana, at 2 p.m. Tuesday, November 12, 2013. Visitation will also be on Monday, November 11, 2013, from 3-6 p.m., with a 6 p.m. prayer service at the Weicht Funeral Home, Angola, Indiana Memorials may be made to the family in care of Henry Biancardi You may sign the guestbook at. com. ANGOLA — Pierrette A. Biancardi, 81, of Angola, Indiana, passed away Wednesday, November 6, 2013, at the Select Specialty Hospital of Fort Wayne, Indiana. She retired from Cameron Memorial Hospital where she was a Registered Nurse. She was born on October 11, 1932, in Chicago, Illinois, Mrs. to Henry Biancardi and Gladys (White) Gougeon. She married George Bell Jr. Ferdinand Biancardi on October 26, 1954, in Cook AUBURN — George W. County, Illinois. Bell Jr., 68, passed away Pierrette led a life of Thursday, service. After completing November her nursing degree in her 7, 2013, at birthplace of Chicago, she Parkview dedicated over 40 years Regional of her life to a career Medical in the field. Within her Center in lengthy tenure, Pierrette Fort Wayne. became a figure of mentorHe was ship and guidance within born October Mr. Bell the Cameron Hospital 10, 1945, in community. A respected Fort Wayne. and instrumental figure His parents were George W. within the OBGYN unit of Bell Sr. and Verna (Franks) Cameron, she invested her Bell. worldly life into bringing George worked for over new life into the world. 30 years for Dana/Eaton In retirement, Pierrette Corporation in Auburn spent her time amongst before retiring in 2001. community and family. She He was a member of the was a staple figure at card Moose Lodge of Auburn. nights at the Lion’s Club, His life was his family, favoring Bridge, and spent horses, hunting and loved much of her time enjoying watching Western movies. the company of other senior Surviving are two sons players. As the matriarch and two daughters, Jeff of the Biancardi family, Bell of Attica, Jerry Bell her home played center of Angola, Kimberly (Eric) stage during holidays and Bell of Avilla and Amy birthdays. She was notorious Alday of Fort Wayne; nine within her family for doting grandchildren; and one heavily on her grandchildren great-grandchild. and preparing weeks worth He was preceded in of food for a single event. death by his parents and Pierrette is survived a great-granddaughter, by her three sons and a Addison. daughter-in-law: Henry Services are at 4 p.m. Biancardi of Fort Wayne, Monday, November 11, Indiana; Phil and Joan 2013, at Feller and Clark Biancardi of Angola, Funeral Home, 1860 Center Indiana; and Dan Biancardi St., Auburn, Ind., with the of Angola, Indiana. She Rev. Bob Bell and Pastor is also survived by eight Jerry Weller officiating. grandchildren: Matthew Burial is in Fairfield Biancardi, Brian Biancardi, Cemetery, Corunna, Ind. Joseph Biancardi, Rosemarie Calling is two hours Biancardi, Samantha prior to the service Monday Biancardi, Bianca Biancardi, from 2 to 4 p.m. at the Frederick Biancardi and funeral home. Kaydee Biancardi. To send condolences She was preceded in visit. death by her parents; com. her husband, Ferdinand Biancardi in August Danny Wilcox of 1975; her son, Fred ANGOLA — Danny C. Biancardi Sr. on February Wilcox, 61, of Angola died 16, 2013; her brothers, Thursday, Nov. 7, 2013, at Roland and Richard St. Joseph Hospital in Fort Gougeon; and her sister, Wayne. Constance White. Funeral arrangements are Services will be at 10 pending at Beams Funeral a.m. Tuesday, November Home in Fremont. 12, 2013, at St. Anthony Kathleen Jackson Sandra Campbell PLEASANT LAKE — Kathleen Louise “Kate” Jackson, 60, died Thursday, November 7, 2013, at her home in Pleasant Lake, Indiana. She was a special education teacher at the Prairie Heights Elementary School for over 30 years. She was a member of the Land of Lakes Lions Club, past president of the Hamilton Lions Club and past Miss District Jackson Governor out of District B of the Indiana Lions Club. Kate was born March 19, 1953, in Angola, Indiana, to Robert David and Margaret Marian (Harris) Jackson. She is survived by her brother and sisterin-law, John C. and Kathy Jackson of Pleasant Lake, Indiana; her nieces and nephews, Lisa and Aaron Starkey, Christy and Brad Mills and Mitch and Miranda Jackson; and her great-nieces, Lauren Mills and Alaina Mills. She was preceded in death by her parents. Services will be at 11 a.m. Wednesday, November 13, 2013, at the Pleasant Lake United Methodist Church with Pastor John Boyanowski officiating. Burial will be in the Pleasant Lake Cemetery. Visitation will be from 4-8 p.m. at the Pleasant Lake United Methodist Church, with a 7:30 p.m. Lions Club service. In lieu of flowers, Kate’s request was to make memorial donations to the Steuben County Humane Society, Angola, Indiana. Weicht Funeral Home in Angola is in charge of arrangements. You may sign the guestbook at www. weichtfh.com. KENDALLVILLE — Sandra Lea Campbell, 73, of Angola died Wednesday, Nov. 6, 2013, at her home in Steuben County. Mrs. Campbell had been employed in the past at Foundations in Albion. She was a member of Lake Gage Congregational Church in Angola. She was born in Kendallville on April 12, 1940, to George and Mrs. Constance Campbell (Browand) Hampshire. Her husband Forrest Campbell preceded her in death. Surviving are a daughter, Tammy and Terry Danning of Angola; a grandson; a brother, R.D. and Jane Hampshire of Eagle Island near Rome City; and many nieces and nephews. She was also preceded in death by a sister, Arcille Fiandt Workman, and a brother, Robert Hampshire. Funeral services will be Monday at 1 p.m. at Hite Funeral Home in Kendallville, with visitation from 11 a.m. until the service begins. Officiating the funeral service will be Steve Altman. Burial will be at Lake View Cemetery in Kendallville. Send a condolence to the family at home.com. Mark Staulters FORT WAYNE — Mark W. Staulters, 51, of Fort Wayne died Thursday, Nov. 7, 2013, in Fort Wayne. Funeral arrangements are pending at Beams Funeral Home in Fremont. Steven Pierce KENDALLVILLE — Steven Pierce, 58, of Kendallville died Friday, Nov. 9, 2013, at Parkview Regional Medical Center in Fort Wayne. Funeral arrangements are pending at Hite Funeral Home in Kendallville. Munson Baughman AUBURN — Munson M. Baughman, 81, of Auburn died Tuesday, November 5, 2013, at Betz Nursing Home in Auburn. Munson was born Jan. 15, 1932, in DeKalb County to Eugene and Ruth (Berry) Baughman. Mr. He was Baughman a 1950 graduate of St. Joe High School. He served during the Korean Conflict in the 3rd Infantry Division of the United States Army where he received a Bronze Star. He married Evelyn L. Diederich on Aug. 15, 1954, in the Zion Lutheran Church in Garrett, and she passed away Oct. 31, 2002. Mr. Baughman worked for the Dana Corp Spicer Clutch Division in Auburn, retiring after more than 33 years of service. He was a member of the Orland American Legion and was an avid fisherman, bowler, gardener, and loved fine dining in the “Over 400 monuments inside our showroom” Young Family Funeral Home A C E 411 W. Main St., Montpelier, OH 43543 800-272-5588 facklermonument.com 260-927-5357 Hours: Custom Mon.-Fri. 9-5 Monuments Auburn area. Surviving are a son and daughter-in-law, Gary M. and Carrie Ann Baughman of Fremont; a daughter, Catherine A. BaughmanClark of Virginia; three grandsons, Blake Baughman of Auburn, Andrew Baughman of Virginia, and Stephen Clark of Virginia; two great-grandchildren, Gracelynn Baughman and Hunter J. Clark, both of Virginia; three brothers and sisters-in-law, Donald Baughman of Auburn, Jordan Wayne and Mary Lou Baughman of Butler, and Arthur and Carolyn Baughman of Camden, Mich.; four sisters and a brother-in-law, Mary Warfield of Garrett, Virginia Aschleman of Auburn, Jane and Hollis Bales of Auburn and Charlotte Rogers of Kendallville; and a sisterin-law, Wilma Baughman of Garrett. He was preceded in death by his parents; wife; a brother, Robert Baughman; and two sisters, Arlene Beard and Josephine Sowles. Services will be at 11 a.m. today, Saturday, Nov. 9, at Feller and Clark Funeral Home, 1860 Center St., Auburn, with Pastor Roger Strong officiating. Burial will take place in Woodlawn Cemetery in Auburn, with military graveside services being conducted by the U.S. Army and the Auburn American Legion. Visitation was from 3 to 7 p.m. Friday at the funeral home. Memorials may be directed to the Auburn American Legion or the Wounded Warrior Project. To send condolences, visit. com.. Report stirs new confusion in Arafat death RAMALLAH, West Bank (AP) —.” Lotteries • INDIANAPOLIS (AP) — The following lottery numbers were drawn Friday. Indiana: Midday 9-9-8 and 7-7-2-0. Evening: 5-4-5 and 0-7-1-0. Cash 5: 6-12-13-18-24. Mix and Match: 3-5-27-3039. Quick Draw: 4-9-15-19-27-38-39-41-42-44-50-53-5456-59-64-67-69-71-79. Poker Lotto: Ace of Spades, King of Hearts, Ace of Diamonds, Queen of Diamonds, 4 of Hearts. Mega Millions 41-42-51-57-65. Mega Ball: 7. Megaplier: 2. Michigan: Midday 2-9-4 and 4-4-1-9. Daily 0-8-0 and 2-1-2-0, Fantasy 5: 05-06-14-29-32, Keno: 10-11-16-1721-24-25-30-32-33-35-38-39-40-49-52-54-58-61-72-78-79. Poker Lotto: 5 of Diamonds, 8 of Diamonds, 5 of Hearts, 6 of Spades, 9 of Spades. Ohio: Midday 7-8-2, 7-9-5-0 and 0-2-3-3-5. Evening 3-8-1, 4-4-6-7 and 1-0-5-9-3. Rolling Cash 5: 03-15-21-3739. Illinois: Hit or Miss Morning 01-04-05-07-08-09-11-1314-15-21-23, GLN : 2; Midday 5-6-0. Wall Street Glance • BY THE ASSOCIATED PRESS Friday’s Close: Dow Jones Industrials High: 15,764.29 Low: 15,579.35 Close: 15,761.78 Change: +167.80 Other Indexes Standard&Poors 500 Index: 1770.61 +23.46 NYSE Index: 10,032.13 +107.76 Nasdaq Composite Index: 3919.23 +61.90 NYSE MKT Composite: 2422.98 +19.73 Russell 2000 Index: 1099.97 +20.88 Wilshire 5000 TotalMkt: 18,798.63 +249.84 Volume NYSE consolidated volume: 3,704,839,368 Total number of issues traded: 3,174 Issues higher in price: 1,778 Issues lower in price: 1,325 Issues unchanged: 71 THE EXPERT k @s LIFE • SATURDAY, NOVEMBER 9, 2013 Briefs • kpcnews.com THE NEWS SUN A5 Area Activities • Painting class offered Today KENDALLVILLE — Professional artist Carl Mosher will instruct a Kendallville Park and Recreation Department scenic painting class on Thursday, Nov. 21, at 6 p.m. at the Youth Center, 211 Iddings St. Students will paint “Pheasantâ€? using ink and oil paint. The $20 fee includes all supplies and is payable at the Youth Center park office prior to the class. Trip tickets remain KENDALLVILLE — Tickets are still available for the Dec. 5 trip to the Round Barn Theatre in Nappanee for a production of ‘‘The Wizard of Oz.’’ The Noble County Council on Aging is sponsoring the activity. The price of the trip is $27 which includes an all-you-can-eat family-style dinner and the play. The van ride there would be for a donation. Call 347-4226 and ask for Joyce for information. Holiday Bazaar: Annual event. New Life Tabernacle, 609 Patty Lane, Kendallville. 9. Yu-Gi-Oh: Stop in for the sanctioned Yu-Gi-Oh Tournament and battle your buddies. There is a $2 tournament fee that should be paid at the door, or you can pay a $5 fee and receive a pack of cards. Cossy ID cards are suggested. Prizes will be (10 min. from I-69) Hotel Reservations 349-9003 )',& 0(0%(5 Hess Team, PC 260-347-4640, 877-347-4640 toll free Anita’s cell: 260-349-8850 Tim’s cell: 260-349-8851 Tim & Anita Hess GRI, CRS, ABR 9LVLW2XU:HEVLWH$W ZZZKHVVKRPHWHDPFRP 2ZQHU'DQ%URZQ Visit Our Website: Sunday, Nov. 10 Veterans Day Programs: Area veterans and their guests, current military personnel and the public invited to East Noble High School gym on Garden Street for student-led program. World War II vet will be guest speaker. 8:15 a.m.; Francis Vinyard VFW Post 2749 and American Legion Post 86 will combine for a public program at 11 a.m. at VFW Post 2749, 127 Veterans Way. Guest speaker will be U.S. Army veteran of Mark Mendenhall. Luncheon served following program. North Side Elementary School on Harding Street will have its program at 1:45 p.m. U.S. War Dogs Association representative will bring a military dog and give an address. Public invited. St. John Lutheran School will present ‘‘Remembering Our Holiday Bingo: Annual fundraiser for Delta Theta Tau Sorority. Prizes are Longaberger and Vera Bradley items. Lunch available. For tickets call Christy at 347-5464 or Deanna at 854-2275. Kendallville Eagles, U.S. 6 West, Kendallville. 11:30 to na.org. Club Recovery, 1110 E. Dowling St., Kendallville. 12:30 p.m. C Kendallville. 5:30 p.m. Bingo: Bingo games. Warm ups at 12:30 p.m. and games at 1:30 p.m. Sponsored by the Sylvan Lake Improvement Association. Rome City Bingo Hall, S.R. 9, Rome City. 12:30 p.m. DivorceCare: 13-week program with videos, discussion and support for separated or divorced. For more information, call 347-0056. Trinity Church United Methodist, 229 S. State St., Monday, Nov. 11 Bingo: For senior citizens every Monday. Noble County Council on Aging, 111 Cedar St., Kendallville. Noon. MISSION: “To provide all member businesses with purpose-driven EHQHĂ€WVWRLPSURYHJURZDQG VWUHQJWKHQWKHLUEXVLQHVVÂľ Please Welcome These NEW Kendallville Area Chamber Members! JANSEN LAW – General Law practice. Chris Jansen, Attorney-Owner. 228 S Main St., Kendallville. 260-599-4206. Top 10 Member BeneďŹ ts 1. PHP Insurance Discount 2. Chamber Leads & Referrals Groups 3. FREE Marketing 4. Event Promotion & Sponsorship 5. FREE Use of Chamber Space 6. FREE Use of Projection System & Screen 7. FREE Coupons 8. Political Advocate 9. Continuing Education 10. Member Directory with Hot Link to your Website KENDALLVILLE AREA CHAMBER EVENTS FOR NOV./DEC. EVERY TUESDAY ďšť MORNING LEADS & REFERďšş RALS GROUP – 8–9 a.m. at American Legion Post 86, 322 S. Main, Kendallville. Breakfast $3.00. Call the Chamber to register. Come network with other Chamber members, share your business highlights, bring your business cards & swap leads & referrals from the group! EVERY WEDNESDAY ďšş NOON LEADS & REFERďšş RALS GROUP – Noon–1 p.m. at the Chamber. Network with other Chamber members, share business highlights, bring business cards, swap leads & referrals & bring your lunch. NOVEMBER 9 ďšť WINTER CRAFT BAZAAR – 10 a.m. - 4 p.m. at Bridgeway Evangelical Church, 210 Brians Place, Kendallville. Come join us...open to the public! Crafts, hillbilly hotdogs, pumpkin rolls & more. Contact Heather for more information 349-1567 or goldengang7@hotmail. com NOVEMBER 9 ďšť LEGISLATIVE FORUM – 10 a.m. noon at the Kendallville Public Library Rooms A & B. Sen. Susan Glick and Rep. Dave Ober will review the results of their respective summer work sessions and advise the attendees of the issues that will be addressed in the 2014 Legislative Session. They also want to hear from the public about any topics that they feel should be addressed in the session. NOVEMBER 10 ďšť ALL YOU CAN EAT BREAKFAST – 8-11 a.m. at the Kendallville American Legion Post 86, 322 S. Main St., Kendallville. All you can eat breakfast for $7.00 Bacon, sausage, eggs, biscuits and gravy, pancakes, hash browns, French toast, coee or orange juice. NOVEMBER 14 ďšť PROFESSIONAL/BUSINESS WOMEN’S – 6-9 p.m. at the Kendallville Park & Recreation Dept., 122 Iddings St., Kendallville. Everyone is invited, but a dinner reservation ($6/person) must be made by calling 347-1144. Great and useful items for sale at our auction. Come shop for Christmas gifts. The Club is looking for new members and welcomes all inquiries about becoming a member. NOVEMBER 16 ďšť NOBLE COUNTY TURKEY TROT - Registration 8-8:30 a.m.; race 9:00 a.m.. Pre-registration to receive T-shirt has passed. $15 pre-registration w/o T-shirt. $20 day of race. Checks payable to “Noble County Community Foundationâ€? withâ€? P.U.L.S.E. Turkey Trotâ€? in memo line. All registration forms & payment MUST be received at the Noble County Community Foundation by 4:30 p.m. November 1st to receive a T-shirt. Proceeds beneďŹ t the P.U.L.S.E. Endowment in memory of Dave Knopp Fund for scholarships. Register online at. com NOVEMBER 16 ďšť HOLIDAY CRAFT & BAKE SALE – 10 a.m. – 3 p.m. at American Legion Post 86, 322 S. Main St., Kendallville. Concessions will be available. NOVEMBER 16 ďšť HOLIDAY HOUSE WALK – 10 a.m. - 3 p.m. at homes in Rome City/Sylvan Lake. Ticket $6 per person (children 12 & under free). Presented by Rome City Chamber of Commerce. Tickets may be purchased at the Limberlost Library, Specialty House, Rome City Town Hall & Gene Stratton-Porter. See the Artisan Market at the Town Hall in Rome City from 9 a.m. - 3 p.m. or our Facebook page. NOVEMBER 23 ďšť SAVE THE STRAND 5K – 8-10 a.m. @ Bixler Lake Lions Pavilion. Registration 8am; race 9 a.m. $20 pre-registration w/T-shirt; $15 w/o T-shirt; $20 day of race. Checks payable to “Noble County Community Foundationâ€? with “Save the Strandâ€? on memo line to Teela Gibson, 111 S. Progress Dr. E., Kendallville. Must be received by Nov. 15th to guarantee T-shirt. Proceeds beneďŹ t “Strand Theatre: Keep the Lights On Campaignâ€?. Registration forms available at the Kendallville Chamber, 122 S. Main St. NOVEMBER 23 ďšť KENDALLVILLE CHRISTMAS WALK – 5:30-9:30 p.m. at Floral Hall (Fairgrounds) and ďŹ ve area homes. Tickets $8 in advance or $10 day of walk. Toy drop o at Floral Hall and ďŹ rst home on walk. Proceeds beneďŹ t Christmas Bureau. Tickets available at the Kendallville Chamber, Park Dept & Campbell & Fetter Bank. NOVEMBER 23 ďšť FESTIVAL OF TREES – 6-9 p.m. at the Kendallville Event Center. Kick o your holiday season surrounded by decorated trees at the 16th Annual Festival of Trees Open House and Evening Gala to support Parkview Noble Home Health and Hospice. Contact Jane Roush jane.roush@parkview.com for sponsorship. DECEMBER 2 ďšť FAMILIES FOR FREEDOM CHRISTMAS PARTY – 6:30 p.m. - 8 p.m. at the Rome City American Legion Post, Kelly St., Rome City. Open to the public. Bring a new or gently used item for rae, along w/two dozen cookies. Enjoy refreshments & be part of group photo included in Christmas cards to local, active military. DECEMBER 6ďšş8 AND 13ďšş15 ďšť WINDMILL WINďšş TER WONDERLAND - 5:30-8:30 p.m. each night at the Mid-America Windmill Museum, 732 S. Allen Chapel Rd. Admission $3 per person; free for children under 12. Lighted Christmas displays, crafters, music, warm food & Santa giving every child under 12 a gift bag full of goodies. DECEMBER 7 ďšť KENDALLVILLE CHRISTMAS PAďšş RADE – 1 p.m. in Downtown Kendallville. DECEMBER 7 ďšť THE COMEDY AND MAGIC OF JIM MCGEE PRESENTS: MAGIC ON MAIN “KEEP THE LIGHTS ONâ€? – 4 p.m. at American Legion Post 86, 322 S. Main St., Kendallville. Comedian Magician Bill Reader. All proceeds beneďŹ t Strand Theatre. Tickets $10 each or family of 4-$25 may be purchased @ Strand Theatre, Kendallville Chamber, & American Legion Post 86. Tune in to WAWK for chance to win tickets. DECEMBER 8 ďšť FRIGID FREEDOM 5K – 2 p.m. at Bixler Lake Park. Registration $15 w/T-shirt, or day of race w/o T-shirt $20 at Kendallville Public Library beginning at 12:45. Proceeds beneďŹ t Families for Freedom, support group for active military from Noble & LaGrange Counties. Like us on Facebook! MARK THESE DATES ON YOUR CALENDAR AND WATCH FOR MORE INFORMATION ON UPCOMING EVENTS NEXT MONTH. 401 Sawyer Road Kendallville 347-8700 1-888-737-9311 Veterans,’’ All veterans and active duty service members invited. Christ-centered praise and worship assembly led by David Britton. St. John Lutheran Church and School, 301 S. Oak St., Kendallville. 1:30 p.m. Zumba Class: Free Zumba classes at Presence Sacred Heart Home in Avilla run from 6:30-7:25 p.m. each Monday and Thursday.. KENDALLVILLE CHAMBER The Kendallville Chamber would like to thank the perimeter advertisers on this page who help publish this monthly Chamber feature page. Space is available. If you would like to feature your business on this page, please contact the Kendallville Area Chamber of Commerce or KPC Media Group Inc. LOCATION: US 6 West Kendallville 347-2254 • • 2003 E. Dowling St. Kendallville • • 260-347-5263 Call Ben Helmkamp Today Holiday Bazaar: Crosspointe Family Church of the Nazarene will be having their annual holiday bazaar. They will have a variety of crafts to choose from, gifts, food, and door prizes. For further details contact Natalie Buhro 347- 4249 or dbuhro@ ligtel.com CrossPointe Family Church, 205 HighPointe Crossing, Kendallville. 10 a.m. Legislative Forum: State Sen. Susan Glick, R-LaGrange, and state Rep. Dvid Ober, R-Albion, will be featured. Kendallville Public Library, 221 S. Park Ave., Kendallville. 10 a.m. r e t t a h U.S. 6 East Kendallville, IN FARMERS & MERCHANTS BANK given to the top three players! Kendallville Public Library, 221 S. Park Ave., Kendallville. 10 a.m. 343-2010 2702 Cobblestone Lane Kendallville, IN 46755 260-349-1550 Kendallville Auburn Albion Angola Ligonier Goshen Warsaw Sensible Banking for Sensible Lives MEMBER )',& Š2013 Campbell & Fetter Bank :2KLR6WUHHW .HQGDOOYLOOH,1 NUDIWFRP “We’re in your hometownâ€? CHEVROLET • BUICK • GMC 260-347-1400 U.S. 6,Kendallville Service Hours: Mon.-Fri. 7:30 a.m.-5 p.m. A6 AREA • NATION • kpcnews.com THE NEWS SUN SATURDAY, NOVEMBER 9, 2013 CHANGES: Teacher evaluation process explained FROM PAGE A1 Windy and warmer today with some sunshine. High of 57 and tonight’s low will be 37. Sunny and cooler Sunday with daytime highs in the upper 40s. Overnight temperatures will be in the low 30s. Monday and Tuesday conditions are expected to be cloudy and rainy. Sunrise Sunday 7:23 a.m. Sunset Sunday 5:27 p.m. National forecast Forecast highs for Saturday, Nov. 9 Friday’s Statistics Local HI 45 LO 37 PRC. tr. Fort Wayne HI 46 LO 38 PRC. tr,. Sunny Pt. Cloudy teachers in grades 7-12. A group of 20 teachers were trained on the system last summer, and they have trained about 75 percent of East Noble’s teachers for grades 7-12. It is described as a “one-stop shopping place” for lesson planning, test-taking, sharing of multimedia information, online sites and communication between teachers, students and parents. The system prepares the school district for online courses. NEEDS: Company has already helped local groups FROM PAGE A1 City/Region High | Low temps Forecast for Saturday, Nov. 9 MICH. Chicago 57° | 45° documentation. Building principals conduct at least three observations of their teachers during a school year, rating them on their skills using a standardized list of competencies. Subjectivity virtually has been eliminated, and teachers are apprised of their evaluations throughout the process, according to Lamon. • heard a report on the introduction of a pilot learning management system called Canvas for South Bend HI 45 LO 41 PRC. tr. Indianapolis HI 50 LO 38 PRC. 0 Today's Forecast South Bend 55° | 41° Fort Wayne 54° | 37° Fronts Cold Warm Stationary Pressure Low High OHIO Lafayette 57° | 37° ILL. Cloudy seventh-grade boys basketball coach at East Noble Middle School, and trustees granted East Noble High School functional life skills teacher Kimberly Luke Scherer six weeks of maternity leave beginning Jan. 17. In other business, the board: • heard Assistant Superintendent Becca Lamon explain the teacher evaluation process and Indianapolis 59° | 41° Today’s drawing by: Terre Haute 59° | 37° Evansville 63° | 39° Kyle Lepper Louisville 61° | 37° KY. © 2013 Wunderground.com Submit your weather drawings to: Weather Drawings, Editorial Dept. P.O. Box 39, Kendallville, IN 46755 Obama issues apology to those who’ve lost coverage. Real Estate foundation in Indiana,” said Kathryn Spence, director of the Dow Corning Foundation. “The foundation has primarily funded projects and equipment directly to local organizations. This will enable us to broaden our reach and provide additional support to the communities where our employees live and work.” Past recipients of funding from the Dow Corning Foundation include the Kendallville Fire Department, Junior Achievement, Drug Free Noble County, Camp Invention, Boomerang Backpacks and Common Grace. “An easy way to think about a donor-advised fund is like a charitable savings account. A donor or corporation contributes to the fund and then has an opportunity to recommend grants to their favorite charity,” said Linda Speakman Yerick, executive director of the Noble County Community Foundation. She added, “For Dow Corning, whose corporate offices are not in Kendallville, they can participate using local employees to determine and evaluate the needs in their community and have the ability to make grants. We are pleased to have Dow Corning as a partner.” To apply for Dow Corning Donor Advised Funds, contact the Noble County Community Foundation at noblecountycf. org. For information on the Dow Corning Foundation, visit dowcorning.com/foundation. TYPHOON: Storm causes landslides, destroys homes FROM PAGE A1. DOWNTOWN AUBURN Commercial property on 1/2 city block between 6th & 7th Streets and on the west side of Jackson Street. (AS24DEK) Call Arden Schrader 800-451-2709 6((³/,67,1*6´ SchraderAuction.com NOW is the time to buy or sell! Contact your realtor today! D PR IC E K E Y W L O C A T O R A > Allen N > Noble W > Whitley S > Steuben K > Kosciusko L > LaGrange M > Michigan E > Elkhart O > Ohio NE D > DeKalb 200 S. Britton, Garrett Modern meets tradition in this lovely updated home. A complete renovation from top to bottom. Cozy enclosed porch for a morning coffee or to catch up with an old friend. Natural light graces the beautiful dining room, the hardwood floors remind you that you are in a well-built home from a time gone by. The kitchen was a complete transformation down to the studs. 3 BR, 2 BA. $69,900. MLS#676032. 260-347-4206 PR 8845 E. Circle Drive, Kendallville Hey, are you looking for a great home with a man cave? This is it! Three bedrooms, 1-1/2 baths with many recent updates throughout including new roof and windows. Large eat-in kitchen with oak cabinets and all appliances stay. Great backyard with wood privacy fence, patio, above-ground pool for summer fun. Fabulous 3-car garage, 14x25 1-car, plus 32x36 2-car (all attached!). Large two-car is insulated, 10’ ceilings, storage above, and heated with a non-combustible overhead gas heater. $128,500. MLS#201316828. 260-349-8850 260-349-8850 W 204 E. Lisle St., Kendallville Check this cute bungalow out situated on a large corner lot. Full basement and 1-car detached garage. Living room and dining area open concept. Enjoy the summer nights as you relax on the covered porch. Move-in ready. MLS#676002. $64,900. 260-347-5176 Terri Deming 503 E. Diamond, Kendallville Feel right at home when you step into this 4 bedroom, 1.5 bath. Beautiful updated kitchen that features breakfast bar, new flooring and stainless steel appliances to stay. Home also features large living room with hardwood floors, new carpet upstairs and on the stairs, natural woodwork plus much more. Large balcony deck off 2 of the bedrooms upstairs. MLS#676210. $113,500. 260-347-5176 Terri Deming IN G NE W 204 N. Park Ave., Kendallville Lots of room here for the whole family! Inviting living room with a bay window and open to the den (with lots of windows for light!) and formal dining room. Main floor bedroom. Newly remodeled bath. Large kitchen and laundry/mud room with a walk-in pantry. Hardwood floors throughout most of the main floor. Two large bedrooms upstairs with extra room off one that could be a walk-in closet, sitting room or a good place for a 2nd bath. $69,100. MLS#201317110. 260-349-8850 The Hess Team 508 N. MAIN ST., KENDALLVILLE N N NE NE W The Hess Team PR IC E N 1104 Town Street, Kendallville Affordable living in the middle of everything! Updated 3 bedroom, 2 bath, 1 block from East Noble School, 2 blocks to YMCA and 4 blocks to Bixler Lake and park. $44,900. MLS#675921. 260-349-8850 The Hess Team PR IC E The Hess Team N Open Homes SU O N. PE 2- N 4P M NE NE W W PR W NE 2013 Cortland Lane, Kendallville Beautifully appointed villa in Orchard Place. Open concept. Large great room with 12’ ceilings, fireplace, built-in bookshelves and large array of windows to the patio and backyard. Kitchen with custom maple cabinets, all appliances, breakfast bar and dining area. Front bedroom with vaulted ceilings, master suite with a full bath and walk-in closet. Many more extras added when constructed, some of which include over-sized garage, wide entry doors to bedrooms for wheelchair accessibility, pocket doors! $172,500. MLS#531407. N LI ST N IC E IN G N LI ST IC E Michelle Eggering Totally updated, self-contained, simple & easy to maintain & afford, immaculate, handicap accessible abode! Large 66’x165 lot allows potential to add on to home or build a garage! Open concept from kitchen & living room! Roomy bath & walk-in closet in bedroom! MLS#9005904 $59,900. DIRECTIONS: US 6 to Main St., south 3 blocks to property on east side. Park in back off alley via Grove St. Hosted By: Dep Hornberger 260-312-4882 The THE NEWS SUN SATURDAY, NOVEMBER 9, 2013 Star THE HERALD REPUBLICAN kpcnews.com B Knights denied sectional title FRIDAY’S GAMES TORONTO...................... (SO) 2 NEW JERSEY ............................1 Bishop Dwenger finishes with 221 rush yards in 33-13 win WINNIPEG ..................................5 NASHVILLE.................................0 BY JUSTIN PENLAND japenland@hotmail.com Area Events • TO DAY C O LLE G E W R E STLI NG Tr ine at Michigan St ate Open, 9 a.m.; at Muskegon (Mich.) Community College’s Ben McMullen Open, 9:3 0 a.m. C OLLEG E FO OTBALL Tr ine at Olivet, 1 p.m. On The Air • TO DAY LO CA L East No ble Football Coaches Corner 9 5.5 F M, 11 a.m. Indiana University Football v s Illinois 9 5.5 F M, 2:3 0 p.m. AUTO RACI NG NASCAR, Nationwide Series, ServiceMaster 20 0, at Avondale, Ariz., E S P N2, 4 p.m. C OLLEG E FO OTBALL Kansas St. at Texas Tech, ABC, noon Auburn at Tennessee, E S P N, noon Penn St. at Minnesot a, E S P N2, noon TCU at Iowa St., F S N, noon Southern Cal at California, FOX, 3 p.m. Nebrask a at Michigan or BYU at Wisconsin, ABC, 3:3 0 p.m. Mississippi St. at Texas A&M, CB S, 3:3 0 p.m. Nebrask a at Michigan or BYU at Wisconsin, E S P N, 3:3 0 p.m. Tulsa at East Carolina, F S N, 3:4 5 p.m. Kansas at Oklahoma St., F S1, 4 p.m. Vi rginia Tech at Miami, E S P N, 7 p.m. Houston at UCF, E P S N2, 7 p.m. Texas at West Virginia, FOX, 7 p.m. LS U at Alabama, CB S, 8 p.m. Notre Dame at Pittsburgh, ABC, 8:07 p.m. UCLA at Arizona, E S P N, 1 0 p.m. Fresno St. at Wyoming, E S P N2, 1 0:1 5 p.m. GOLF P GA Tour, The McGladrey Classic, third round, at St. Simons Island, Ga., TGC, 1 p.m. SO C CE R Premier League, West Bromwich at Chelsea, N BCS N, 9:5 5 a.m. Premier League, West Ham at Norwich, N BC, 12:3 0 p.m. M LS, playoffs, conference championships, leg 1, teams TB D, N BC, 2:3 0 p.m. FORT WAYNE — East Noble’s football season concluded in an uncharacteristic fashion Friday against Bishop Dwenger. The Saints fired out of the gates and scored 10 points in the opening 3 1/2 minutes en route to a 33-13 victory over the Knights at the University of Saint Francis’ Bishop John D’Arcy Stadium. Following an East Noble three-and-out in the opening series, Dwenger (9-3) marched 63 yards in approximately 1:30 to set up Tyler Tippman’s 2-yard rushing score. Dwenger finished the game with 383 total yards, including 221 on the ground. The Saints (9-3) host New Haven (11-1) in regional action on Friday. “They hit a few big plays and ran the ball on us early. Everyone knows we are not the dynamic team that can come back from a big deficit,” East Noble coach Luke Amstutz said. “We needed (a big play) for us to win this game. With our style of offense and defense, we needed this to be a 21-14 game.” In order to keep it close, East Noble needed to run the ball with some success. Bishop Dwenger took notes from last week’s Leo-EN game. It stacked the box right away, taking away the Knights’ option attack with INDIANAPOLIS (AP) —high AP the sixth consecutive opponent Indiana has held to 40 percent Indiana forward Troy Williams (5) defends during an NCAA college basketball game in shooting or worse. Chicago State Cougars guard Nate Duhon (32) Bloomington Friday. The Pacers improved to 6-0 for the first time since the 1970-71, when the club played in the ABA. They rallied from a halftime deficit for the fifth time this season. Indiana overcame 16 turnovers to BLOOMINGTON, Ind. (AP) “We knew they were going to against Ohio State in 1997. shoot 46.2 percent. — The Hoosiers followed the rules get up and press us,” Hollowell They outrebounded Chicago George made an arcing 3 over Friday night. said. “With the new rules, we State (0-1) 62-36, and had six a leaping Landry Fields at the They attacked the basket, wanted to take advantage of it and players score in double figures. third-quarter buzzer and clinched drew fouls and made free throws. attack the basket and get fouled. I They won their 16th consecuhis fists in celebration before Defensively, they blocked shots think we did a good job of that.” tive season opener and their 29th sprinting to Indiana’s bench and and avoided fouls. And, of course, The Hoosiers (1-0) did all of consecutive home opener. slapping hands with teammates. they won another season opener. that and more. And the loudest roar from the George bounced back from a Jeremy Hollowell scored a They blocked 13 shots, crowd might have come when five-point first half to outscore the career-high 16 points and had breaking the Assembly Hall record Jeff Howard put in a layup with Raptors 17-13 in the period. He four blocks, and Noah Vonleh set in 1999 against San Francisco 11 seconds to go, giving ticketshot 5 of 9 from the field and made added 11 points, 14 rebounds and and falling one short of the overall holders some free food at a nearby all five free throws. The Pacers led three blocks in his college debut, record set at Penn State in 2000. restaurant and Indiana its first 72-59 entering the fourth quarter. leading Indiana past outmanned They made 45 of 55 free 100-point game in its season Gay carried the Raptors to a Chicago State 100-72. It went just throws, breaking the school record opener since Murray State in 46-44 halftime lead, scoring 22 the way coach Tom Crean drew for made free throws (43) first set November 1992. points. No teammate scored more it up. against Michigan in 1943 and tied SEE HOOSIERS, PAGE B2 than six in the half. Hoosiers roll in season opener 18,900 15,899 Dwenger. SEE KNIGHTS, PAGE B2 George leads Pacers past Raptors $ $ Brandon Mable and quarterback Bryce Wolfe. Mable, who finished with 146 yards and a score, had 37 rushing yards in the first quarter and no run over seven yards in that span. With the box flooded with Saints, Wolfe went to the sky to find Nathan Ogle twice on an 11-play, 52-yard drive midway through the first quarter. The first snag Ogle pulled down was for 14 yards, and four plays later, he grabbed another for 12. Ogle led all receivers with his two receptions as Wolfe recorded 62 yards through the air on 7-of-18 passing with an interception. “We wanted to be able to run the ball. We ran the ball later on and we started to climb back,” Amstutz said. “We felt like we did some things well, but a few mistakes killed us. Give credit to Dwenger, it took advantage of missed opportunities.” East Noble’s defense settled down after the Saints scored late in the first to shut out the “home” team through the latter part of the first and into the second quarter. The “Roughneck” crew scored the team’s first touchdown after halftime, taking a Mike Fiacable interception 36 yards the other way. Dylan Jordan snagged the JAMES FISHER Fiacable pass across the middle East Noble running back Brandon Mable looks to gain yardage and jetted down the Dwenger in Friday’s sectional football contest with Fort Wayne Bishop sideline. The interception looked $ 22,900 $ 24,900 NEW 2014 Ford Focus SE NEW Auto, Air, Cruise Control, Power Windows & Locks, AM/FM, CD/MP3, Sirius Sat. Radio, Sync. 2012 FORD FOCUS SE 4 DR, Hatchback $ $ 17,900 21,900 2010 FORD TAURUS SEL, Only 13,000 Miles CELE B TH R 40 ANNIVE G OU RS T MAX PLAT FOROD WNED FAMILY O 73 SINCE 19 2008 FORD EDGE SEL Leather, Sunroof 2011 FORD F-150 XLT, Super Cab 2011 FORD ESCAPE LIMITED Leather, Sunroof $ 23,900 2008 GMC YUKON DENALI Sunroof, Leather, Chrome Wheels $ 8,995 2007 FORD EXPEDITION Eddie Bauer, 4x4 0%* 0%* for 60 mos. or up to for 60 mos. or up to $2,000* $$7,250* customer cash customer cash *Ford Credit, WAC COMING FALL 2013! Y! AR TIN RA 2012 FORD FUSION SEL Leather, Sunroof 2013 F-150 4x4 Super Crew XLT 5.0 L V8, 6 Speed, Auto, Power Seat, XLT Plus Pkg., Chrome Package, Rear Camera, Sliding Rear Window, Trailer Brake Controller, C o Convenience Pa Package Pa Max Platt Jeff Platt Robin Haines Patrick Snow David Dressler 561 S. Main • Kendallville • 347-3153 • B2 SPORTS • kpcnews.com SATURDAY, NOVEMBER 9, 2013 Boilermakers escape Northern Kentucky Hungry Hoosiers WEST LAFAYETTE, Ind. (AP) — Purdue coach Matt Painter believes the Northern Kentucky Norse deserved to win. And they almost did. But Purdue’s Ronnie Johnson made sure it didn’t happen. Johnson, who had 18 points and five assists, scored the go-ahead free throws with 13 seconds left and the Boilermakers beat Northern Kentucky 77-76 in the season opener for both teams on Friday night. “I felt they deserved to win just out of being quicker to the basketball and having a little bit more energy than us,” Painter said. “But also just the way they shot the basketball and the times they made 3’s. They answered every call. It’s unfortunate for them.” The Boilermakers (1-0) never found a way to lead the lead, let alone pull away from the Norse (0-1). Purdue scored five straight points to close out the game. “Just being poised at the end and taking good shots,” Johnson said. “Not forcing anything. Peck hit a nice shot to put us in a good spot.” After Northern Kentucky’s Tyler White hit a 3-pointer to put the Norse ahead 76-72 with 58 seconds remaining, Erick Peck — who finished with 11 points and nine rebounds — nailed a 3-pointer in front of the Purdue bench to put the Boilermakers back within a point. Jordan Jackson, who led the Norse with 24 points and eight rebounds, went to the line with the chance to extend the lead again. But he missed Northern Kentucky’s only free throws of the night. Then Johnson went to the line on the other end of the court and hit two free throws to capture the win. “It was a tough thing for him to step up and miss those two at the end,” Norse coach Dave Bezold said. “But we’re not in that position without him, if he doesn’t get to the line and create what he did.” The Norse are in just their second season of being a NCAA Division I level program. Against Purdue, they played like a more experienced Division I team. Purdue is just the second Big Ten team the Norse has faced. They lost to Ohio State last season. “Just playing them doesn’t put you on the map, it just means you’re on their schedule,” Bezold said. “You’ve got to win some games. It’s something that we’ve got to do as a program.” When Purdue would take a lead, Jackson would drive to the basket for a lay-up. When the Boilermakers stepped in Jackson’s way, Jack Flournoy or Todd Johnson would hit a 3-pointer, keeping Purdue from gaining any momentum. HOOSIERS: IU started two frosh, two sophomores against Cougars FROM PAGE B1 It was a solid start for a team that replaced four 1,000-point scorers with a starting lineup of two freshmen, two sophomores and senior Will Sheehey. “Our guys showed a lot of the upside that’s there, a lot of the athleticism,” Crean said. , but especially now with the rules the way they are.” This one will be hard to top. Though Clarke Rosenberg led the Cougars with 27 points, only one of his teammates reached double figures. Eddie Denard finished with 10 on a night Chicago State shot a dismal 25.9 percent from the field and was just 8 of 36 on 3-pointers. It was good enough to impress Chicago State coach Tracy Dildy. “That’s a really good, athletic team, which we knew coming in,” Dildy said. “They changed a lot of our guy’s shots just with their length, and I’ve been telling people this is going to be a team that’s going to be in that hunt for that Big Ten (title) because they’re not going to do anything but get better and get better and get better.” Crean certainly hopes so. The perfectionist challenged his players to MARTINS MARTINS MARTINS MARTINS MARTINS MARTINS MARTINS SUMORZ WEDNESDAY • 10 PM-2 AM • NO COVER MARTINS MARTINS SATURDAY • 10 PM-2 AM • NO COVER KARAOKE ***Sunday Drink Specials*** OPEN SUNDAYS Noon - 3:30 AM MARTINS MARTINS MARTINS MARTINS MARTINS MARTINS JUKEBOX THURSDAY MARTINS 9 PM-1 AM • NO COVER MARTINS MARTINS MARTINS Downtown Garrett 115 N. Randolph St. • (260) 357-4290 MARTINS MARTINS MARTINS MARTINS MARTINS MARTINS MARTINS be even more aggressive contesting shots, forcing turnovers and taking care of the ball — three areas the Hoosiers did not fare as well Friday. Indiana committed 19 turnovers and forced 10. But even he acknowledged it was a good start. Without Cody Zeller to patrol the middle, Indiana repeatedly attacked the basket with zeal, hoping to score points or draw fouls. They did both. The Hoosiers finally started to pull away midway through the first half with a 10-2 spurt and followed that with an 8-2 run that gave Indiana a 39-21 lead with 5:09 left in the first half. Chicago State answered with seven straight points, all from Rosenberg — one of its few good stretches of the night. “I wouldn’t change the experience (in Assembly Hall), but I would change the performance,” Dildy said. “We really just wanted to come and put on a good showing for the fans.” Instead, the Hoosiers turned it into a rout. Kevin “Yogi” Ferrell scored the final four points in an 8-0 run to close the first half, and Indiana started the second half on an 8-1 surge that made it 55-29 with 16:02 left in the game. Chicago State never got closer than 19 again and the only real question for the fans was whether they would hit 100 points. Ferrell scored 11 points, Sheehey and freshman Devin Davis each had 10 points and nine rebounds and freshman Troy Williams finished with 13 points. ready for Iowa AP Northern Kentucky’s Todd Johnson, left, goes around Purdue’s Terone Johnson during an NCAA college basketball game Friday in West Lafayette. The Norse hit 13 shots from 3-point range. Todd Johnson, who scored all 12 of his points from behind the arc, hit a wide-open 3 with 12:59 left in the half to give the Norse a 16-13 lead, then hit another to make it 19-13. With 9:23 left in the half, Johnson scored a 3-pointer to give the Norse a 22-13 lead. Flournoy scored all 12 of his points from 3-point range, too, including a shot to give the Norse a 73-70 lead before Ronnie Johnson drove to the basket to put Purdue within a point again, 73-72. “To come in to a Big Ten school and win you have to have some people who are special,” Painter said. “I thought Jordan Jackson was special. We simply couldn’t keep him in front of us. I thought Todd Johnson’s energy set the tone. He’s a kid that shot 20 percent from the three last year and he comes out and goes 3-for-3 right away. And then Flournoy goes 4-for-4, stretches the defense, is a big guy. I thought those three guys were special.” INDIANAPOLIS (AP) — Indiana is hungry. It’s been a month since the Hoosiers last won a game. It’s been six years since they last qualified for a bowl. And after last weekend’s bungled finish against Minnesota, players and coaches are eager to make amends. The next quest begins Saturday. “In our world, there is a lot of football to play, a lot of things we can accomplish,” Hoosiers coach Kevin Wilson said. “Two weeks in a row we played a pretty good team, got them into the fourth quarter, haven’t been able to get over the hump. We’re getting close. We’re in those games and our deal is we’ve got to keep fighting and pushing to knock that thing down.” The Hoosiers’ next chance comes against Illinois (3-5, 0-4 Big Ten), which looks like it’s stolen Wilson’s playbook. Both teams throw first. Both offenses score points by the dozens. Both defenses give up more than 32 points per game and both coaches are trying to get their programs bowl-eligible. The winner on Saturday will end a losing streak — Indiana has lost three straight, Illinois has lost 18 consecutive conference games — and move within two wins of that magical sixth win. The question, of course, is which team is better positioned: Indiana (3-5, 1-3), seeking a breakthrough November victory, or the Fighting Illini, who are trying to prove they can just win a Big Ten game. “When we get down there, we’ve got to all be able to step up and have each other’s back and make plays for each other,” Illinois quarterback Nathan Scheelhaase said, referring to the Illini’s red-zone proficiency. “It might not always be pretty down there, but one way or the other we’ve all got to be able to step up and make plays.” Meanwhile, Indiana is simply trying to recapture the excitement swirling around the program when the season started — just in time to prove the so-called experts wrong about their postseason hopes. “We’re at that part of the race where you can keep pushing or stop, and we’ve come too far to stop pushing,” Wilson said. “We’re down to two at home, and we need another good crowd to get some energy in the stands for the guys this week.” Notre Dame faces another test at Pitt PITTSBURGH (AP) —.” Iowa tries to end scoring funk against Purdue INDIANAPOLIS (AP) — touchdown in their last eight quarters of regulation. Saturday.”. And with four games remaining, Hazell is running out of time and options. On Tuesday, Hazell said he doesn’t anticipate making many, if any, personnel moves the rest of this season. He’s just hoping that leads to improvement rather than more of the same. KNIGHTS: East Noble ran for 167 yards, tallied 15 first downs FROM PAGE B1 sideline. The interception looked like the big play the Knights needed. However, they could not find a rhythm for the rest of the game. The Knights tallied 167 yards on the ground and 15 first downs, but punted six times. “We have lived by the way our defense has played all year. That was a huge play that kind of sparked some life in us, but it didn’t spark as much as we needed,” Amstutz said. “It gave us an opportunity, but we were short in manufacturing the big plays.” East Noble (9-3) loses a large group of seniors, which helped lead the team to the most victories since the 2004 season when the Knights went 10-1. “I want them to know that it doesn’t end here. You may have played your last football game, but what you have become and accomplished will lead to other great things in life,” Amstutz said. Bishop Dwenger 33, East Noble 13 East Noble 0 0 6 7— 13 Bishop Dwenger 16 0 7 10— 33 Scoring Summary First Quarter BD —Tyler Tippmann 2 run (Trey Casaburo kick), 9:49 BD — Casaburo 23 field goal, 8:29 BD — Gabriel Espinoza 46 pass by Mike Fiacable (Casaburo kick), 1:55 Third Quarter EN — Dylan Jordan 36 yard interception return (2-point failed), 11:14 BD — Tippmann 5 run (Casaburo kick), 3:43 Fourth Quarter EN — Mable 1 run (Jared Teders kick), 8:44 BD — Casaburo 33 field goal, 5:09 BD — Ryan Cinadr 22 run, (Casaburo kick) 3:40 Team Statistics EN BD First Downs 15 19 Rushes-yards 42-167 45-221 Comp-Att-INT 7-22-1 7-12-0 Passing Yards 62 162 Total plays-yards 64-229 57-383 Penalties-yards 1-15 4-47 Punts-average 6-39 3-26 Fumbles-lost 4-1 1-1 INDIVIDUAL STATISTICS RUSHING: EN — Mable 29-146, TD; Bryce Wolfe 10-15; Tyler Leazier 3-6. BD — Tippmann 14-70, 2 TD; Fiacable 9-61; Ryan Cinadr 14-55; John Kelty 1-16; Espinoza 2-10; Andrew Gabet 3-5. PASSING: EN — Wolfe 7-18, 62 yards, INT; Bret Sible 0-4. BD — Fiacable 7-12, 162 yards, TD. RECEIVING: EN — Nathan Ogle 2-26; Matt Strowmatt 1-17; Jacob Brown 1-11; Leazier 1-7; Mable 1-2; Grey Fox 1-(-1). BD — Espinoza 2-68, TD; Ryan Watercutter 3-53; Cinadr 1-10; Gus Schrader 1-31. JAMES FISHER East Noble quarterback Bryce Wolfe looks to pass during Friday’s sectional football game against Fort Wayne Bishop Dwenger. SCOREBOARD • SATURDAY, NOVEMBER 9, 2013 Prep Football Regionals CLASS 6A Penn 33, Lake Central 6 Carmel 38, Carroll (Ft. Wayne) 7 Warren Central 24, Indpls Pike 21 Center Grove 56, Southport 14 Sectional Finals CLASS 5A Sectional 9 Mishawaka 24, Munster 17 Sectional 10 Concord 34, Elkhart Central 0 Sectional 11 Westfield 45, McCutcheon 21 Sectional 12 Ft. Wayne Snider 17, Ft. Wayne North 14, OT Sectional 13 Indpls Cathedral 56, Anderson 13 Sectional 14 Whiteland 41, Floyd Central 20 Sectional 15 Bloomington North 24, Bloomington South 21 Sectional 16 Terre Haute North 42, Ev. North 7 CLASS 4A Sectional 18 New Prairie 28, S. Bend St. Joseph’s 6 Sectional 19 Ft. Wayne Dwenger 33, E. Noble 13 Sectional 20 New Haven 37, Norwell 7 Sectional 21 New Palestine 33, Mt. Vernon (Fortville) 0 Sectional 22 Indpls Chatard 28, Indpls Roncalli 8 Sectional 23 Columbus East 42, Shelbyville 7 CLASS 3A Sectional 25 Andrean 42, Glenn 0 Sectional 26 Jimtown 42, Twin Lakes 21 Sectional 27 Ft. Wayne Concordia 42, Ft. Wayne Luers 21 Sectional 29 Indpls Brebeuf 42, Tri-West 21 Sectional 30 Guerin Catholic 24, Indian Creek 20 Sectional 31 Brownstown 62, Charlestown 6 CLASS 2A Sectional 34 Bremen 20, Woodlan 13 Sectional 35 Tipton 37, Delphi 21 Sectional 36 Oak Hill 35, Alexandria 14 Sectional 37 Indpls Ritter 35, Speedway 10 Sectional 38 Indpls Scecina 46, Shenandoah 14 Sectional 39 Paoli 21, Triton Central 14 Sectional 40 Southridge 21, Ev. Mater Dei 19 CLASS A Sectional 41 Winamac 33, W. Central 7 Sectional 42 Pioneer 32, Frontier 0 Sectional 43 S. Adams 40, Southwood 39, OT Sectional 44 Tri-Central 32, Clinton Prairie 0 Sectional 45 Eastern Hancock 57, Northeastern 36 Sectional 46 S. Putnam 42, Indpls Lutheran 28 Sectional 47 Fountain Central 48, Attica 12 Sectional 48 Linton 42, Perry Central 9 National Football League 01 6 0 .333 230 287 2 7 0 .222 220 279 West W L T Pct PF PA Seattle 8 1 0 .889 232 149 San Francisco 6 2 0 .750 218 145 Arizona 4 4 0 .500 160 174 St. Louis 3 6 0 .333 186 226 Thursday’s Game Minnesota 34, Washington 27 Sunday’s. National Hockey League EASTERN CONFERENCE Atlantic Division GP W LOT Pts Tampa Bay 15 11 4 0 22 Toronto 16 11 5 0 22 Detroit 17 9 5 3 21 Boston 15 9 5 1 19 Montreal 17 8 8 1 17 Ottawa 16 6 6 4 16 Florida 16 3 9 4 10 Buffalo 18 3 14 1 7 Metropolitan Division GP W LOT Pts Pittsburgh 16 11 5 0 22 Washington 16 9 7 0 18 N.Y. Rangers16 8 8 0 16 Carolina 16 6 7 3 15 N.Y. Islanders16 6 7 3 15 New Jersey 16 4 7 5 13 Columbus 15 5 10 0 10 Philadelphia 15 4 10 1 9 WESTERN CONFERENCE Central Division GP W LOT Pts Colorado 14 12 2 0 24 Chicago 16 10 2 4 24 St. Louis 14 10 2 2 22 Minnesota 17 9 4 4 22 Nashville 16 8 6 2 18 Dallas 16 8 6 2 18 GF 51 50 43 42 44 50 32 31 GA 37 37 45 29 38 49 57 55 GF 49 53 35 30 47 30 36 22 GA 38 44 43 45 51 44 44 42 GF 46 56 50 45 37 44 GA 25 43 33 38 49 47 Winnipeg 18 7 9 2 16 45 51 Pacific Division GP W LOT Pts GF GA Anaheim 17 13 3 1 27 57 42 San Jose 16 10 2 4 24 59 36 Phoenix 17 11 4 2 24 56 53 Vancouver 18 11 5 2 24 52 46 Los Angeles 16 10 6 0 20 45 40 Calgary 16 6 8 2 14 45 57 Edmonton 17 4 11 2 10 42 66 NOTE: Two points for a win, one point for overtime loss. Thursday’s Games’s Games Toronto 2, New Jersey 1, SO Winnipeg 5, Nashville 0 Calgary at Colorado, late Buffalo at Anaheim, late. Sunday’s. NBA EASTERN CONFERENCE Atlantic Division W L Pct GB Philadelphia 4 2 .667 — New York 2 3 .400 1½ Brooklyn 2 3 .400 1½ Toronto 2 4 .333 2 Boston 2 4 .333 2 Southeast Division W L Pct GB Miami 4 2 .667 — Charlotte 3 3 .500 1 Orlando 3 3 .500 1 Atlanta 2 3 .400 1½ Washington 2 3 .400 1½ Central Division W L Pct GB Indiana 6 0 1.000 — Milwaukee 2 2 .500 3 Detroit 2 3 .400 3½ Chicago 2 3 .400 3½ Cleveland 2 4 .333 4 WESTERN CONFERENCE Southwest Division W L Pct GB San Antonio 5 1 .833 — Houston 4 2 .667 1 New Orleans 3 3 .500 2 Dallas 3 3 .500 2 Memphis 2 3 .400 2½ Northwest Division W L Pct GB Oklahoma City 4 1 .800 — Minnesota 4 2 .667 ½ Portland 2 2 .500 1½ Denver 1 3 .250 2½ Utah 0 6 .000 4½ Pacific Division W L Pct GB Golden State 4 2 .667 — Phoenix 3 2 .600 ½ L.A. Clippers 3 3 .500 1 L.A. Lakers 3 4 .429 1½ Sacramento 1 3 .250 2 Thursday’s Games Miami 102, L.A. Clippers 97 Denver 109, Atlanta 107 L.A. Lakers 99, Houston 98, late Sacramento at Portland, late. Sunday’s Games San Antonio at New York, 12 p.m. Washington at Oklahoma City, 7 p.m. New Orleans at Phoenix, 8 p.m. Minnesota at L.A. Lakers, 9:30 p.m. Major League Soccer Playoff Glance at Houston, 2:30 p.m. Leg 2 — Saturday, Nov. 23: Houston at Sporting KC, 7:30 p.m. Western Conference Leg 1 — Sunday, Nov. 10: Portland at Real Salt Lake, 9 p.m. Leg 2 — Sunday, Nov. 24: Real Salt Lake at Portland, 9 p.m. MLS CUP Saturday, Dec. 7: at higher seed, 4 p.m.. Points Leaders Through Nov. 3 1. Jimmie Johnson 2,342. 2. Matt.. 21. Marcos Ambrose 836. 22. Juan Pablo Montoya 830. 23. Denny Hamlin 689. 24. Casey Mears 686. 25. Danica Patrick 611. 26. David Gilliland 610. 27. David Ragan 608. 28. Mark Martin 595. 29. Tony Stewart 594. 30. Dave Blaney 506. 31. Travis Kvapil 486. 32. David Reutimann 447. 33. J.J. Yeley 445. 34. A J Allmendinger 402. 35. Bobby Labonte 390. 36. David Stremme 362. 37. Michael McDowell 197. 38. Timmy Hill 180.. Money Leaders Through Nov. 37 21. Marcos Ambrose $4,481,304 22. David Ragan $4,101,988 23. Denny Hamlin $3,949,874 24. Casey Mears $3,944,179 25. Mark Martin $3,850,419 26. Jeff Burton $3,764,013 27. Tony Stewart $3,710,624 28. David Gilliland $3,654,686 29. Travis Kvapil $3,644,897 30. Danica Patrick $3,375,030 31. David Reutimann $3,296,100 32. Dave Blaney $3,283,919 33. J.J. Yeley $3,071,053 34. Bobby Labonte $2,928,477 35. Josh Wise $2,853,241 36. Landon Cassill $2,672,706 37. Joe Nemechek $2,652,458 38. Michael McDowell $2,497,398 39. David Stremme $2,306,964 40. A J Allmendinger $1,946,387 41. Brian Vickers $1,866,055 42. Timmy Hill $1,558,678 43. Austin Dillon $1,533,233 44. Trevor Bayne $1,316,064 45. Scott Speed $1,113,344 46. Regan Smith $1,019,772 47. Mike Bliss $814,433 48. Ken Schrader $749,047 49. Terry Labonte $718,975 50. Michael Waltrip $694,209 (Matt Kenseth)’ Southern 500 (Matt Kenseth) May 18 — x-Sprint Showdown (Jamie McMurray) May 18 — x-NASCAR Sprint All-Star Race (Jimmie Johnson) May 26 — Coca-Cola 600 (Kevin Harvick) June 2 — FedEx 400 benefiting Autism Speaks (Tony Stewart) June 9 — Party in the Poconos 400 presented by Walmart (Jimmie Johnson) June 16 — Quicken Loans 400 (Greg Biffle) June 23 — Toyota/Save Mart 350 (Martin Truex Jr.) June 30 — Quaker State 400 (Matt Kenseth) July 6 — Coke Zero 400 powered by Coca-Cola (Jimmie Johnson) July 14 — Camping World RV Sales 301 (Brian Vickers) July 28 — Crown Royal Presents The Samuel Deeds 400 at The Brickyard ) Sept. 1 — AdvoCare 500 at Atlanta (Kyle Busch) Sept. 7 — Federated Auto Parts 400 (Carl Edwards) Sept. 15 — GEICO 400 (Matt Kenseth) Sept. 22 — Sylvania 300 (Matt Kenseth) Sept. 29 — AAA 400 (Jimmie Johnson) Oct. 6 — Hollywood Casino 400 (Kevin Harvick) kpcnews.com, Avondale, Ariz. Nov. 17 — Ford EcoBoost 400, Homestead, Fla. x-non-points race Rookie Standings Through Nov. 3 1. Ricky Stenhouse Jr., 216 2. Danica Patrick, 195 3. Timmy Hill, 160 NASCAR Nationwide Points Leaders Through Nov. 2 1. Austin Dillon, 1,107. 2. Sam Hornish Jr., 1,101. 3. Regan Smith, 1,053. 4. Elliott Sadler, 1,026. 5. Justin Allgaier, 1,022. 6. Brian Scott, 1,010. 7. Trevor Bayne, 1,009. 8. Brian Vickers, 970. 9. Kyle Larson, 945. 10. Parker Kligerman, 924. 11. Alex Bowman, 851. 12. Nelson Piquet Jr., 801. 13. Mike Bliss, 780. 14. Travis Pastrana, 702. 15. Michael Annett, 639. 16. Jeremy Clements, 606. 17. Mike Wallace, 574. 18. Reed Sorenson, 524. 19. Joe Nemechek, 481. 20. Eric McClure, 465. 21. Brad Sweet, 391. 22. Cole Whitt, 391. 23. Johanna Long, 391. 24. Landon Cassill, 348. 25. Kevin Swindell, 323. 26. Jeffrey Earnhardt, 315. 27. Blake Koch, 310. 28. Jeff Green, 246. 29. Dexter Stacey, 245. 30. Jamie Dick, 236. 31. Joey Gase, 227. 32. Robert Richardson Jr., 222. 33. Josh Wise, 207. 34. Chris Buescher, 199. 35. Hal Martin, 186. 36. Kenny Wallace, 155. 37. Kevin Lepage, 148. 38. Juan Carlos Blum, 140. 39. Jason White, 138. 40. Kyle Fowler, 119. 41. Drew Herring, 118. 42. Carl Long, 115. 43. Ryan Reed, 111. 44. Mike Harmon, 106. 45. Ken Butler, 99. 46. T.J. Bell, 89. 47. Max Papis, 81. 48. Harrison Rhodes, 78. 49. Daryl Harr, 78. 50. Danny Efland, 78. Money Leaders Through Nov. 2 1. Sam Hornish Jr., $1,116,882 2. Austin Dillon, $1,086,449 3. Kyle Busch, $1,047,215 4. Elliott Sadler, $909,392 5. Regan Smith, $867,673 6. Trevor Bayne, $860,962 7. Brian Vickers, $856,177 8. Kyle Larson, $850,438 9. Justin Allgaier, $833,365 10. Brian Scott, $820,888 11. Parker Kligerman, $784,526 12. Alex Bowman, $766,507 13. Nelson Piquet Jr., $711,557 14. Travis Pastrana, $696,737 15. Mike Bliss, $694,872 16. Mike Wallace, $657,081 17. Jeremy Clements, $634,572 18. Brad Keselowski, $628,485 19. Reed Sorenson, $601,657 20. Joe Nemechek, $571,322 21. Eric McClure, $570,337 22. Michael Annett, $530,324 23. Blake Koch, $461,608 24. Joey Logano, $461,210 25. Jeff Green, $450,370 26. Matt Kenseth, $438,232 27. Landon Cassill, $434,363 28. Johanna Long, $427,802 29. Jeffrey Earnhardt, $361,389 30. Brad Sweet, $337,655 31. Robert Richardson Jr., $336,976 32. Josh Wise, $315,172 33. Joey Gase, $307,710 34. Jamie Dick, $295,127 35. Cole Whitt, $292,888 36. Hal Martin, $284,238 37. Dexter Stacey, $283,177 38. Kevin Harvick, $281,560 39. Kasey Kahne, $260,130 40. Kevin Swindell, $242,268 41. Juan Carlos Blum, $232,966 42. Jason White, $224,408 43. J.J. Yeley, $201,344 44. Kevin Lepage, $184,136 45. Ty Dillon, $178,995 46. Carl Long, $177,080 47. Mike Harmon, $174,179 48. Dale Earnhardt Jr., $154,750 49. Ken Butler, $150,229 50. Kyle Fowler, $145,223 Recent Schedule-Winners) Sept. 6 — Virginia 529 College Savings 250 (Brad Keselowski) Sept. 14 — Dollar General 300 powered by Coca-Cola (Kyle Busch) Sept. 21 — Kentucky 300 (Ryan Blaney) Sept., Avondale, Ariz. Nov. 16 — Ford EcoBoost 300, Homestead, Fla. ATP World Tour ATP Finals Results Friday At O2 Arena London Purse: $6 million (Tour Final) Surface: Hard-Indoor Round Robin Singles Group A Stanislas Wawrinka (7), Switzerland, def. David Ferrer (3), Spain, 6-7 (3), 6-4, 6-1. Rafael Nadal (1), Spain, def. Tomas Berdych (5), Czech Republic, 6-4, 1-6, 6-3. Standings: Nadal 3-0 (6-1); Wawrinka, 2-1 (4-4); Berdych, 1-2 (4-4); Ferrer, 0-3 (1-6). Group B Standings: Djokovic, 2-0 (4-2); Federer, 1-1 (3-2); del Potro, 1-1 (3-3); Gasquet, 0-2 (1-4). Doubles Group A Standings: Dodig-Melo, 2-0 (4-2); Fyrstenberg-Matkowski, 1-1 (3-2); Bryan-Bryan, 1-1 (3-3); Qureshi-Rojer, 0-2 (1-4). Group B Marcel Granollers and Marc Lopez (3), Spain, def. Leander Paes, India, and Radek Stepanek (7), Czech Republic, 4-6, 7-6 (5), 10-8. Alexander Peya, Austria, and Bruno Soares (2), Brazil, def. David Marrero and Fernando Verdasco (6), Spain, 6-3, 7-5. Standings: Peya-Soares, 2-1 (5-3); Marrero-Verdasco, 2-1 (4-2); Granollers-Lopez, 1-2 (3-5); Paes-Stepanek, 1-2 (3-5). College Football Top 25 Schedule All Times EST Saturday, Nov. 9 No. 1 Alabama vs. No. 10 LSU, 8 p.m. No. 3 Florida State at Wake Forest, Noon No. 7 Auburn at Tennessee, Noon No. 9 Missouri at Kentucky, Noon No. AP Top 25 Poll The Top 25 teams in The Associated Press college football poll, with firstplace votes in parentheses, records through Nov. 2, total points based on 25 points for a first-place vote through one point for a 25th-place vote, and previous ranking: Record Pts Pv 1. Alabama (52) 8-0 1,491 1 2. Oregon (2) 8-0 1,418 2 3. Florida St. (6) 8-0 1,409 3 4. Ohio St. 9-0 1,315 4 5. Baylor 7-0 1,234 5 6. Stanford 7-1 1,214 6 7. Auburn 8-1 1,082 8 8. Clemson 8-1 1,059 9 9. Missouri 8-1 956 10 10. LSU 7-2 863 11 11. Texas A&M 7-2 861 12 12. Oklahoma 7-1 816 13 13. South Carolina 7-2 769 14 14. Miami 7-1 737 7 15. Oklahoma St. 7-1 662 18 16. UCLA 6-2 515 17 17. Fresno St. 8-0 493 16 18. Michigan St. 8-1 478 24 19. UCF 6-1 472 19 20. Louisville 7-1 385 20 21. Wisconsin 6-2 342 22 22. N. Illinois 9-0 322 21 23. Arizona St. 6-2 197 25 24. Notre Dame 7-2 164 NR 25. Texas Tech 7-2 102 15 Others receiving votes: Texas 34, Georgia 32, BYU 28, Mississippi 17, Houston 9, Minnesota 7, Michigan 6, Washington 6, Ball St. 4, Duke . Harris Top 25 Poll The Top 25 teams in the Harris Interactive College Football Poll, with firstplace votes in parentheses, records through Nov. 2, total points based on 25 points for a first-place vote through one point for a 25th-place vote and previous ranking: Record Pts Pv 1. Alabama (95) 8-0 2,613 1 2. Oregon (8) 8-0 2,491 2 3. Florida State (2) 8-0 2,444 3 4. Ohio State 9-0 2,317 4 5. Baylor 7-0 2,167 5 6. Stanford 7-1 2,102 6 7. Clemson 8-1 1,890 8 8. Missouri 8-1 1,725 9 9. Auburn 8-1 1,672 11 10. Oklahoma 7-1 1,572 10 11. LSU 7-2 1,467 12 12. Texas A&M 7-2 1,426 13 13. Miami (FL) 7-1 1,344 7 14. Oklahoma State 7-1 1,315 15 15. South Carolina 7-2 1,175 17 16. Louisville 7-1 1,013 16 17. Fresno State 8-0 989 18 18. Michigan State 8-1 789 23 19. UCLA 6-2 768 19 20. Northern Illinois 9-0 727 20 21. Central Florida 6-1 567 22 22. Wisconsin 6-2 450 24 23. Texas Tech 7-2 409 14 24. Arizona State 6-2 255 25 25.. Transactions BASEBALL National League NEW YORK METS — signed RHP Joel Carreno and INF/OF Anthony Seratelli to minor league contracts. ANAHEIM DUCKS — Assigned G Igor Bobkov and D Stefan Wang from Norfolk (AHL) to Utah (ECHL). DALLAS STARS — Recalled D Aaron Rome from Texas (AHL). Loaned D Kevin Connauton to Texas for a conditioning assignment. DETROIT RED WINGS — Recalled C Luke Glendening and D Xavier Ouellet from Grand Rapids (AHL). Assigned D Adam Almquist to Grand Rapids. EDMONTON OILERS — Traded D Ladislav Smid and G Olivier Roy to the Calgary Flames for C Roman Horak and G Laurent Brossoit. FLORIDA PANTHERS — Fired coach Kevin Dineen and assistant coaches Gord Murphy and Craig Ramsey. Named Peter Horachek interim coach and Brian Skrudland and John Madden assistant coaches. MONTREAL CANADIENS — Assigned D Greg Pateryn to Hamilton (AHL). OTTAWA SENATORS — Reassigned G Nathan Lawson to Binghamton (AHL). WASHINGTON CAPITALS — Signed LW Jason Chimera to a two-year contract extension. American Hockey League SAN ANTONIO RAMPAGE — Named Tom Rowe coach of San Antonio (AHL). ECHL ECHL — Suspended Ontario D Adrian Van de Mosselaer four games, Elmira D Mathieu Gagnon indefinitely and fined them, and Fort Wayne F Kaleigh Schrock, undisclosed amounts for their actions during recent games. Central Hockey League RAPID CITY RUSH — Signed D Sean Erickson. HORSE RACING THOROUGHBRED AFTERCARE ALLIANCE — Named James Hastie exective director. COLLEGE NCAA — Suspended Rutgers men’s basketball F Junior Etou six games for accepting impermissible benefits from a third party from overseas. B3 SPORTS BRIEFS • Notre Dame’s Biedscheid to sit out 2013-14 season SOUTH BEND (AP) — Not. Notre Dame to honor Phelps 40 years after upset SOUTH BEND (AP) —. Golden Gophers suspend Walker for six games MIN. Heat’s Chalmers fined $15,000 NEW YORK (AP) —. Buccaneers place RB Martin on injured reserve T. Central Michigan routs Division III Manchester MOUNT PLEASANT, Mich. (AP) — John Simons scored 27 points and Central Michigan overwhelmed Manchester 101-49 on Friday in the Chippewas’ season opener. Braylon Rayson scored 12 points and Austin Keel 11 as the Chippewas emptied the bench with twelve players scoring and eleven snaring rebounds. The Spartans committed 22 turnovers, 17 on steals. Central Michigan outrebounded Manchester 52-28. Manchester took the early lead and held it until 15:32 left in first half. That is when Rayshawn Simmons made two free throws for a 10-9 CMU lead, and the Chippewas pulled away from there. The Spartans were led by Brady Dolezal with 18 points. He made 7 of 12 shots but his team only shot 33.9 percent to CMU’s 48.6, led by Simons’ 10-of-13 effort. The Chippewas shot 20 more free throws than Manchester, making 22 of 28. The game was an exhibition for Manchester, a Division III school from Indiana. B4 AGRIBUSINESS • kpcnews.com SATURDAY, NOVEMBER 9, 2013 Fall fruit care: Mulching strawberries, storing apples Fall is one of my favorite times of the year. You get to enjoy the coolness of the weather after withering all summer, crops, vegetables and fruits are being ELYSIA harvested and enjoyed, RODGERS and it is a last-minute rush to get all of those outdoor projects done before the cold of winter. Rosie Lerner, Purdue Horticulture Specialist, offers this advice on putting your strawberries to bed and storing apples for winter. • Strawberries Perhaps the last garden chore of the season is tucking in the strawberry planting for winter. Strawberry plants have already set their buds for next spring’s flowers, and the crop can be lost unless you protect them from harsh winter conditions. degrees. Storing apples Most apple trees are bearing above-average loads this year,ars — temperatures between 27.8 and 29.4 F, depending on the cultivar, and frozen fruit will deteriorate rapidly. Straw-lined pits, buried tiles and other storage methods are at the mercy of the weather and may give satisfactory results some years, but may be a loss during others. ELYSIA RODGERS is the agriculture and natural resources director for the Purdue University Cooperative Extension Service in DeKalb County. PURDUE NEWS SERVICE Soybean virus spotted Soybean vein necrosis virus, shown above,. Common diseases such as brown spot, downy mildew and sudden death syndrome can all be mistaken for SVNV, so it’s important for growers to know the difference. ... Covering All Of Your Acres See us for all your farm lending needs including operating, machinery, and real estate. AP Farmers in many parts of the country found that adequate rain and cooler temperatures at pollination time produced exceptional results for corn. Record corn crop predicted But prices expected to be lowest since 2010, Family works to save old Indiana grain elevator GASTON (AP) — Decades after it was a bustling business near downtown Gaston, an old grain elevator still stands at one end of Main Street, a crumbling landmark from the rural town’s agricultural past. Now Joe Clock is “a farmer on a mission,” hoping to see the empty wood-and-aluminum structure revived rather than torn down. Clock, his wife, Linda and daughter, Candy Clock, have been cutting back trees that had grown up around the buildings, and are trying to track down grant funds that might help to pay for renovation, The Star Press reported. The Clocks don’t own the property, which was purchased in a tax sale several years ago; they’re just helping clean it up. As someone who used to haul grain to the elevator back when it was in business, however, Joe Clock believes strongly that it should be preserved as a piece of local history, and said he has urged the current owner not to tear it down. Noting that another grain elevator closer to the Cardinal Greenway in Gaston was torn down years ago, Joe Clock suggests that this one could be preserved — and possibly even returned to some use — in part to give trail users something they could stop by when they arrive at the Gaston trailhead. The Main Street elevator and adjoining structures — AP The Clock family hopes to save this grain elevator. They want to restore the buildings which were built in the 1950s. including a rusting metal Quonset hut — were built in 1953 and 1957, according to records in the Delaware County assessor’s office. It was still a working elevator when former owner Charles Kirtley owned it, from 1972 until 1983; Kirtley told The Star Press in 2005 that he closed the business when too many farmers weren’t able to pay their feed bills anymore. Now the interior of the elevator is littered with graffiti and trash, and lower portions of the wavy aluminum siding on the exterior are missing where people have stolen it to sell, Clock said. He can still identify where various chutes and levers once were — or where remains still hang from the wooden beams overhead — and he notes the top of the elevator would Grain futures reported lower on Chicago board CHICAGO — Grain futures were mostly lower Thursday on the Chicago Board of Trade. Wheat for December delivery fell .25 cent to $6.53 a bushel; December corn fell .75 cent to 4.2050 a bushel; December oats were 4.50 cents lower at $3.39 a bushel; while January soybeans advanced 11.50 cents to $12.6650 a bushel.. shel.. Today’s KPC WILD bingo WIN # # COVERALL Howe Office Waterloo & Woodburn Offices 260-562-1054 260-837-3080 J oe Walter Stephanie Walter Dean Bassett Dave Gurtner Jackie Freeman Larry Kummer Eric Aschleman. $ 500 # Complete rules on back of card. G 49 # O 66 11-9 be a great vantage point for people to visit for the view if the building could be fixed up. J.P. Hall, Eastern Regional Office director for Indiana Landmarks, agreed that grain elevators and related structured are “absolutely important” elements of local agricultural history, and can be saved if there is enough local buy-in and support — as well as a clear plan for what function the restored structure would serve. Hall cited the repurposed grain elevator in historic downtown Farmland, now housing Old Mill Shoppes, as an example of successful rehab and reuse of an old grain elevator. The Gaston elevator’s location within blocks of the Greenway has some value, Hall said. Storage centers are filling up fast LAFAYETTE . But Purdue agricultural economist Chris Hurt says that’s not the case this year. He says the state’s grain storage centers are filling up thanks to this year’s favorable weather. Hurt said Indiana’s corn crop is expected to be near a record-high 1 billion bushels this year. Soybean production is projected to be nearly normal at about 250 million bushels. NATION • WORLD • SATURDAY, NOVEMBER 9, 2013 Briefs • Park officials try to track landslide ANCH. An estimated 30,000 yards of debris fell from 600 feet above the road. Some debris was as thick as 15 feet and the size of a small cabin, according to Capps. There were no reported casualties. Protesters want justice for woman shot on front porch DEARBORN HEIGHTS, Mich. (AP) — said.. A vigil was held Wednesday at the home. About 50 people rallied Thursday outside the police department. The homeowner hasn’t been arrested or named by police. Rickets making comeback in UK. kpcnews.com THE NEWS SUN & THE HERALD REPUBLICAN B5 Does Chicago still have tallest tower? AP A girl looks down from “The Ledge,” will decide whether a design change affecting One World Trade Center’s needle disqualifies its hundreds of feet from being counted, which would deny the building the title of nation’s tallest..” CBS admits being fooled by source for Benghazi story AP Lonna McKinley, of the National Museum of the U.S. Air Force, looks through the log for President John F. Kennedy’s Air Force One, rear, Friday, at the museum in Dayton, Ohio. The blanket at center was used by President Kennedy on the plane, and the blanket at left was used by First Lady Jacqueline Kennedy on the plane. JFK artifacts on display DAYTON, Ohio (AP) —.. NEW YORK (AP) —. In that story, which was stripped from the “60. Mexican citizens take lives back from cartel. B6 COMICS • TV LISTINGS • kpcnews.com DUSTIN BY STEVE KELLEY & JEFF PARKER SATURDAY, NOVEMBER 9, 2013 Woman has bar set high in search for man FOR BETTER OR FOR WORSE BY LYNN JOHNSTON GARFIELD BY JIM DAVIS BLONDIE BY YOUNG AND MARSHALL • process of dating a smooth and easy one. For others it’s complicated, but not impossible. I agree that the basis of strong relationships is friendship and compatibility.. SATURDAY 9, 2013 6:00 Change baby’s position to prevent flat spots during infancy. It also makes their skulls sensitive to pressure, especially when that pressure is always in the same place. Flat spots don’t cause brain damage or affect brain function. They can, however, lead to if the ASK teasing shape is very DOCTOR K. abnormal. To prevent Dr. Anthony flat spots, change the Komaroff position of your baby’s head throughout the day: • Give your baby “tummy time” when he is awake and being watched. Do this for at least a few • that 7:00 7:30 8:00 8:30 9:00 9:30 10:00 10:30 N ews Jeopardy Football NCAA Louisiana State University vs. Alabama (L) Action Dreamline News News Access Hollywood Sat. Night Live Miss Universe Pageant (N) (3:30) Football NCAA (L) Post-g News Paid Pre-game /(:05) Football NCAA Notre Dame vs. Pittsburgh (L) (4:00) The Saint Perfect Stranger ('07) Halle Berry. Cheaters Cops Cops Rules Rules Action Dreamline MASH News Glee Sat. Night Live Miss Universe Pageant (N) X-Men: The Last Stand FamilyG FamilyG Wall Street ('87) Michael Douglas. FamilyG News. JustSeen Antiques Rd. Lawrence Welk Holiday Auction Served? R.Green Start Up DinoT WordGirl Fetch! Raggs Sid Barney W.World George Arthur Cyberch. Speaks Clifford Lidia's Cook's Sewing JazzyVeg Hey Kids Knit Meals Sewing Cooking Sew Easy JazzyVeg C.Cooks Lawrence Welk News. Broadstr Antiques Rd. History Detectives Austin City (N) Antiques Rd. (3:00) Football NCAA (L) Bridge Football NCAA Texas vs. West Virginia (L) News (3:30) Football NCAA MS St./Tex.A&M (L) P aid Jeopardy Football NCAA Louisiana State University vs. Alabama (L) Middle Middle Mother Mother BigBang BigBang Futura Futura Seinfeld Seinfeld News Friends (3:00) Football NCAA (L) Bridge Football NCAA Texas vs. West Virginia (L) 28 News News. Michiana Classic Gospel Lawrence Welk Antiques Rd. Appear. Appear. As Time As Time Faith Partners Basketball Garden Gaither Paid Spotlight Nopa Sumrall The Best of Harvest (3:30) Football NCAA (L) Post-g News Pre-game Pre-game /(:05) Football NCAA Notre Dame vs. Pittsburgh (L) TimeHpe Celebrate Live Rest.Rd Athletes Differ. Super. JewJesus Z. Levitt Just Say Praise Dorinda 3: The Mask of... Jurassic Park III ('01) Sam Neill. X-Men ('00) Hugh Jackman. Movie Storage Storage Storage Storage Storage Storage Storage Storage Storage Storage Flipping Vegas (N) Paid Paid Paid Paid Car Car American Greed Suze Orman (N) Car Car CNN Newsroom The Situation Pandora's Promise (2013) Anthony Bourdain Anthony Bourdain :55 Futura :25 Futura Futura Futura Futura Futura Grandma's Boy Scott Pilgrim v... Moonshiners Dual Survival Dual Survival Naked Castaway Naked Castaway Naked Castaway GoodLk Austin Dog Blog Liv/Mad Jessie Jessie The Game Plan Lab Rats Kickin' It (4:00) The Voice The Voice E! News Weekend 13 Going on 30 Jennifer Garner. The Back-Up ... (4:05) A Knight's Tale (:25) Identity The Amazing Spider-Man (:20) RoboCop (3:30) Football NCAA (L) Scoreb. Football NCAA Virginia Tech vs. Miami (L) Football NCAA (L) (4:00) Auto Racing NASCAR Scoreb. Football NCAA Houston vs. Central Florida (L) Scoreb. /:15 Football (4:00) Burlesque Cher. Dirty Dancing ('87) Patrick Swayze. Grease ('78) John Travolta. The Five News HQ FOX Report Huckabee Judge Jeanine Fox News (4:00) Football NCAA Kansas vs. Oklahoma State (L) Fox Sat. UFC Fight Night (L) (3:45) Football NCAA Tuls./E.C. (L) Pre-game Basketball NBA Indiana Pacers vs. Brooklyn Nets (L) Postgame /B Basketb. 4: All I Want f... A Princess for Christmas Snow Bride ('13) Patricia Richardson. Debbie Macom... 4:15 Wrath of ... I, Robot ('04) Will Smith. Taken 2 ('12) Liam Neeson. Boxing HBO After Dark Real Sports Behind the Candelabra Matt Damon. The Newsroom Down Ladies True Blood Movie (:50) Boardwalk Empire (:55) A Simple Plan Bill Paxton. This Is 40 ('12) Paul Rudd. Love It or List It HouseH House HouseH House Love It or List It Love It/ List It (N) HouseH House Ax Men Ax Men Pwn Star Pwn Star Pwn Star Pwn Star Pwn Star Pwn Star Pwn Star Pwn Star 4: A Very Mer... The Christmas Blessing A Country Christmas Story (N) Christmas Angel (:15) Warm Bodies Ocean's Twelve George Clooney. (:10) S. Back Orig Life of Pi Teen Mom 3 The Nightmare Before Christmas Snooki Snooki Step Up 2: The Streets Sponge Sponge Thunder. Hathawa Sam, Cat Sam, Cat Sam, Cat Hathawa Thunder. Thunder. Inst.Mom F.House Piranhaconda ('12) Michael Madsen. Lake Placid 3 ('10) Yancy Butler. Bering Sea Beast (P) Cassie Scerbo. (:15) Love and Honor Liam Hemsworth. Homeland On the Road ('13) Sam Riley. (:05) Masters of Sex (4:00) Training Day Cops Cops Cops Cops Cops Cops Cops The Departed (:05) King Arthur ('04) Clive Owen. (:15) Basic ('03) John Travolta. Dancing Edge (N) (:10) Spartacus: B Queens Queens Ray Ray Ray Ray BigBang BigBang BigBang BigBang BigBang BigBang Hoarding Hoarding Hoarding Untold Stories Untold Stories Untold Stories Movie (:35) Man on a Ledge (:20) Step Up Revolution The Frighteners Michael J. Fox. (4:30) Invincible The Longest Yard ('05) Adam Sandler. Rush Hour 3 ('07) Chris Tucker. Griffith Griffith Griffith Griffith Griffith Griffith Griffith Griffith Ray Ray Ray Ray NCIS "Dog Tags" NCIS "Toxic" Modern Modern Modern Modern Modern Modern Modern Modern 4:30 S.N.L Chrissy Love and Hip-Hop Crazy Sexy Cool: The TLC Story Diary of a Mad Black W... Law:CI "Beast" Bones Bones Home Videos Home Videos Home Videos On this date Nov. 9: • In 1872, fire destroyed nearly 800 buildings in Boston. • In 1938, Nazis looted and burned synagogues as well as Jewish-owned stores and houses in “Kristallnacht.” • In 1965, the great Northeast blackout occurred as a series of power failures lasting up to 13 1/2 hours left 30 million people in seven states and part of Canada without electricity. THE BORN LOSER BY ART & CHIP SANSOM 6:30 (3:30) Football NCAA MS St./Tex.A&M (L) Almanac • DEAR DOCTOR relationship won’t work if I can’t bring myself to be intimate with the person. In all my years of dating, I have been in love only twice. Any help would be appreciated. — LOST DEAR LOST: I DEAR wish I had a lamp ABBY magic that would give you what you’re Jeanne Phillips looking for in a puff of smoke, but I don’t. What I can offer is that you need to continue looking for someone who is as independent as you are, so you can find an attractive man whose needs are similar to yours. Some couples find the. DR. KOMAROFF is a physician and professor at Harvard Medical School. His website is AskDoctorK.com. Crossword Puzzle • kpcnews.com SATURDAY, NOVEMBER 9, 2013 B7 Kerry warns gaps remain in nuclear talks with Iran GENEVA (AP) — U.S. Secretary of State John Kerry warned Friday of significant differences between Iran and six world powers trying to fashion a nuclear agreement, as he and three European foreign ministers tried. Kerry arrived from Tel Aviv after meeting with Israeli Prime Minister Benjamin Netanyahu during which Kerry.” He told reporters, “There is not an agreement at this point in time.”. The six powers negotiating with Tehran are considering a gradual rollback of sanctions that have crippled Iran’s economy. In exchange they demand initial curbs on Iran’s nuclear program, including a cap on enrich- AP U.S. Secretary of State John Kerry shakes hands with European Union foreign policy chief Catherine Ashton before their meeting with Iranian Foreign Minister Mohammad Javad Zarif in Geneva Friday. ment to a level that can be turned quickly to weapons use. The six have discussed ending a freeze on up to D e K a l b , kpcnews.com L a G r a n g e , N o b l e a n d $50 billion (37 billion euros) in overseas accounts and lifting restrictions on petrochemicals, gold and other precious metals. HOMES / RENTALS S t e u b e n C o u n t i e s To ensure the best response to your ad, take the time to make sure your ad is correct the first time it runs. Call us promptly to report ■ any ❐ errors. ■ We ❐ reserve ■ ADOPT: A bright future awaits the child that blesses my home. Active, creative, financially secure woman seeks to adopt a baby. Expenses Paid. Call Sarah 1-855-974-5658 Kendallville Bridgeway Evangelical Church 210 Brian’s Place, East of Rural King Sat. • 10-4 Lots of Craft Vendors, Pumkin Rolls, Fudge, Cookies, &other Baked goods.Hillbilly Hot Dogs Adopt: Our hearts reach out to you. Loving cou ple seeks to adopt a newborn bundle of joy to complete our family and share our passions for cooking, travel & education. Please call Maria and John 888-988-5028 or johnandmariaadopt.com JOBS EMPLOYMENT ■ ◆ ■ ◆ ■ Drivers WEST NOBLE SCHOOL CORPORATION in Ligonier, IN is looking for substitute bus drivers. Training is included. Apply at: West Noble Transportation Office or call Kathy Hagen (260) 894-3191 ext. 5036 Factory seeking REWARD!-Reward for safe return of 3 adult dogs missing 10/30/13. (2) Shih Tzus, (1) Yorkie. Garwick’s the Pet People. 419-795-5711. garwicksthepet people.com. (A) BAZAARS Holiday Bazaar New Life Tabernacle 609 Patty Lane Kendallville Friday • 9 - 6 Sat. • 9 - 3 Call 260 347-8488 SEARCHING FOR THE LATEST NEWS? CLICK ON PFG Customized Distribution Call (260)343-4336, or (260)316-4264 Auditor NOTICES Delivery Drivers is adding Class A Drivers at the Kendallville Distribution Center. Scheduled dedicated regional teamroutes, four-day weekly delivery schedule. Guaranteed weekly pay & excellent benefits. EOE.) Drivers QUALITY AUDITOR CLASSIFIED full time and first shift. Must ensure high level customer service and communication skills. Must be able to correct quality issues and complaints. Must be able to analyze data, product specifications, formulate and document quality standards. Must be able to read blueprints and fill out SPC charts. Don’t want the “treasure” you found while cleaning the attic? Make a clean sweep ... advertise your treasures in the Classifieds. Please send resume and qualifications to: EMPLOYMENT EMPLOYMENT ■ ● ■ ● ■ ■ ❐ ■ ❐ ■ ■ ✦ ■ ✦ ■ General Health General FWT, LLC. A leading manufacturer of utility & telecommunication towers for over 50 years. Quality Auditor PO Box 241 Ashley, IN 46705 Minimum 3 years experience. Must be able to pass an AWS D1.1 certification. FITTERS/LAYOUT Must be able to read blueprints & obtain AWS certification. QUALITY ASSURANCE INSPECTORS Ultrasonic testing, mag particle testing & visual testing experience in weld inspection required. ■ ◆ ■ ◆ ■ Maintenance We are hiring for the following positions: Apply in person at: Kendallville Manor 1802❐Dowling ■ ■ ❐St.■ Kendallville, IN EOE ■ ❐ ■ ❐ ■ OR EMAIL RESUME TO hicksville@fwtllc.com OR FAX RESUME TO ■ ● ■ ● ■ •Slitter Operator We are not a mill or foundry. Our working conditions are great. Benefits include: 401(K), Health, Dental, Disability, Life Insurance and Bonus opportunities! Pay will be commensurate with experience. ■■■■■■■■■■■■■ General JOURNAL GAZETTE Routes Available In: Kendallville, Angola, & Wolcottville We love kids who love the outdoors! If you know a young person who has an outdoor story to tell, send the story and any photos to The Outdoor Page editor Amy Oberlin at amyo@kpcnews.net. UP TO $1000/ MO. Call 800-444-3303 Ext. 8234 Please include a daytime contact phone number. ■■■■■■■■■■■■■ photo EPRINTS R Hundreds of published and non-published photos available for purchase! ❊ ❊ Magic Coil Products Attn: HR Dept. 4143 CR 61 Butler, IN 46721 ■ ✦ ■ ✦ ■ Your connection to ❊ Go to: kpcnews. mycapture.com local and world news kpcnews.com aaaA Sudoku Puzzle Complete the grid so that every row, column and 3x3 box contains every digit from 1 to 9 inclusively. Novae Corporation is a growing trailer manufacturer with locations in Markle, Columbia City, and North Manchester, Indiana. With our continued growth comes the need for additional qualified individuals at our Markle and North Manchester facilities in the following positions: Mig Welders • Production welding experience of 2 or more years is required. • Ability to read blueprints, tape measures, and general knowledge of fabrication. Assembly/Final Finish • Experience in construction and assembly. • Experience in wiring, decking, axle installation, metal hanging, and roofing. • Applicants must possess an eye for detail and strive to produce a quality product. Shipping & Receiving • Forklift experience is preferred, but not required. • Ability to verify and keep records of incoming and outgoing shipments. • Prepare items (trailers and accessories) for shipment. Paint Automotive manufacturer in northeast Indiana has the following opening for a result-oriented Maintenance team member. • General knowledge of preparation and painting process. • Know how to use powder guns and gauges. • Ability to determine paint flow, viscosity, and coating quality by performing visual inspections. Must have extensive industrial electrical knowledge, mechanical aptitude, read/interpret electrical and electronic circuit diagrams and familiar with computers and programmable logic controllers. All applicants must have the following: • High School diploma or GED. • Ability to pass pre-employment drug test. • Ability to lift 80 lbs. on a regular basis. • Proven dependability. • Excellent work and attendance history. Experience with preventative maintenance programs and pneumatics. Must be able to work any shift. We offer a comprehensive benefit package including Medical, Dental, Vacation, 401K, Holidays and more. Novae Corp. is an equal opportunity employer and maintains a Drug and Alcohol Free Workplace for all employees. Job offers are contingent upon successful completion of a pre-employment drug screen, and employees must maintain compliance with the policy for the duration of employment. No phone calls please! Applicants that have already applied are still being considered. Qualified candidates should send their resume and salary requirements to: Applications can be submitted in person at: HUDSON INDUSTRIES ATTN: Human Resource Manager PO Box 426, Hudson, IN 46747 Jody.Blaskie@midwayproducts.com EOE EMPLOYMENT •General Labor Please respond via: APPLY IN PERSON AT 761 W. High Street Hicksville, OH 43526 419-542-1420 •Slitter Set-up / Helper •Crane Operator • CNA’s • LPN’s • RN’s Positions are for 1st and 3rd shifts and requires candidates to be able to pass a pre-employment physical and drug screen. Steel Service Center needs employees and is WILLING TO TRAIN for the following 1st and 2nd shift positions: •Barcoding WELDERS 419-542-0019 kpcnews.com Health “Residents First.. Employees Always..” EMPLOYMENT One Novae Parkway, Markle, IN or 11870 N - 650 E, North Manchester, IN DIFFICULTY: 4 (of 5) 11-09 or Online: adnum=80212245 B8 kpcnews.com SATURDAY, NOVEMBER 9, 2013 EMPLOYMENT Instructor ◆ ❖ ◆ ❖ ◆ WELDING INSTRUCTOR Maintenance EOE At Trine University Now Hiring - G&M Media Packaging is seeking a selfmotivated individual interested in working in a non-automotive environment to join our 2nd Shift maintenance team. The position will require you to have a proven background in trouble shooting automated equipment, carry out preventative and predictive maintenance programs and the ability to read prints and schematics when necessary to be able to trouble shoot electrical issues. A mechanical aptitude is a must, as it will be a very hands-on position. A background in metal stamping and tooling would definitely be a plus. The right individual must be willing to work overtime as needed and have demonstrated interpersonal skills and excellent attendance. You must be able to pass a drug screen and background check to be considered for the position. If you feel you fit the above qualifications and want to join a company that has competitive wages and excellent benefits, please reply via email to HR@gm-media packaging.com OR mail to: Human Resources P. O. Box 524 Bryan, Ohio 43506 ◆ ❖ ◆ ❖ ◆ ■ ❏ ■ ❏ ■ General Pokagon State Park is now hiring for winter seasonal help. Positions available include toboggan workers, rental room attendants and laborers. Wages begin at $8.06/hour. Must be available weekends and during the Christmas school break. Must be able to lift 50 lbs repetitively, be 18 years of age or older, have reliable transportation to work and be able to work outside for extended periods of time. Interested applicants should contact the Park Office for further information at: 260-833-2012 AGRIBUSINESS • Every Saturday The Star THE NEWS SUN THE HERALD REPUBLICAN Call 1-800-717-4679 today to begin home delivery! Hamilton Lake Ashley Appetit MAINTENANCE Bon Management TECH Company Help Wanted read up on the latest trends, technology and predictions for the future of farming. MOBILE HOMES FOR RENT Pokagon SP is an Equal Opportunity Employer ■ ❏ ■ ✦ ✦ Office ✦ ❏ ■ ✦ ✦ All Positions Please call: (260) 665-4811 to schedule an interview ❖ ❖ ❖ ❖ ❖ ❖ ❖ Security Security Officer Positions (Angola, Butler & Auburn Areas) $8.50 - $10.00 Securitas Security Services, USA is now accepting applications for Security Officers. We have open positions available in Angola, Butler & Auburn, IN. Some essential functions of the job include, but not limited to: Access control, observe and report suspicious activity, interior and exterior patrols. Qualified applicants must be at least 18 years of age, have a high school diploma or GED and must be able to pass a drug screen and background investigation. PLEASE APPLY AT: SECURITASJOBS .COM 260 436-0930 EOE/M/F/D/V Drivers Driver Trainees Needed Now! Learn to drive for US Xpress! Earn $800+ per week! No experience needed! CDL-Trained and Job Ready in 15 days! 1-800-882-7364 General EQUIPMENT FABRICATOR WANTED--2 years equipment fabrication or maintenance experience required. MIG and TIG welding skills required. Tools will be required. Starting scale $14-$18 based on aptitude scores and ex perience. Great Work Hours and Benefit Package. Career position, located in Ft. Wayne, IN. Indoor work w/ overtime. 260-422-1671, ext. 106. (A) PART TIME (Fill-In) RECEPTIONIST NEEDED Must have strong organizational skills & ability to multi-task and prioritize. Email resume to: resume.angola@ yahoo.com ✦ ✦ ✦ ✦ ✦ Sudoku Answers 11-09 GOBBLE UP ON SAVINGS AT ASHLEYHUDSON APTS! $99 Move-In Special 1 BR Apartments available Water, Sewer, Trash pickup, & Satellite TV service included in rent! Rental assistance available to those who qualify. Eligibility requirements: 62 years of age or older, disabled any legal age may apply. Rent based on all sources of income and medical expenses. FREE HEAT! AS THE TEMPERATURE GOES DOWN SO DOES OUR RENT DEPOSITS START AT $ 99! Thanksgiving Special Open House 2 Days Only Nov. 8th & 9th $200 off 2nd Month’s rent $0 Application Fee • Free Heat & Water • Pet Friendly Community CALL TARA TODAY! NELSON ESTATES STORAGE Auburn Inside winter RV storage $40.00 monthly. 260 920-4665 after 7pm%) OPEN HOUSES 1815 Raleigh Ave., Kendallville 46755 nelsonestates@mrdapartments.com mrdapartments.com BANKRUPTCY FREE CONSULTATION $25.00 TO START Payment Plans, Chapter 13 No Money down. Filing fee not included. Sat. & Eve. Appts. Avail. Call Collect: 260-424-0954 act as a debt relief agency under the BK code Divorce • DUI • Criminal • Bankruptcy HOME IMPROVEMENT All Phase Remodeling and Handyman Service - No Job too Big or Small !!! Free Estimates Call Jeff 260-854-9071 Qualified & Insured Serving You Since 1990 General Practice KRUSE & KRUSE,PC ROOFING/SIDING 260-925-0200 or 800-381-5883 A debt relief agency under the Bankruptcy Code. FREE ESTIMATES POLE BUILDINGS We Build Pole Barns and Garages. We also re-roof and re-side old barns, garages and houses. Call 260-632-5983. (A) County Line Roofing Tear offs, wind damage & reroofs. Call (260)627-0017 CHILD CARE ALBION Child Care available in smoke-free home. Close to schools & factories. 1st shift & after school Availability (260)564-3230 HOMES FOR RENT Angola Pine Canyon Lake 4 BR, 3 1/2 BA 4077 Sq. Ft. • 1000 Sq. Ft. deck. • 382 ft. Lake front, Year round rental, non sports lake. Beautiful home! $1,350. (843)450-7810 up to $1000.00 Antique & Collectible Show National Guard Armory 130 West Cook Rd. Ft. Wayne, IN Sat. Nov 9 • 10-5 Sun. Nov 10 • 10-4 $2 Admission Free Parking FURNITURE 2ND BEST FURNITURE Thurs & Fri 10-5, Sat 8-3 8451 N. S.R. 9 1 MILE N. OF 6 & 9 Brand NEW in plastic! QUEEN PILLOWTOP MATTRESS SET Can deliver, $125. (260) 493-0805 Very nice dining room table, 6 chairs, custom pad, 2 leaves. $325. 260-495-4124 BUILDING MATERIALS Angola-Crooked Lake $500 mo.+ Deposit, New Flooring/ No pets 432-1270/ 624-2878 Auburn Land contract, 3 BR garage, $500/mo. 260 615-2709 Kendallville 353 N. Main St. 3 BR $640/mo. + dep. & util. 318-5638 Waterloo Land contract, 3 BR garage, $450/mo. 260 615-2709 KPC Contest FARM/GARDEN MOBILE HOMES FOR SALE Garrett MOBILE HOMES FOR AS LOW AS $550.00 A MONTH - LEASE TO OWN! WE HAVE 2 & 3 BR TO CHOOSE FROM. WE ALSO DO FINANCING. CALL KATT TODAY 260-357-3331 REALLY TRULY LOCAL... KPC Phone Books Steuben, DeKalb, Noble/LaGrange Poulen Chain Saw 14” works good, $25.00. Butler, (260) 760-0419 Junk Auto Buyer ANTIQUES 260 349-2685 Kendallville OPEN HOUSE 230 E. RUSH ST. SUNDAY, NOV. 10 1-4 The character of an old home with modern updates. Original wood floors, NEW windows, carpet, stainless appliances, bathroom & siding. 1650 sq. ft. main floor laundry & master BR. 2 large BR up, corner fenced lot w/driveway. $98,500. 260 760-5056 8 - 1 gal. Glass Jugs. No chips or cracks. Clean, ready to use. $40.00. Call or text, (574) 535-3124 IVAN’S TOWING All species of hard wood. Pay before starting. Walnut needed. GARAGE SALES BUSINESS & PROFESSIONAL Cromwell Now Leasing Crown Pointe Villas Call (260) 856-2146 Handicap Accessible Equal Housing Opportunity “This institution is an equal opportunity provider, and employer.” SETSER TRANSPORT AND TOWING ATTENTION: Paying up to $530 for scrap cars. Call me 318-2571 TIMBER WANTED Auburn $99 First Month 2BR-VERY NICE! SENIORS 50+ $465 No Smokers/ No Pets (260) 925-9525 MERCHANDISE UNDER $50 7' artificial Christmas tree w/standgreat condition $100 260-927-0221 WANTED TO BUY ASHLEY 506 South Union St. $500 before 11/10/13. $550 after • 668-4409 MERCHANDISE UNDER $50 MERCHANDISE HR Quinton Fitness Treadmill/Club Track 510. Asking $350. text - 260 349-2793 Angola ONE BR APTS. $425/mo., Free Heat. 260-316-5659 AUTOMOTIVE/ SERVICES USED TIRES Cash for Junk Cars! 701 Krueger St., K’ville. 260-318-5555 EXERCISE EQUIPMENT Auburn 260-349-0996 Avilla 1 & 2 BR APTS $450-$550/ per month. Call 260-897-3188 AT YOUR SERVICE Kendallville 1206 N Lima Rd. (SR3) Fri -Sat • 9-5 Household, Tools, (some old), Player Piano, DBL Garage door w/ track, Lawn Equip. & Lots of Miscellaneous! Wolcottville 2 & 3 BR from $100/wk also LaOtto location. 574-202-2181 Ashley Hudson Apartments 830 W. State St. Ashley, In 46705 260-587-9171 For Hearing Impaired Only, Call TDD # 1-800-743-3333 This institution is an Equal Opportunity Provider & Employer. NOW OFFERING WEEKLY RENTALS! GARAGE SALES Hamilton Lake 2 BR, updated, large kitchen & LR, one block to lake, nice park, others available. $450/mo. (260) 488-3163 HOMES has an opening for Welding Instructor ❖ ❖ ❖ ❖ ❖ ❖ Restaurants RENTALS Impact Institute APARTMENT RENTAL STUFF EMPLOYMENT APPLES & CIDER Mon.-Sat. • 9-5:30 Sun. • 11-5 GW Stroh Orchards Angola (260) 665-7607 (260) 238-4787 CARS 2008 Dodge Caliber 4 DR, White, Looks Brand New $6500 Call 897-3805 2007 Cadillac DTS 49,500 mi, good cond., white pearl, new brakes $13,500/OBO Call Bret @ 260 239-2705 2003 Chevy Blazer LS 4 x 4, Blk, V6, Fact. Mag Wheels, ABS, CD, No rust, Very Good Cond.. $4950 /obo (260) 349-1324 1998 Olds Achieva 136,000 miles, Exc. cond. $2100/ obo (260)316-5450 1 & ONLY PLACE TO CALL--to get rid of that junk car, truck or van!! Cash on the spot! Free towing. Call 260-745-8888. (A) Indiana Auto Auction, Inc.--Huge Repo Sale Thursday, Nov. 14th. Over 100 repossessed units for sale. Cash only. $500 deposit per person required. Register 8am-9:30am to bid. No public entry after 9:30am. (A) TRUCKS 98 Ford F150XLT 4X4 4.6 V8, Miles 150,000, Auto/Air/Tilt/Cruise/ Pr.Windows/Locks Good Tires: $3900 Blakesley Auto Sales 260-460-7729 SUV’S MOTORCYCLES 1997 Harley Davidson 1200 Sportster, 26k mi. $3,500/obo 260 668-0048 PETS/ANIMALS MERCHANDISE UNDER $50 Coton de Tulear Puppies, Ready for Christmas, all white, 5 males. Call 260 668-2313 10 gal. Reptile Terrarium includes 2 lights, temp gauge & cover. $30.00 obo. Call or text, (260) 573-6851 FREE to good home: Kittens 12 weeks old, 1 Male, 1 Female , prefer to adopt together. (260) 349-9093 100 Firearm Publications. $20.00 for all. (260) 837-4775 SNOW EQUIPMENT Buhler Allied snowblower Model 6010 3 point hitch $1400.00 (260)337-5850 11 Boxes 20 ga. Slugs. $40.00 with belt (260) 349-3437 12’ Metal Single Person Tree Stand. $50.00. (260) 349-3437 13” RCA Color TV with Remote, $10.00. (260) 243-0383 1976 “Uncle Sam” Complete Set Bicentennial 7-Up Cans. $50.00. (260) 347-2291 WHEELS EMPLOYMENT AUTOMOTIVE/ SERVICES $ WANTED $ Junk Cars! Highest prices pd. Free pickup. 260-705-7610 705-7630 3 - 1 gal. Glass Jugs. 1 green, 2 brown, 1 brown has crack. Clean. $25.00. Call or text, (574) 535-3124 3 New 5”x5” Conabear Traps. $20.00. (260) 349-3437 4 ft. Christmas Tree in box & 2 boxes decorations & lights. $20.00. (260) 242-2689 Antique Single Bottom Plow. All metal except handles. $50.00. (260) 347-3388 Baby Bouncer Seat with netting, $5.00. Call or text, (260) 336-2109 Basket For Steps Very nice, clean. $15.00. (260) 927-5148 Casio Electric Piano. Model CTK-700. $50.00. Text for pic. (260) 573-9116 Chair. Good cond. Clean. No smoke, no dogs. Beige/gold with pattern. $45.00. (260) 349-1607 Collection of Cookbooks. All for $29.00 (260) 833-4232 Princess Diana Porcelain collectors doll, in box, $25.00. (260) 925-2579 Quilter Frame for hand quilting. $50.00. (260) 837-4775 Red Crushed Velvet, swivel, rocker chair. Good cond. $40.00. (260) 925-1125 Round Kerosene Heater. $40.00. (260) 837-4775 Round Table with 4 chairs, 2 leaves. Medium wood color. Call or text, (260) 336-2109 Sauder TV Entertainment Center with glass side shelves and drawers for CD/tapes. Opening for TV is 36wx24t. $50.00. (260) 349-2689 Colts Shower Curtain & Rug. Very nice, $25.00. (260) 927-5148 Set of Four Michelin Exalto A/S 205/50/R17 with good tread. $50.00. (260) 410-9600 Craftsman 1 1/2 h.p. Router with lite and 15 bit set. $35.00. (260) 833-2362 Sled with Ice Skates & Wreath attached. $25.00. (260) 347-0951 Craftsman 10” Mitre Chop Saw with 104 Tooth Blade, $45.00. (260) 833-2362 Craftsman 10” Variable Speed Band Saw, 3 blades, 2 sanding belts. $40.00. (260) 833-2362 Dark Brown Lined Trench Coat style. Size medium. Never worn. $10.00. (260) 414-2334 Desk with chair 41”lx31”hx18”d. Very nice, clean. $45.00. (260) 927-5148 Exercise Bicycle $15.00 (260) 925-2579 Exotic African Tree 4’ Very different, $15.00 (260) 927-1286 Extra large box material for crafts or quilts. $15.00. (260) 242-2689 Glass Top Electric Kitchen Range. Almond color, $45.00. (260) 854-2253 Glider Chair Bought from Vans in 2008. $45.00 (260) 927-1286 Homelite Electric Hedge Trimmer. Like new, $15.00. (260) 347-2291 Hot Point Refrigerator 18.5 cu. ft. Asking $40.00. (260) 833-1049 Larin 3 lb. Sausage Stuffer. 3 tubes in box. $30.00. (260) 349-3437 Like New Black Moby Wrap/Carrier $20.00. Call or text, (260) 336-2109 London Fog Winter Dress Coat, size 42. Gray, $25.00. Butler, (260) 760-0419 London Fog Winter Dress Coat, size 46. Tan, $25.00. Butler, (260) 760-0419 Longaberger Bread Basket. 1999 warm brown basket w/American Holly liner & protector. Great cond. $29.00. (260) 833-4232 Longaberger Sleigh Basket with liner & fabric. $25.00. (260) 347-0951 Maple Jenny Lind Crib No mattress, $20.00. (260) 833-2362 McCoy Kettle Jar & 3 matching dishes. $20 (260) 347-0951 Mens Slacks Size 38x30, 3 pair. $6.00. (260) 347-6881 Motorcycle Seats from a 2002 Honda Ace 750. Very good cond. $50.00. (260) 238-4285 Moving Picture Projector/Outside. 10 slides all season/holidays/nice for garage door, etc. $10.00. (260) 925-4570 Nice Oval Mirror on a wood stand. $40.00. (260) 761-3031 Office Desk Chair Good cond. $12.00 (260) 927-1286 Older Sewing Machine in cabinet. Works good, Fleetwood. $35.00. Butler, (260) 760-0419 4 Kasey Kahne pictures and coaster set. $50.00 obo. (260) 553-0709 Pair of 2675/65/18 Tires. Good shape, $50.00. (260) 768-9122 7 1/2 ft. Pre-lite Concord Fir pine Christmas tree. $35.00. (260) 318-4950 Poulan Pro Gas Blower/Vac. Brand new, used once. $50.00. (260) 665-5193 Sofa. Good cond. Clean. No smoke, no dogs. Beige/gold. $50.00. (260) 349-1607 Solid Oak Framed Cabinet & Shelves on casters.33”hx28”wx19”d $30.00. Fremont, (260) 243-0383 Solid Oak Framed Coffee Table with 2-sectioned tempered glass top. 4’Lx2’wx16”h. $40.00. Fremont, (260) 243-0383 St. Michaels Church Centennial Plate, $10.00. (260) 837-4775 Steel Toe Boots 9W Used little, w/Guards, black. $20.00 Butler, (260) 760-0419 Swivel Straight Christmas Tree Stand. $5.00. (260) 318-4950 TV Stand. Fits up to 52”. 2 shelves. $40.00. Wolcottville, (260) 854-9305 Twin Mattress $5.00. Fremont, (260) 243-0383 Very nice TV Cabinet with extra storage. Only $50.00. (260) 316-4606 W.W.II Wood Shipping Crate Box, $50.00. Text for pic. (260) 573-9116 Woman’s Black Leather 3/4 length coat. Size M. $20.00 cash only (260) 357-3753 Womans Brown Dansko shoe, Mary Jane style. Size 8 1/2-9. $35.00. (260) 318-4950 Wood Desk. 48x30, 2 drawers, removable shelves. $20.00. (260) 347-2291 Yard Swing Good cond., $50.00 (260) 243-8671. “You’vgeot news!” Every print subscription includes online access to kpcnews.com The News Sun is the daily newspaper serving Noble and LaGrange counties in northeast Indiana.
https://issuu.com/kpcmedia/docs/ns11-09-13?e=4200578/5558945
CC-MAIN-2018-22
refinedweb
22,255
76.11
2008-09-29 22:30:28 8 Comments How can I create an Excel Spreadsheet with C# without requiring Excel to be installed on the machine that's running the code? Related Questions Sponsored Content 26 Answered Questions [SOLVED] How do I enumerate an enum in C#? - 2008-09-19 20:34:50 - Ian Boyd - 663584 View - 3379 Score - 26 Answer - Tags: c# .net enums enumeration 17 Answered Questions [SOLVED] How do I tell if a regular file does not exist in Bash? 24 Answered Questions [SOLVED] Cast int to enum in C# 38 Answered Questions [SOLVED] How do I properly clean up Excel interop objects? - 2008-10-01 17:18:43 - HAdes - 285468 View - 701 Score - 38 Answer - Tags: c# excel interop com-interop 38 Answered Questions [SOLVED] How do I get a consistent byte representation of strings in C# without manually specifying an encoding? - 2009-01-23 13:39:54 - Agnel Kurian - 1131080 View - 2032 Score - 38 Answer - Tags: c# .net string character-encoding 12 Answered Questions [SOLVED] How do I force my .NET application to run as administrator? - 2010-05-12 11:09:50 - Gold - 404536 View - 788 Score - 12 Answer - Tags: c# .net windows-7 administrator elevated-privileges 30 Answered Questions [SOLVED] How do I create a file and write to it in Java? 41 Answered Questions [SOLVED] Deep cloning objects 10 Answered Questions [SOLVED] Should 'using' directives be inside or outside the namespace? - 2008-09-24 03:49:50 - benPearce - 174880 View - 1854 Score - 10 Answer - Tags: c# .net namespaces stylecop code-organization @Leniel Maccaferri 2009-06-20 20:48:26 I've used with success the following open source projects: ExcelPackage for OOXML formats (Office 2007) NPOI for .XLS format (Office 2003). NPOI 2.0 (Beta) also supports XLSX. Take a look at my blog posts: Creating Excel spreadsheets .XLS and .XLSX in C# NPOI with Excel Table and dynamic Chart @John M 2010-04-30 13:45:52 A note on NPOI - Row and Column references are zero-based. Does work well for populating an existing template. @Mike Webb 2010-04-08 21:36:03 You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code: ExcelLibrary's also NPOI which works with both. Lesser General Public License (LGPL) NPOI - Apache License Here some example code for ExcelLibrary: Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom: Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me. @Mark A 2010-11-04 00:11:19 ExcelLibrary has been superseded by the exceptional EPPlus - epplus.codeplex.com. Jan updates it regularly. Have been using it and it is one of the finest open source projects we've worked with. @rossisdead 2011-10-18 23:17:34 It should be noted that ExcelLibrary has a lot of performance issues when dealing with large datasets(larger than 5000 rows with lots of columns). Currently doing a heavy modification of the code base at work so we can use it in a project. @Seth 2012-01-26 23:21:17 EPPlus seems far less buggy than ExcelLibrary, BUT it is GPL and therefore only a solution for open source projects. @ta.speot.is 2014-02-22 09:44:02 -1 If you're going to post sample code you might as well make sure it's correct. Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed. @Beep beep 2015-01-27 20:48:09 EPPlus is actually still technically GPL because it is a derived work (i.e. the code base is still based off of ExcelLibrary, and since that is GPL so is EPPlus ... you can't make some changes to GPL code and slap a LGPL license on it). Does anyone know of a way to write to Excel using either commercial code or true LGPL (or similarly licensed code). @Chris 2015-10-28 15:06:41 ExcelLibrary doesn't work anymore. If you want to write Excel 2003 files (.xls) this library is working great: CSharpJExcel sourceforge.net/projects/jexcelapi Make sure to download the C# port. @Amadeus Sánchez 2015-11-30 18:10:23 What about ClosedXML? I may prove to be useful in your projects. @Kiquenet 2016-07-15 11:44:25 Maybe aspose.com/products/cells or gemboxsoftware.com/spreadsheet/overview @Shubham 2019-01-04 05:17:40 check this out no need for third party libraries you can simply export datatable data to excel file using this @Rup 2019-01-04 09:44:10 That generates a tab-separated file and saves it with an .XLS extension so that it gets opened by Excel. It's not a real Excel file, and you can't include formatting etc. There are similar answers here which try the same trick with HTML and the wrong extension. @Vijay Dodamani 2018-11-05 07:46:39 To save xls into xlsx format, we just need to call SaveAsmethod from Microsoft.Office.Interop.Excellibrary. This method will take around 16 parameters and one of them is file format as well. Microsoft document: Here SaveAs Method Arguments The object we need to pass is like Here, 51 is is enumeration value for XLSX For SaveAs in different file formats you can refer the xlFileFormat @Rup 2018-11-05 14:45:29 There's an old answer about using Office Interop too. @AlexDev 2017-12-07 20:40:09 One really easy option which is often overlooked is to create a .rdlc report using Microsoft Reporting and export it to excel format. You can design it in visual studio and generate the file using: You can also export it do .doc or .pdf, using "WORDOPENXML"and "PDF"respectively, and it's supported on many different platforms such as ASP.NET and SSRS. It's much easier to make changes in a visual designer where you can see the results, and trust me, once you start grouping data, formatting group headers, adding new sections, you don't want to mess with dozens of XML nodes. @ScaleOvenStove 2010-07-09 19:21:26 You can just write it out to XML using the Excel XML format and name it with .XLS extension and it will open with excel. You can control all the formatting (bold, widths, etc) in your XML file heading. There is an example XML from Wikipedia. @Francois Botha 2010-09-22 16:03:52 This is cool except it doesn't support charts or images. @ 2009-10-22 15:21:25 I also vote for GemBox.Spreadsheet. Very fast and easy to use, with tons of examples on their site. Took my reporting tasks on a whole new level of execution speed. @Nick 2008-09-30 00:53:38 The Java open source solution is Apache POI. Maybe there is a way to setup interop here, but I don't know enough about Java to answer that. When I explored this problem I ended up using the Interop assemblies. @Harsha.Vaswani 2015-07-23 07:55:17 I have written a simple code to export dataset to excel without using excel object by using System.IO.StreamWriter. Below is the code which will read all tables from dataset and write them to sheets one by one. I took help from this article. @Rup 2015-07-23 09:39:24 Like the article says though, that's XML that Excel will read rather than actually being an XLS file, which means that it might only work in Excel and not other programs that read spreadsheets. But it's probably better than the equivalent HTML table answers here! @Kiquenet 2017-02-16 14:52:13 Supports xlsx ? OpenXML ? @EMP 2009-02-15 08:12:37. @biozinc 2008-11-24 08:22:41. @liya 2009-12-03 08:08:22 This one works on both .net and java,and is not expensive. SmartXLS smartxls.com @ManiacZX 2008-09-29 22:48:00 You may want to take a look at GemBox.Spreadsheet. They have a free version with all features but limited to 150 rows per sheet and 5 sheets per workbook, if that falls within your needs. I haven't had need to use it myself yet, but does look interesting. @Davis Jebaraj 2016-10-07 18:03:31 Syncfusion Essential XlsIO can do this. It has no dependency on Microsoft office and also has specific support for different platforms. Code sample: The whole suite of controls is available for free through the community license program if you qualify (less than 1 million USD in revenue). Note: I work for Syncfusion. @Sam Warwick 2008-09-30 01:16:40 You could consider creating your files using the XML Spreadsheet 2003 format. This is a simple XML format using a well documented schema. @Manuel 2010-11-23 16:33:00 If you're creating Excel 2007/2010 files give this open source project a try: @Druid 2011-06-08 12:40:24 I tried using this in a project that builds pretty large Excel sheets. Excellent library, but extremely poor in performance. I just did a comparison for the project I'm working on: ClosedXML (v 0.53.3) took 92,489 ms whereas EPPlus (v 2.9.03, for testing - we can't use because it's GPL) took 16,500 ms. @Chris Marisic 2015-08-12 16:08:27 @Druid the license is LGPL assuming you don't modify the source code to ClosedXML it is free to use epplus.codeplex.com/license @GEOCHET 2008-09-29 22:34:23 You actually might want to check out the interop classes. You say no OLE (which this isn't), but the interop classes are very easy to use. You might be impressed if you haven't tried them. Please be warned of Microsoft's stance on this: @MagicKat 2008-09-29 22:40:28 But you have to make sure that you dispose of everything manually, otherwise you will leak memory @MagicKat 2008-09-29 22:42:57 @Ricky B: Also, in my experience with the interop is that it does use excel. Every time we used it, if Excel wasn't installed on the machine, we would get COM exceptions. @Jennifer Zouak 2010-03-09 21:54:00 With the OLE, even with very careful disposals, it eventually leaks memory or crashes. This is argueably OK for attended applications/ workstations, but for servers is not recommended (MS has a KB stating this). For our server, we just reboot it nightly. Again, that works OK. @Jennifer Zouak 2010-03-11 17:49:53 @Geoffrey: ah OK you are going to make me work for it :) --> support.microsoft.com/kb/257757 Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application... @md1337 2011-02-03 18:52:15 I'm coming to this discussion after struggling more than a week on interop, and unless your needs are very simple, this is not gonna work. The support for formatting your spreadsheet is abysmal, which is arguably the reason for generating an .xls file and not just a flat .csv file. For example, have you tried outputting more than 911 characters in a cell, or have you tried setting the width of merged cells in a consistent manner? I have, and I can't tell you how much I hate this crap now... Do yourself a favor and go with one of the free libraries mentioned on this discussion. @pkuderov 2013-05-13 15:11:30 I haven't changed Interop for EPPlus yet (but already on the half way) so I don't really know how much better life is with it, but dealing with Interop I got so much pain in very surprising cases nearly every time I needed something more complex than just create .xls/.xlsx file with simple table inside. And mentioned above 'twice-check-to-dispose-everything-magic' is one of that everyday pain. But yeah, it works, and most of the time it's enough. @Petr Snobelt 2009-02-12 15:04:46 You can use ExcelXmlWriter. It works fine. @Nate 2009-06-01 15:45:06 A few options I have used: If XLSX is a must: ExcelPackage is a good start but died off when the developer quit working on it. ExML picked up from there and added a few features. ExML isn't a bad option, I'm still using it in a couple of production websites. For all of my new projects, though, I'm using NPOI, the .NET port of Apache POI. NPOI 2.0 (Alpha) also supports XLSX. @Jeremy 2010-09-17 13:55:24 Be careful with ExcelPackage if you need to support XLS. I had a hard time with it and eventually switched to ExcelLibrary. @Nate 2010-09-21 15:16:28 Definitely true. ExcelPackage/ExML is only a good option if you need the XLSX support. @Pragmateek 2013-11-03 19:00:31 Note that ExcelPackage has a successor: EPPlus (epplus.codeplex.com) which supports XLSX. My only concern, compared to NPOI for example, is performance, e.g. when there is a lot of columns. @Joe Erickson 2009-01-24 18:33:17 The commercial solution, SpreadsheetGear for .NET will do it. You can see live ASP.NET (C# and VB) samples here and download an evaluation version here. Disclaimer: I own SpreadsheetGear LLC @md1337 2011-02-03 18:43:19 You have a great product but I think a lot of people here are expecting free solutions. That might explain the down votes. @Panos 2008-09-29 22:41:09 You can use OLEDB to create and manipulate Excel files. Check this: Reading and Writing Excel using OLEDB. Typical example: EDIT - Some more links: @Lamar 2008-09-30 01:45:11 Can someone confirm if this works when running in x64? I am pretty sure Jet only works if your app is compiled or running in 32-bit mode. @Chris Richner 2009-06-16 07:31:19 I've just tested this connection and it failed on a Windows Server 2008 R2 x64 RC, seems like one have to install the 2007 Office System Driver: Data Connectivity Components [microsoft.com/downloads/… @dbkk 2009-09-29 09:02:22 Be very careful with this -- it's a big ugly cludge (for example, sometimes it guesses a column type and discards all the data that does not fit). @Kenny Mann 2010-06-09 16:03:29 One should be very careful if using this method. I've found it very flaky for data that isn't in a perfect format. @Caner Öncü 2014-09-13 18:32:16 As a person who had to use OleDb in a big project, I say STAY AWAY FROM IT! It sometimes is not able to retrieve a cell value just because it couldn't understand the format. It doesn't have a delete operation. It works totally different and unpredictable even with a slightest provider change. I'd say go for a proven commercial solution. @Justin 2016-05-05 21:36:31 Microsoft has upgraded Jet, try this link stackoverflow.com/questions/14401729/… @Stephen G Tuggy 2016-07-09 05:33:12 At a previous job, we used Microsoft Access Database Engine 2010 Redistributable. It took the form of an OLEDB driver that allowed reading from and writing to Excel files, as well as Access format files. Note that this download does not require you to install the entire Office suite. Note also that it comes in both 32-bit and 64-bit flavors. It is very important that you match the 32-bit or 64-bit version to the architecture of the host process that will access the file(s). In our case, the host process was SSIS. @Pellared 2011-08-16 09:25:58 And what about using Open XML SDK 2.0 for Microsoft Office? A few benefits: Links: @Josh Brown 2011-09-20 13:03:06 Important to note that the DLL for this is just over 5 MB and limited to Office 2007 formats. But certainly the easiest and fastest solution which works for me. @Snuffleupagus 2013-01-04 16:47:11 Just a heads up that v2.5 is out and can be downloaded here. @Tsahi Asher 2014-12-24 16:27:57 The SDK models the XML into classes, so that each XML tag is mapped to a tag, and then you have to build the class hierarchy (each instance has a collection of child instances/tags) correctly. This means you have to know the XML structure of an Excel file, which is very complicated. It's much easier to use a wrapper such as EPPlus, mentioned above, which simplifies things. @Greg 2017-02-17 17:51:38 A great sample of Microsoft Open XML SDK - Open XML Writer can be found at polymathprogrammer.com/2012/08/06/… Or see Stack Overflow solution stackoverflow.com/questions/11370672/… @Greg 2017-02-17 17:54:49 I found Microsoft Open XML SDK's Open XML Writer to be great. Using the solutions above, (Especially Vincent Tom's sample (Poly Math)), it's easy to build a writer that streams through big sets of data, and writes records in a manner similiar and not too much more complex to what you'd do for CSV; but that you're instead writing xml. Open XML is the mindset that Microsoft considers it's new Office formats in. And you can always rename them from .xslx to .zip files if you feel like poking at their XML contents. @horeaper 2018-05-30 23:37:44 Please note that Open XML SDK are now open source and hosted on github. Also you don't need to install the SDK, just fire-up nuget and DocumentFormat.OpenXml is all you need. It works with .net standard 1.3. @Jan Källman 2010-03-29 12:25:54 If you are happy with the xlsx format, try my codeplexGitHub project. EPPlus. Started it with the source from ExcelPackage, but today it's a total rewrite. Supports ranges, cell styling, charts, shapes, pictures, namesranges, autofilter and a lot of other stuff. @Mike Gledhill 2011-11-23 12:04:00 My completely-free library also lets you export any DataSet, DataTable or List<> directly into an Excel 2007 .xlsx file, using Open XML. Full source code, and demo, available here: mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm @Simon D 2012-02-05 12:30:14 License is now LGPL, release notes here: epplus.codeplex.com/releases/view/79802 @Paul Chernoch 2015-02-10 18:55:49 The examples were helpful. I was able to change my code from using Microsoft interop library (horribly slow) to this library (version 4.x) in a couple hours. My benchmark writes a file with two tabs and about 750,000 cells. Using MS interop it took 13 minutes. Using EPPlus it took 10 seconds, a roughly 80x speedup. Very happy! @PeterX 2015-02-24 03:39:45 @JanKällman You should update your CodePlex page to show you've got these methods available: LoadFromCollection<T>, LoadFromDataTableetc. (found via here) @Chris Marisic 2015-08-12 16:10:30 For clarity in this thread, the LGPL allows the software to be linked to without the infective part of the GPL occuring. You only need to open source changes you make to ClosedXml or if you directly put the source code (as opposed to referencing the ClosedXml assemblies) inside of your application then you need to open source your application. @Marc Meketon 2018-02-15 22:53:00 @Paul Chernoch: We populate large Excel sheets with interop very quickly. The secret is to do a bulk update. Create a object [,] block, populate that, then write that matrix to Excel at one time: excelWorksheet.get_Range(range).Value2 = block; @Vladimir Venegas 2017-09-27 15:18:35 Some time ago, I created a DLL on top of NPOI. It's very simple to use it: You could read more about it on here. By the way, is 100% open source. Feel free to use, edit and share ;) @Taterhead 2017-02-27 23:30:08: DesiredLook.xlsx. DesiredLook.xlsxand click the Reflect Code button near the top.where you can paste the generated code. If you go back one version of the file, it will generate an excel file like this: @TonyG 2018-07-26 16:34:27 I haven't tried this Open XML SDK solution yet but Wow, I will definitely check it out. I've worked with tools like this for many years and didn't know about this one. I've published my own simple FOSS for converting files to XLSX with .NET: github.com/TonyGravagno/NebulaXConvert @Gayan Chinthaka Dharmarathna 2017-04-05 09:00:59 If you make data table or datagridview from the code you can save all data using this simple method.this method not recomended but its working 100%, even you are not install MS Excel in your computer. @Mike Gledhill 2011-12-05 12:08:36 Here's a completely free C# library, which lets you export from a DataSet, DataTable: It doesn't get much simpler than that... And it doesn't even require Excel to be present on your server. @UrbanEsc 2017-01-23 15:33:19 This seems a bit misleading, as you are asking for a donation to get all of the features. @Mike Gledhill 2017-05-02 14:15:29 That's partly true: The completely free version will generate a perfect .xlsx file for you, and all source code is provided. If you donate $10 or more to one of those two charities (of which I receive absolutely nothing), then you get a "better" version showing how to do formatting, dates, etc. Given the cost of third-party products, I reckon donating $10 to a good cause instead is well worth it ! @mcalex 2019-02-01 04:47:19 NET::ERR_CERT_COMMON_NAME_INVALID as at January 2019 @Sachin Dhir 2015-12-02 13:30:28 OpenXML is also a good alternative that helps avoid installing MS Excel on Server.The Open XML SDK 2.0 provided by Microsoft simplifies the task of manipulating Open XML packages and the underlying Open XML schema elements within a package. The Open XML Application Programming Interface (API) encapsulates many common tasks that developers perform on Open XML packages. Check this out OpenXML: Alternative that helps avoid installing MS Excel on Server @saurabh27 2014-12-20 06:37:43 I am using following code for create excel 2007 file which create the file and write in that file but when i open the file but it give me error that exel cannot open the file bcz file might be coruupted or extension of the file is not compatible. but if i used .xls for file it work fines also refer link @Rup 2014-12-22 20:48:41 That all relies on your Contactclass, and you haven't told us what that is. If it works for xls then chances are you're actually writing out HTML which isn't a real Excel file. And your link is using interop, which as mentioned above shouldn't be used server-side and can be slow filling large tables. @saurabh27 2014-12-23 09:53:12 Contact is linkedlist not a class.declare a linkledist and used it because i haven't know the size of data so i used linkedlist. @Rup 2014-12-23 09:55:02 Oh, so you're producing a plain text file with one item per line? So Excel is treating it as a CSV without the commas? @Dimi Takis 2009-11-10 05:05:23 Well, you can also use a third party library like Aspose. This library has the benefit that it does not require Excel to be installed on your machine which would be ideal in your case. @Shahzad Latif 2011-08-29 11:55:55 To be more precise, you can use Aspose.Cells for .NET in order to create Excel (XLS, XLSX) files in your .NET application. @Mike Gledhill 2012-01-05 13:10:00 Yes you can, if you don't mind paying a minimum license fee of $999. Try the MikesKnowledgeBase library... which is $999 cheaper than this !! @user529824 2010-12-03 19:53:12 You can create nicely formatted Excel files using this library: See below sample: where sample look like this:
https://tutel.me/c/programming/questions/151005/how+to+create+excel+xls+and+xlsx+file+in+c+without+installing+ms+office
CC-MAIN-2019-13
refinedweb
4,141
72.97
This post is intended to serve as a basic guide to deploying Spark based APIs onHasura. By the end of this post, our codebase will have the following features: 1. API endpoint that handles a JSON request and responds in JSON 2. API endpoint that makes an API request (useful for say push notifications) 3. API endpoint that makes a HasuraDB request using the Hasura SDK 4. Dockerise the entire API server Setup Spark Instructions on setting up Spark with IntelliJ Add the following dependency to the pom.xml file of your project. <dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.5</version> </dependency> Then add to your java file. import static spark.Spark.*; Making a JSON API endpoint For JSON handling we use GSON. Instructions on using GSON Add the following dependency to the pom.xml file of your project. <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> Then add to your java file import com.google.gson.Gson; Object to JSON : Gson gson = new Gson(); String countryInJSON = gson.toJson(country) //country is an object. JSON to Object : Suppose we have a Json string which needs to be converted to the country object. Gson gson = new Gson(); country countryObj = gson.fromJson(countryInJSON,country.class); Find the sample code for the json api end-point. Making an API endpoint that queries an external API Instructions on using okhttp Add the following dependency to your pom.xml file. <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.3.1</version> </dependency> Then add the following to the respective java file. import java.io.IOException import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response In the code: (GetExample object).run(url) will return the body of the response obtained, and if there is an error in the url, throws an Exception. Making an API endpoint that uses HasuraDB Instructions on using HasuraDB SDK - Include the dependencies of bass-sdk-java in the build.gradle (or) any other build tool. Also add a hasura.javafile to your project. The instructions for the same can be found here . - Customize the hasura.propertieswith the respective values. - url :. your-project-name.hasura-app.io - adminAPIKey : You can find it after logging at. your-project-name.hasura-app.io - package : Your 'db' package where you want all the table classes. - dbprefix : /api/1 - dir : Path of your 'db' directory. - Run the task 'generate'. This will create all the table classes according to the schema. - To run the task 'generate'. Go to the build.gradle file. - Select the code block of the task. - Right click and then build it. - Refer this sample code making insert and select queries. Dockerizing your Spark server Instructions on using Docker build - Create a jar file of your java-project. In the IntelliJ IDE framework we can create a jar file by. - Select File > Project Structure > Articrafts > (add '+') > JAR > From Modules with dependencies. - Set the main class with the file where your main class lies and click 'Ok'. - Now select Build > Build Artificats... > Click on build. - This will create a directory with the jar file in the src/out/artifacts directory. - Write the dockerfile, you can find a sample one here . - Go to the directory containing the dockerfile and build your docker image. docker build -t <image-name> . - Run your docker image.
http://126kr.com/article/83pt706cmcz
CC-MAIN-2017-17
refinedweb
562
54.08
The F-words: functor and friends While algebras are something we (programmers) rely on in our everyday work, we don’t always use them knowingly. Functional programming, however, has a relatively high number of programmers, that care about correctness and mathematical formalism, that leads to it. It is no surprise that it was FP that explored the idea that if you perceive your program as a pipeline of operations, you could provide stronger guarantees if you had a tools to define such pipelines mathematically. Pipeline of values But let’s not rush into mathematical abstractions right from the start. Let start with some use cases, figuring out some common patterns and leave distilling mathematical models at the end, when we already gained some intuition. The simplest case is when we put some data into pipeline a get some data out of it. E.g. final case class User(name: String, surname: String) val getName: User => String = user => user.name val toUpper: String => String = str => str.toUpperCase val greet: String => String = name => s"Hello, $name!" Since these pipelines are function, we can combine them together by simple function composition. All we have to take care of is make sure the output of a preceding function matches the input of a succeeding one: val greetUppercased = getName .andThen(toUpper) .andThen(greet) .apply(User("John", "Smith")) // "Hello, JOHN!" val uppercaseGreet = getName .andThen(greet) .andThen(toUpper) val user = User("John", "Smith") greetUppercased(user) // "Hello, JOHN!" uppercaseGreet(user) // "HELLO, JOHN!" But, let’s say we have a List of things. And we want to apply our pipeline to each element, and receive a List of results. Imperative way of doing this would be: import scala.collection.mutable val users: List[User] = ??? val greetsMutable: mutable.List[User] = mutable.List.empty users.foreach { user => greetsMutable += greetUppercased(user) } val greets: List[String] = greetsMutable.toList Quite a lot of code, and it is easy to make a mistake (even easier if you use language allowing for (int i = 0; i < list.size; i++) ceremony). Besides, if we wanted to do this in steps: val users: List[User] = ??? // mutable stuff val names: List[String] = ??? // mutable stuff val greets: List[String] = ??? things would create even more boilerplate and make things even easier to break. Another possibility: if each of the operations in your would take some time, so it would make sense to avoid blocking, and run each of them on a thread pool. In Scala we can achieve it with Futures (and Promises). import scala.concurrent.{ Future, Promise } import scala.concurrent.ExecutionContext.Implicits.global import scala.util.{ Success, Failure } val userF: Future[User] = Future { /*user*/ } val greetP: Promise[String] = Promise[String]() userF.onComplete { case Success(user) => greetP.success(greetUppercased(user)) case Failure(error) => greetP.failed(error) } val greetF: Future[String] = greetP.future We can see that manual completion of a Promise is quite bolerplate-y and error-prone. What if we broke this into stages, just like with Lists? Here is makes more sense as it make things more granular on thread pool level. Again, we would end up with quite a lot of mess. The last case we’ll consider: let’s say we had some sort of validation, the simplest data structure for that would be Either. By convention the correct (or right) values go into the Right type parameter, while errors are what is left if something went wrong, so they end up in Left type parameter. Let’s say we don’t want to change our error type while we go though the stages of our pipeline and the input is already validated. We don’t intend to invalidate it, so we want to have some code like: // here error is stored as String val validatedUser: Either[String, User] = ... val validatedGreet: Either[String, String] = validatedUser match { case Right(user) => Right(greetUppercased(user)) case Left(error) => Left(error) } What each of these cases have in common? - each time we have some Container[A]that we want to turn into Container[B]using A => Bfunction. The container can contain 0, 1 or more values of Atype and feeds it into our function, so we can also consider it as a data source, which ensures that the result will be embedded in the same type of Containeras the source, - each time we process one value at a time and return exactly one result - we don’t want to consider case like a missing results, failing Future, etc., - while have an implicit assumption that whether we run transformations in stages or pass whole composed function at once, the result will be the same. In mathematics a relation between input and output is called a map, and in many contexts it is virtually equal to a function. So assigning each value in a container a corresponding value would be called mapping. That is why a method that maps container is called a map: val users: List[User] = ??? val greets: List[String] = users.map(greetUppercased) val userF: Future[User] = ??? val greetF: Future[String] = userF.map(greetUppercased) val validatedUser: Either[String, User] = ??? val validatedGreet: Either[String, String] = validatedUser.map(greetUppercased) The abstraction we arrived at is called a functor. Let’s formalize our finding. Functor Let’s take a type constructor F[_]. Let’s assume that each type A can be lifted F[A] and each function A => B can be lifted to F[A] => F[B]. We also put some constraints on how we lift things: - lifting of an identity[A]to F[A] => F[A]always behave the same as identity[F[A]]( identityis a function returning input unchanged), - lifting of an f andThen gbehaves the same as lifting of fcomposed with lifting of g. If we use a notation that lifting if a function is implemented using map method of a fa: F[A] (so fa.map(f): F[B]), we can express these laws with: fa.map(identity) == identity(fa)for each fa fa.map(f).map(g) == fa.map(f.andThen(g)). These constraints are called functor laws and F[_] that is following them we call a functor (or covariant functor). You can see the idea illustrated using the diagram quite known for people in touch with category theory: A -- F --> F[A] | | f F[f] | | V V B -- F --> F[B] (Trivia: functor lifts A →F(A). If you reversed the arrow A←F(A) you would get an F-algebra). Let’s check if structures we used so far can be considered functors. List[_] can lift ant A to List[A]. It also allows us to lift function A => B to List[A] => List[B] using map: val times2: Int => Int = i => i*2 val asString: Int => String = i => i.toString List(1,2,3).map(identity) // List(1, 2, 3) identity(List(1,2,3)) // List(1, 2, 3) List(1,2,3).map(times2).map(asString) // List("2", "4", "6") List(1,2,3).map(times2 andThen asString) // List("2", "4", "6") As we can see functor laws hold for List[_]. How about Either[_]? Left[String, Int]("failed").map(identity) // Left("failed") identity(Left[String, Int]("failed")) // Left("failed") Right[String, Int](2).map(identity) // Right(2) identity(Right[String, Int](2)) // Right(2) Left[String, Int]("failed").map(times2).map(asString) // Left("failed") Left[String, Int]("failed").map(times2 andThen asString) // Left("failed") Right[String, Int](2).map(times2).map(asString) // Right("4") Right[String, Int](2).map(times2 andThen asString) // Right("4") It seems functor laws hold also for Either - while only Right side changes its actual values (which is why we say that Either is Right-biased), both Left and Right act in a way preserving Either’s lawfulness. But let’s check something that is not a functor and try to illustrate why. val isEven: Int => Boolean = i => i%2 == 0 def getRandom: Boolean => Int = { val r = new java.util.Random(0) _ => r.nextInt } Set(1,2,3,4).map(isEven).map(getRandom) // Set(-1155484576, -723955400) Set(1,2,3,4).map(isEven andThen getRandom) // Set(-1155484576, -723955400, 1033096058, -1690734402) As we can see when side effects and state come into the picture, Set[_] comes unlawful. Here, we simulated what would happen in case our invisible state (content of Random) behaves the same way in both cases (here: starts with the same seed). We end up with different results - in first one four results of first mapping collapse into 2 results and then these 2 results are mapped further. In seconds case we don’t give a chance to collapse on intermediate results, so we end up with 4 element set. This shows one example where lawfulness matters - functions with side effects, should compose without violating our assumptions, even implicit ones. Applicative functors So far we have a wrapper/container and a value inside. We can take some function, lift it to function taking and returning wrapper and that’s it. But what, if we wanted to combine 2 wrappers? If you have Future { 2 } and Future { 3 } you cannot combine them using some f: (Int, Int) => Int = _ + _. (You could do it using flatMap, but in this article we are not discussing monads). How could we do it? Well, what if we partially applied it? Future { 2 }.map(i => f(2, _)) gives us Future[Int => Int]. So if we only manage to move that other Int… Except functor doesn’t give us a way to move it. However, there is a functor’s extension that does. Applicative functor differs from normal functor, because it has an additional method ap. It works like this: f: A => B fab: F[A => B] = F.pure(f) fa: F[A] = F.pure(a) fab.ap(fp): F[B] fab.ap(fp) == F.pure(f(a)) By F.pure(a) I mean some some wrapping function, that lifts A to F(A). It has many names like pure, point and it simply takes a value and wraps it up (so it would be List(a) for List, Future.successful(a) for Future, etc). As you see, we can use it to combine wrapped values together (that is, once someone provide you with the right method or extension method - Scala’s standard collection doesn’t have them): val f1: F[Int] = F.pure(1) val f2: F[Int] = F.pure(2) val fAdd: F[Int => Int => Int] = F.pure(i => j => i + j) fAdd.ap(f1).ap(f2) The rules to follow regarding ap are: F.pure(f).ap(F.pure(a)) == F.pure(f(a)) F.pure(identity).ap(a) == F.pure(a) - technically speaking apshould be distributive F.pure(a).ap(f) == F.pure(f).ap(F.pure(a)) - and consistend with map F.pure(a).map(f) == F.pure(a).ap(F.pure(f)) The most known applicative functors in Scala community (as far as I can tell, there was no research for it), are Validation/ Validated from Scalaz/Cats. The composition property was used to implement Cartesian syntax: (validated1, validated2, validated3).mapN { (a1, a2, a3) => buildSomething(a1, a2, a3) } Which is used to build some bigger objects once the pairts used to their construction are validated and valid. Underneath it uses ap to apply arguments partially until it has a whole tuple (or if validation fails, it just aggregates errors). This example is kind of funny as you almost never use the ap directly. I am sure, that there is quite large group of people using them everyday not knowing what an applicative functor is. Sink input transformations Functor can be treated as a way of constructing (non-failing) pipeline starting at some source of values. As a matter of the fact, we use this in Scala’s Streams, FS2 streams and Reactive Streams (e.g. Akka Stream): Stream .iterate(1) { i => i + 1 } .map(times2) .map(asString) // Stream("2", "4", "6", ...) import akka.stream.scaladsl._ Source .fromIterator(() => Iterator.from(1)) .map(times2) .map(asString) // Source[String, akka.NotUsed] But, what if we looked from the other side? What if we have some Sink[Input] or Subscriber[A] that accepts values? It is the end of our pipeline (or at least it is the dead-end in graph of all inputs and outputs) - we cannot usually map it. We only can feed it with values. trait Subscriber[A] { def consume(value: A): Unit } object IntSubscriber extends IntSubscriber[Int] { def consume(value: Int): Unit = println(s"Next int is $value") } Iterator.from(1).foreach(IntSubscriber.consume) Exactly! We feed it with values. Which means if there are some values, that doesn’t fit consumer requirements, which we still want to consume, we might adjust transforming them before they will go into Subscriber/ Sink or whatever we call it. val asInt: Double => Int = _.toInt Iterator.iterate(1.0){ d => d * 2.0 }.foreach { d => IntSubscriber.consume(asInt(d)) } It would be nice if we could made such adjustment a part of our interface. It is not a map method which transforms our current type into another, but its complementary, which transforms another type into our. That is why we’ll call it comap: trait Subscriber[A] { self => def consume(value: A): Unit def comap[B](f: B => A): Subscriber[B] = new Subscriber[B] { def consume(value: B): Unit = self.consume(f(value)) } } Iterator .iterate(1.0){ d => d * 2.0 } .foreach(IntSubscriber.comap(asInt).consume) It would share some properties in common with functor though - the fact that identity doesn’t affect it and that mappings can be composed. Confunctor A type constructor F[_] which lifts A to F[A], and B => A to F[A] => F[B] (using comap / contramap), that obeys: fa.comap(identity) == fa fa.comap(f).comap(g) == fa.comap(g andThen f) is called a cofunctor or contravariant functor. (I like the sound of the former, certain FP programmers would kill you for not using the later). To distinct it from functor we can imagine them using this diagram: C --g--> A --f--> B F[C] <--comap(g)-- F[A] --map(f)--> F[B] At some point in our pipeline we have a F[A] stage. We can then use map to travel down the pipeline (calculate next step from current) and comap to travel up the pipeline (map preceding step into current). Other way to express it is by looking at type signatures. In functor the direction of arrows stays the same during lifting, only types get wrapped with F[_]. Cofunctor not only wraps, but also reverts the direction of arrows. Invariant and phantom When we talk about variance in Scala, we mention: - covariance - A <: Bimplies F[A] <: F[B]- if you can travel from Ato B, you can travel from F[A]to F[B]for free. , - contravariance - A <: Bimplies F[B] <: F[A]- when you can travel from Bto A, you can travel from F[A]to F[B]for free, - invariance - none of the above - you cannot travel for free in any side whether A <: Bor B :> A. What would invariance mean for a functor? What would it mean, that functor is invariant? F[A] is a drop in relacement for F[B] only if A = B. You cannot take F[A], pass it one function to turn it into F[B] and forget that it ever was F[A]. I mean, we could, but here A is some algebra, and we want to keep its properties when we map F[A] to F[B]. What you can do, is to pass mappings in both ways: A => B and B => A. This way, when you want to perform some operation on F[B] it will internally translate operands back to A, run the computations and translate the result to B again. This two side mapping is imap ( xmap). import io.circe._ import io.circe.generic.auto._ import io.circe.parser._ import io.circe.syntax._ val a = List(1, 2).asJson val b = List(3, 4).asJson Semigroup[List[Int]] .imap(_.asJson)(decode[List[Int]](_).toOption.get) .combine(a, b) .noSpaces // "[1,2,3,4]" There is also the fourth kind of variance - non-existing in Scala. Phantom variance/anyvariance is when F[A] = F[B] for any A and B. Intuitively, the type doesn’t matter, maybe it is not stored anywhere physically like tags in tagged types. Phantom would use pmap to turn F[A] into F[B]. It wouldn’t need any functions, as it doesn’t operate on actual values. Bifunctor We know how to travel in both direction in our pipeline. However, so far we always assumed, that there is only one type describing values we operate on. Even with Either[L, R] we assumed, that the L type is fixed to be able to treat Either[L, _] as our F[_]. But what, if we wanted to map over both types? The idea, that you have two type parameters, and if you fix one of them, you’ll get a functor is called a bifunctor. In other to have generic enough definition we would require a type constructor B[_, _] that lifts a pair of types A and B to B[A, B] and a bimap function that lifts pair of functions A => C and C => D into B[A, B] => B[C, D]. If it follows the laws: bab.bimap(identity, identity) == indentity(bab) bab.bimap(f1, f2).bimap(g1, g2) == bab.bimap(f1 andThen g1, f2 andThen g2) Quite often, you would like to avoid doing both mappings at once, so there are first and second helper methods defined: bi.first(f) == bi.bimap(f, identity) bi.second(g) == bi.bimap(identity, g) At least, that is the nice theory - no one in Scala has to confirm to such convention. Either is a bifunctor which uses left.map and right.map in order to let you treat one of the types as a functor for one operation. In general, if you wanted to use bifunctor you would have to use type classes (and extension methods) from Cats or Scalaz - the definitions we talk about here are specifications that the implementation would have to follow, but it doesn’t necessarily mean, that each eligible type already has one. That is why FP-heavy codebases are so eager to embrace Cats/Scalaz libraries - they provide both syntax and implantations for certain operations, that standard library does not. An example of heavily (overly) advertised bifunctor for IO operations is ZIO. Scala’s Either, Cats’ Validated and Scalaz’s Validation would also qualify as bifunctors. Same with EitherT monad transformer - each of them could be used to embed error type as the left type and valid type as a right type ( Either and EitherT only by convention, the rest also by nomenclature). These are examples of coproduct bifunctors, but there are also product ones. Tuple (A, B) would be a bifunctor if we defined a bimap for it. Profunctor Bifunctor might be though of as 2 separate pipelines going in parallel (e.g. pipeline of errors and pipeline of successful computations). However, if we had something like Flow[A, B] (using Reactive Streams nomenclature), we see that bifunctor would not work. We would like to be able to map over B type and comap over A type. A1 -------- f --------> A B ------- g -------> B1 Flow[A1, B] <-comap(f)- Flow[A, B] -map(g)-> Flow[A, B1] If we wanted to do comap with f and map with g at once, we could define a dimap method: (flowAB: Flow[A, B]) .dimap(f: A1 => A, g: B => B1): Flow[A1, B1] As you figured what we just defined is a profunctor - a bifunctor’s sibling with covariant functor for first type parameter and covariant functor for second one. You can notice profunctors everywhere you abstract over function, that is: you take some input, emit some output, and there is enough place to put something before and after the computation. Other interesting usage of functors are optics. You basically start with a type Lens[A, A] or Prism[A, A] and then you dimap with pairs of functions (or partial functions) A => B and B => A, defined in a way that allows you to look inside your value to extract some specific value or modify your ADT without cascade of .copy(): trait Lens[S, A] { self => def get(s: S): A def set(s: S)(a: A): S def modify(s: S)(f: A => A): S = set(s)(f(get(s))) def compose[A1](l: Lens[A, A1]) = new Lens[S, A1] { def get(s: S): A1 = l.get(self.get(s)) def set(s: S)(a: A1): S = self.set(s) { val a = self.get(s) l.set(a)(l.get(a)) } } } object Lens { def apply[A]: Lens[A, A] = new Lens[A, A] { def get(s: A): A = s def set(s: A)(a: A): S = a } } final case class Credentials(login: String) final case class Config(credentials: Credentials) val intoCredentials = new Lens[Config, Credentials] { def get(s: Config): Credentials = s.credentials def set(s: Config)(a: Credentials): Config = s.copy(credentials = a) } val intoLogin = new Lens[Credentials, String] { def get(s: Credentials): String = s.login def set(s: Credentials)(a: String): Credentials = s.copy(login = a) } val config = Config(Credentials("test")) intoCredentials.compose(intoLogin).modify { value => value + value } // Config(Credentials("testtest")) I don’t want to get into more details here, as optics are interesting enough that they deserve their own, separate article. Natural transformation / FunctionK So far we operated under one assumption - we are changing only the types of values inside a container, never the type of container itself. mapping over List still returns List. map over Future still returns Future. What if we wanted to do the opposite? What if we wanted to save the inner type, but change the container? // lazy value used for e.g. // expensive but synchronous calulations trait Eval[A] { self => def value(): A // expensive calculation def map[B](f: A => B) = new LazyValue[B] { def value(): B = f(self.value) } } object Eval { def apply[A](a: => A) = new Eval[A] { def value = a } } val expensiveInt: Eval[Int] = Eval { /* expensive int calculation */ 1 } val expensiveString: Eval[String] = expensiveInt.map(i => i * 2).map(i => i.toString) val futureString: Future[String] = ??? // how to interpret expensiveString into Future[String] This example is rather trivial (after all you can just Future { expensiveString.value }), but what if you have some more generic problem? You might decide to use a free functor and decide later on what to do with it: sealed trait Free[S[_], A] { def map[B](f: A => B): Free[S, B] = Free.Mapped(this, f) } object Free { final case class Point[S[_], A](a: A) extends Free[S, A] final case class Mapped[S[_], A, B](fa: F[A], f: A => B) extends Free[S, B] } (Just in case: I wanted to implement free functors that are not free monads, which is why implementations differs from what you’ll find in Cats/Scalaz/Freestyle/whatever). Similarly to free monoids, we call it free because it preserves properties (and laws) of a functor, no matter what kind of S[_] we put inside - it’s reliability is completely free from dependency on any details about S. Point (or Pure) is the name of function (or constructor) that simply wraps the value - point refers to the fact that function’s argument can be also called the point (function has a value y at point x) while pure refers, that it is a pure function - it has no side effects, it takes one argument, there is not much it can do about it. If it was Int => Int it could increment, decrement, multiply etc by constant, but since it’s A => F[A] it most likely just wraps the value and that’s all. So, we have a pretty useless Free[F, A] and want to interpret it into something more useful. For instance Future[A] or Eval[A]. So, we can implement it as: object futureInterpreter { def apply[S[_], A](free: Free[S, A]): Future[A] = free match { case Free.Pure(a) => Future.successful(a) case Free.Mapped(fa, f) => // just an example!! it is not stack safe!! futureInterpreter(fa).map(f) } } object evalInterpreter { def apply[S[_], A](free: Free[S, A]): Eval[A] = free match { case Free.Pure(a) => Eval(a) case Free.Mapped(fa, f) => // just an example!! it is not stack safe!! evalInterpreter(fa).map(f) } } This would do the job, but it wouldn’t be very generic solution. What if we wanted to interpret Free[S, _] into Eval[_] and then Eval[_] into Future[_]? What if we wanted to have more interpreters and make them more composable? First thing we need to do is to extract the common interface: trait Interpreter[F[_], G[_]] { def apply[A](fa: F[A]): G[A] } Any implementation conforming to such interface would allow us to translate values from one functor to another. As a matter of the fact, such interpreter already has a name: natural transformation. It has also another name: FunctionK - this one refers to the fact that this is a function operating not on actual types, but on type constructors (which makes it a higher-Kinded function). Scalaz prefers the former nomenclature while Cats the latter, but this is basically the same concept. Natural transformation is often denoted with ~> type alias, and since in Scala types with two type parameters can be described with infix notation, don’t be surprised to see things like this: trait NaturalTransformation[F[_], G[_]] { self => def apply[A](fa: F[A]): G[A] def andThen[H[_]](nt: G[_] ~> H[_]) = new (F[_] ~> H[_]) { def apply[A](fa: F[A]): H[A] = self[A] andThen nt[A] } } type ~>[F[_], G[_]] = NaturalTransformation[F, G] def futureInterpreter[S[_]] = new (Free[S, ?] ~> Future) { def apply[A](fa: Free[S, A]): Future[A] = ??? } def evalInterpreter[S[_]] = new (Free[S, ?] ~> Eval) { def apply[A](fa: Free[S, A]): Eval[A] = ??? } Because natural transformation is a (parametric) function you can compose natural transformations just like other functions Yoneda lemma So far we evaluated map eagerly, at each point we remembered, that F[_] is functor, and when we mapped, we applied the transformation instantly (whether that transformation was immediately evaluated inside is another thing). So, let’s try to figure out clever trick, showing how we could collect transformations and then delay the actual mapping. Let’s start with a set of all functions from A to B . Let’s call it home-set Hom(A, B) (if we wanted to express it using Scala’s type system it would be a type Function[A, B]). If we make B a parameter, we’ll end up with a functor Hom(A, -) - in this functor we could lift f : B→C into Hom(A,B)→Hom(A,C) (because of applicative, we could write it also as Home( A ,f )_ ) (in other words we create a functor Function[A, ?], where we map over returned value type, turning Function[A, B] into Function[A, C]). We also have a functor F ( F[_]). Yoneda lemma states, that for each possible A we can define a set of natural transformation Nat(Hom(A,−),F) ( phi: Function[A, ?] ~> F), which is isomorphic to F(A) (there is one-to-one correspondence between elements of these sets). Intuitively: when you have a set of functions A→B, you can always fix some value a:A, which you would apply to these functions, obtain B which you can lift into F(B), and it will be the same as if you interpreted functions into F(A→B) first and then feed it with F(A) created by lifting a. The number of possible ways you can do that corresponds to the size of F(A). Formally, the way we create such correspondence is: - we take some natural transformation Φ ∈ Nat(Hom(A,−),F) val phi: Function[A, ?] ~> F - we apply type A to parametric function Φ obtaining Φ A:(A→A)→F(A) and pass identity function id A into it, so that we’ll end up with an element u:F(A) val u: F[A] - we define the natural transformation Φ(f)=F(f)(u) object Phi extends (Function[A, ?] ~> F) { def apply[B](f: A => B): F[B] = F.lify(f).ap(u) // F.lift(f): F[A => B] } This takes care of the other direction of correspondence. The proof of Yoneda lemma can be found on Wiki, here we are only interested in practical application. What is the practical application? Yoneda lemma states that there is a natural transformation between Function[A, ?] and F[_] that we can construct using F[A]. It also shows that the order in which we apply some A => B and run this natural transformation is irrelevant. So, lets implement that! First, the interface: trait Yoneda[F[_], A] { def apply[B](f: A => B): F[B] def map[B](f: A => B): Yoneda[F, B] } object Yoneda { // to skip explaining type classes and stuff: // here I am assuming import of type classes // and syntax from cats/scalaz, to be sure that // I can always call .map on fa def apply[F[_]: Functor, A](fa: F[A]): Yoneda[F, A] } We can see that Yoneda[F, ?] represents Function[A, ?] from the lemma, map is functor mapping and apply is natural transformation Φ. With such interface we could: Yoneda(Eval(2)).map(_ * 2).apply(_.toString) Yoneda(Eval(2)).apply(_.toString).map(_ * 2) Both ways we’ll end up with the same result. However, mapping things within Yoneda has some advantages, namely we can implement things like: trait Yoneda[F[_], A] { self => def apply[B](f: A => B): F[B] def run: F[A] = apply(identity[A]) def map[B](f: A => B): Yoneda[F, B] = new Yoneda[F, B] { def apply[C](g: B => C) = self(f andThen g) } } object Yoneda { def apply[F[_]: Functor, A](fa: F[A]): Yoneda[F, A] = new Yoneda[F, A] { def apply[B](f: A => B): F[B] = Functor[F].map(fa)(f) } } The trick here lies in implementation of apply and map - as you can see as long as we stay within Yoneda we can compose functions that will be eventually applied to map. However, until we run apply (or run) non of the maps will be evaluated on fa. So one way to thinking about Yoneda is that is maps you functor lazily. The other way (used in Cats and Scalaz documentation) is that it is partially applied map method of a Functor type class, there the f is passed only after you finished composing functions. At the same time, we can completely forget, that F[_] is a functor - we only see that Yoneda[F, ?] is a functor and use it as such. If you still wonder what you could do with - imagine that you want to run some computations at once, without breaking it into chunks, that would be run on separate threads or maybe in separate calls to a thread pool if you are thinking about Future. You want to optimize them, but collapsing them into one function, but you don’t want to loose that nice syntax where you just map things. With Yoneda you can just lift your algebra in first call, keep your nice maps and then post one aggregated function to a thread pool on run. Dual to Yoneda is Coyoneda - if differs mainly in that it doesn’t require you to prove that F[_] is functor then you create Coyoneda, but when you exit it in run: trait Coyoneda[F[_], A] { self => type I // original value type val fi: F[I] // original F[A] val f: I => A def run(implicit functor: Functor[F]): F[A] = functor.map(fi)(f) def map[B](g: A => B): Coyoneda[F, B] = new Coyoneda[F, B] { type I = self.I val fi = self.fi val f = self.f andThen g } } object Coyoneda { def lift[F[_], A](fa: F[A]) = new Coyoneda[F, A] { type I = A val fi = fa val f = identity[A] } } As everything else discussed here Yoneda and Coyoneda are defined in both Cats and Scalaz. Summary In this article, we discussed briefly some more common functors and related terms. We tried to figure out some intuitions and practical application. At this point we should already see, that when it comes to building pipelines of data different kinds of functors are ubiquitous. However, none of the functors we discussed was able to bypass 1-correct-input-1-correct-output requirement. For that - failing with error and recovering, filtering and producing multiple values out of one - we need more generic solution. But that is a tale for another day. Originally published on kubuszok.com
https://functional.works-hub.com/learn/the-f-words-functor-and-friends-f76fe
CC-MAIN-2019-51
refinedweb
5,514
63.8
AlertController An Alert is a dialog that presents users with information or collects information from the user using inputs. An alert appears on top of the app's content, and must be manually dismissed by the user before they can resume interaction with the app. It can also optionally have a title, subTitle and You can pass all of the alert's options in the first argument of the create method: create(opts). Otherwise the alert's instance has methods to add options, such as setTitle() or addButton(). Alert Buttons In the array of buttons, each button includes properties for its text, and optionally a handler. If a handler returns false then the alert will not automatically be dismissed when the button is clicked. All buttons will show up in the order they have been added to the buttons array, from left to right. Note: The right most button (the last one in the array) is the main button. Optionally, a role property can be added to a button, such as cancel. If a cancel role is on one of the buttons, then if the alert is dismissed by tapping the backdrop, then it will fire the handler from the button with a cancel role. Alert Inputs Alerts can also include several different inputs whose data can be passed back to the app. Inputs can be used as a simple way to prompt users for information. Radios, checkboxes and text inputs are all accepted, but they cannot be mixed. For example, an alert could have all radio button inputs, or all checkbox inputs, but the same alert cannot mix radio and checkbox inputs. Do note however, different types of "text"" inputs can be mixed, such as url, text, etc. If you require a complex form UI which doesn't fit within the guidelines of an alert then we recommend building the form within a modal instead. Usage import { AlertController } from 'ionic-angular'; constructor(private alertCtrl: AlertController) { } presentAlert() { let alert = this.alertCtrl.create({ title: 'Low battery', subTitle: '10% of battery remaining', buttons: ['Dismiss'] }); alert.present(); } presentConfirm() { let alert = this.alertCtrl.create({ title: 'Confirm purchase', message: 'Do you want to buy this book?', buttons: [ { text: 'Cancel', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }, { text: 'Buy', handler: () => { console.log('Buy clicked'); } } ] }); alert.present(); } presentPrompt() { let alert = this.alertCtrl.create({ title: 'Login', inputs: [ { name: 'username', placeholder: 'Username' }, { name: 'password', placeholder: 'Password', type: 'password' } ], buttons: [ { text: 'Cancel', role: 'cancel', handler: data => { console.log('Cancel clicked'); } }, { text: 'Login', handler: data => { if (User.isValid(data.username, data.password)) { // logged in! } else { // invalid login return false; } } } ] }); alert.present(); } Instance Members config create(opts) Display an alert with a title, inputs, and buttons Advanced Alert options Input options Button options Dismissing And Async Navigation After an alert alerts, this means it's best to wait for the alert to finish its transition out before starting a new transition on the same nav controller. In the example below, after the alert button has been clicked, its handler waits on async operation to complete, then it uses pop to navigate back a page in the same stack. The potential problem is that the async operation may have been completed before the alert has even finished its transition out. In this case, it's best to ensure the alert has finished its transition out first, then start the next transition. let alert = this.alertCtrl.create({ title: 'Hello', buttons: [{ text: 'Ok', handler: () => { // user has clicked the alert button // begin the alert's dismiss transition let navTransition = alert.dismiss(); // start some async method someAsyncOperation().then(() => { // once the async operation has completed // then run the next nav transition after the // first transition has finished animating out navTransition.then(() => { this.nav.pop(); }); }); return false; } }] }); alert.present(); It's important to note that the handler returns false. A feature of button handlers is that they automatically dismiss the alert when their button was clicked, however, we'll need more control regarding the transition. Because the handler returns false, then the alert does not automatically dismiss itself. Instead, you now have complete control of when the alert has finished transitioning, and the ability to wait for the alert to finish transitioning out before starting a new transition.
https://ionicframework.com/docs/v3/3.5.0/api/components/alert/AlertController/
CC-MAIN-2019-13
refinedweb
699
55.13
RE: [gothic-l] Re: "Umlaut" in Gothic? Expand Messages - *<?xml:namespace prefix = o No doubt, Nestor is worth reading. Of course, he could not think out everything written in the Original Chronicle. There are some real facts in the underground. But still, when reading Nestor, I'd suggest you to investigate three startling personages of the chronicle. The chronicle mentions a ringleader Vadim Khrabry (killed by Ruric in Novgorod) and two jarls Ascold and Dir (co-rulers in Kiev murdered by the Rurik's successor Oleg). These personages put an idea into my head. Pay please your attention to resemblance of three names with personages of the Scandinavian epos: Vadim Khrabryj - (V)odin Radbard (Raudbard) Ascold -- Skjold Dir - Tyr. Other parallels fortify this resemblance. Odin Ra(u)dbard (alias Vadim Khrabryj) was represented as a konung of Gardariki or Austrriki (i.e. Initial Russia) in Edda and Hrolv Passenger Saga (I beg your pardon for possibly incorrect spelling of the saga title). Skiold and Tyr (alias the Kiev co-rulers Ascold and Dir) were sons of Odin, and Odin designated Skjold as a konung of Reidgotaland, which might be identified with the Gothic realm (e.g. of Ermanaric) on the territory of modern Ukraine. (All this has been written in more detail in my brochure "Rus and Rus again", but it is in Russian.) So, I can repeat following you: we have much work ahead of us. Good luck! Vladimir -----Original Message----- From: Tore Gannholm [mailto:tore.gannholm@...] Sent: Wednesday, September 24, 2003 1:07 PM To: gothic-l@yahoogroups.com Subject: RE: [gothic-l] Re: "Umlaut" in Gothic? Hi Vladimir! I can only agree with you. I have understood that these ideas started already during the 19th century but were officially supported later on. We have much work ahead of us. I am trying to gather all sources I get hold of on my research library. Unfortunately, as you have seen, most of it is in Swedish, The Russian documents I can't read. About Nestor, I have it in front of me. However one has to read it very carefully as he is mixing religion with actual happenings. Tore [Non-text portions of this message have been removed] Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/gothic-l/conversations/topics/7389?o=1&d=-1
CC-MAIN-2015-27
refinedweb
383
65.73
The QElapsedTimer class provides a fast way to calculate elapsed times. More... #include <QElapsedTimer> Note: All functions in this class are reentrant. This class was introduced in Qt 4.7. The QElapsedTimer class provides a fast way to calculate elapsed times. The QElapsedTimer class is usually used to quickly calculate how much time has elapsed between two events. Its API is similar to that of QTime, so code that was using that can be ported quickly to the new class. However, unlike QTime, QElapsedTimer tries to use monotonic clocks if possible. executeSlowOperations(int timeout) { QElapsedTimer timer; timer.start(); slowOperation1(); int remainingTime = timeout - timer.elapsed(); if (remainingTime > 0) slowOperation2(remainingTime); }. This enum contains the different clock types that QElapsedTimer may use. QElapsedTimer will always use the same clock type in a particular machine, so this value will not change during the lifetime of a program. It is provided so that. See also clockType() and isMonotonic(). true if this object was invalidated by a call to invalidate() and has not been restarted since. See also invalidate(), start(), and restart().(). Restarts the timer and returns the time elapsed since the previous start. This function is equivalent to obtaining the elapsed time with elapsed() and then starting the timer again with restart(),(). Returns true if this object and other contain different times. Returns true if this object and other contain the same time.
https://doc.qt.io/archives/qt-4.7/qelapsedtimer.html
CC-MAIN-2021-17
refinedweb
229
60.11
Snake Game in Java (OOP design concepts) Get FREE domain for 1st year and build your brand new site In this article, we have explored how to design the classical Snake Game using Object Oriented Programming (OOP) concepts and implement it using Java. Let us start immersing ourselves into it by fueling ourselves with some Nostalgia. Below is Snake Xenzia the Nokia. The classic game that we are all acquainted with is actually surprisingly simple to implement and understand. So lets get this straight, What do we need in our snake game? - A snake? Ofcourse! - Food for the snake! - A board.. where will the snake move afterall - Logic for the real game Now that we're clear with what makes a Snake Game, lets look at it with an object oriented approach. What classes do we need? Snake A Snake Class for the snake. We want to --> Know and maintain the size of the snake. --> The ability to control movement of the Snake --> Check whether it did not hit a Wall. So it shall contain the following functions: - A constructor to initialise the snake with its head. - A function to grow the size of the snake. - A function for the snake to move. - A function to check if the snake has crashed. - A function that returns the snake - A function to set values in the snake. - A function that returns the head of the snake. - A function to set the head of the snake. Cell While food seemed intuitive to me while thinking, cell feels intuitive to me for working! Why so? Our boards, consistes of various cells, A cell at random will be proclaimed as the cell containing food. The identify of food is random, but identity of cell is meaningful, so I would rather make a class Cell than food. Cells are also important to kep track of position of the snake! Each cell is thereby contains the information about --> Its Row --> Its Column --> Whether it contains food or not? --> Whether it is a part of the snake or not? Hence its member functions include - A constructor to initialise it. - A function that specifies its type (contains food etc.) - A function that returns its type. - A function to return its row. - A function to return its column. Board It is the set of valid points for the game to function on, qualitatively a matrix of cells. While the cells revert to the questions, being the collection and home of cells, the board needs to ensure the cells get satisfiable answers Whether it contains food or not? We need to assign food to some random cell as well. This is attributed to the board, as the cell doesn't choose whether it shall contain food, the board is acquainted with the cells it contains and hence should empowered to assign a cell to contain food. Whether it is a part of the snake or not? This is answered by the Snake class we described above. While food is an attribute of the board, movement is an attribute of the snake! Hence it is wise to let the Snake class contain method pertaining to the Snake's movement. It will contain the following functions - A constructor to initialise te board with number of rows and columns. - A function to return its cells. - A function to set values in its cells. - A function to generate Food. Game This is the meaty part of the code, our primary logic, the game! It needs an instance of - Board - Game Notice how Board already contains instances of Cell. This also needs to contain the following --> Ability and logic to use the classes we make and conduct a game! --> Know when the game is over So the following functions will be required: - A constructor to initialise the game with a snake and a board. - A function to return the snake. - A function to set the value of snake. - A function to return the board. - A function to set the value of board - A function to set the game to be over. - A function to check if the game is over. - A function to set the direction of snake's motion. - A function to return the direction of snake's motion. - A function to update the game according to snake's movement. - A function to keep track of the forthcoming cell. After this we will also define a main function to actually play the game. Now that we are clear with the what and what not of the game, lets start coding! Code Cell The most basic element, we only need private data members as discussed and public methods to set and retrieve them. public class Cell { private final int row, col; private CellType cellType; public Cell(int row, int col) { this.row = row; this.col = col; } public CellType getCellType() { return cellType; } public void setCellType(CellType cellType) { this.cellType = cellType; } public int getRow() { return row; } public int getCol() { return col; } } Board For the board, it must contain a 2-Dimensional array of cells, which we need to initialise in its constructor. Thereby it is meaningful to maintain the ROW_COUNT and COL_COUNT for a board, which shall be passed to the constructor. We also need a method to randomly designate a cell as Food along with some methods to set and retrieve cells. public class Board { final int ROW_COUNT, COL_COUNT; private Cell[][] cells; public Board(int rowCount, int columnCount) { ROW_COUNT = rowCount; COL_COUNT = columnCount; cells = new Cell[ROW_COUNT][COL_COUNT]; for (int row = 0; row < ROW_COUNT; row++) { for (int column = 0; column < COL_COUNT; column++) { cells[row][column] = new Cell(row, column); } } } public Cell[][] getCells() { return cells; } public void setCells(Cell[][] cells) { this.cells = cells; } public void generateFood() { System.out.println("Going to generate food"); int row = (int)(Math.random() * ROW_COUNT); int column = (int)(Math.random() * COL_COUNT); cells[row][column].setCellType(CellType.FOOD); System.out.println("Food is generated at: " + row + " " + column); } } Snake We will be representing the snake with a Linked List, that is because it has O(1) insertion, which helps us increase the size of the snake at the pace of the game! We need to add elements at the tail and retrieve position with the head. This is a FIFO approach, i.e. represented by a Queue that we are implementing with a Linked List. We need to create methods for - Movement of snake i.e. incrementing the position in the direction of movements. - Check crashes i.e. if snake comes in contact with any prohibited cell, it shall declare a crash! // To represent a snake import java.util.LinkedList; public class Snake { private LinkedList<Cell> snakePartList = new LinkedList<>(); private Cell head; public Snake(Cell initPos) { head = initPos; snakePartList.add(head); } public void grow() { snakePartList.add(head); } public void move(Cell nextCell) { System.out.println("Snake is moving to " + nextCell.getRow() + " " + nextCell.getCol()); Cell tail = snakePartList.removeLast(); tail.setCellType(CellType.EMPTY); head = nextCell; snakePartList.addFirst(head); } public boolean checkCrash(Cell nextCell) { System.out.println("Going to check for Crash"); for (Cell cell : snakePartList) { if (cell == nextCell) { return true; } } return false; } public LinkedList<Cell> getSnakePartList() { return snakePartList; } public void setSnakePartList(LinkedList<Cell> snakePartList) { this.snakePartList = snakePartList; } public Cell getHead() { return head; } public void setHead(Cell head) { this.head = head; } } Game Credits to the classes we've made so far the forthcoming section is actually surprisingly easy! We need a class Game, which contains data members to take care of the snake and the board. We need a set of fixed directions for movement, and a direction member to determine movement. Along with a boolean to check for the game to be over! - We need methods to initialise and receive the values. - We need to ensure that the game is updated as per the user, i.e. actually calling the functions for moving the snake, getting the food etc. One characteristic is that, even though direction of movement is somewhat characteristic to the snake, the position is actually attributed to the cell, which is a part of the board. Since we have the snake as well as access to current values here, and have also added direction members here, it seems right to and modular to maintain directions here. - A function to update the direction here itself. // To represent Snake Game public class Game { public static final int DIRECTION_NONE = 0, DIRECTION_RIGHT = 1, DIRECTION_LEFT = -1, DIRECTION_UP = 2, DIRECTION_DOWN = -2; private Snake snake; private Board board; private int direction; private boolean gameOver; public Game(Snake snake, Board board) { this.snake = snake; this.board = board; } public Snake getSnake() { return snake; } public void setSnake(Snake snake) { this.snake = snake; } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public boolean isGameOver() { return gameOver; } public void setGameOver(boolean gameOver) { this.gameOver = gameOver; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } // We need to update the game at regular intervals, // and accept user input from the Keyboard. public void update() { System.out.println("Going to update the game"); if (!gameOver) { if (direction != DIRECTION_NONE) { Cell nextCell = getNextCell(snake.getHead()); if (snake.checkCrash(nextCell)) { setDirection(DIRECTION_NONE); gameOver = true; } else { snake.move(nextCell); if (nextCell.getCellType() == CellType.FOOD) { snake.grow(); board.generateFood(); } } } } } private Cell getNextCell(Cell currentPosition) { System.out.println("Going to find next cell"); int row = currentPosition.getRow(); int col = currentPosition.getCol(); if (direction == DIRECTION_RIGHT) { col++; } else if (direction == DIRECTION_LEFT) { col--; } else if (direction == DIRECTION_UP) { row--; } else if (direction == DIRECTION_DOWN) { row++; } Cell nextCell = board.getCells()[row][col]; return nextCell; } public static void main(String[] args) { System.out.println("Going to start game"); Cell initPos = new Cell(0, 0); Snake initSnake = new Snake(initPos); Board board = new Board(10, 10); Game newGame = new Game(initSnake, board); newGame.gameOver = false; newGame.direction = DIRECTION_RIGHT; // We need to update the game at regular intervals, // and accept user input from the Keyboard. // here I have just called the different methods // to show the functionality for (int i = 0; i < 5; i++) { if (i == 2) newGame.board.generateFood(); newGame.update(); if (i == 3) newGame.direction = DIRECTION_RIGHT; if (newGame.gameOver == true) break; } } } You are welcome to compile and run them together, maybe even develop a friendly interface and actually play it! You see, the way to solve a problem is logically breaking it into smaller problems. Now go ahead and maybe build another game, or break down your own game into smaller fragments and implement it!
https://iq.opengenus.org/snake-game-java/
CC-MAIN-2021-43
refinedweb
1,722
66.84
go to bug id or search bugs for Description: ------------ Currently the internal PHP function library is, well, unique. Proposed is a means to maintain backward compatibility while rectifying the problem and hopefully on the engine side speed up the process by reducing what the zend engine has to track. import keyword. import attaches the specified namespace to the current one. An error is thrown if there is a symbol collision between the namespaces. namespace Bar { function Foo(){} } namespace Test { import \Bar Foo() // works Bar\Foo() // doesn't work - try use Bar instead. } If import is asked to pull a namespace that doesn't exist there's an error. Import has one other use. namespace Test; import @PDO; This pulls the PDO library of PHP 6 into the Test namespace. This brings us back to the solution of the function library problem. PHP 6 would ship with a legacy mode set to true. In that mode everything is as now - the namespace \ having thousands of functions. Turn it off though and namespace \ is empty except for a core selection of functions and objects. The rest of the function library will be divided into libraries that can be imported as needed. Legacy functions remain available in library legacy so namespace MyNamespace; import @Legacy; would let code in MyNamespace use the current function library. Add a Patch Add a Pull Request This is certainly a feature request which requires discussion on the internals@ mailing list, and likely the RFC process. For the time being, I'm suspending this ticket.
https://bugs.php.net/bug.php?id=53160
CC-MAIN-2022-27
refinedweb
256
64
API Documentation is a quick and concise way to tell a user about how to use a library or work with a program. It details classes, functions, parameters, return types and more. Courtesy of Sphinx, Yaydoc had build in support for Documenting APIs for Python based projects right from it’s inception. Sphinx has a built in tool autodoc which provides certain directives such as autoclass, automodule, etc which can be used to automatically extract docstrings from all specified Python packages and modules and use it to generate API documentation. As a user of Yaydoc you could add ReST sources files with appropriate directives provided by autodoc and we would handle the rest. As part of enhancing this feature we wanted to do three things. - Enhance support for Python - Extend API documentation to other languages apart from Python - Automate the process of generating ReST source files For Enhancing support for python projects, we implemented a few things. Since autodoc imports the modules it needs to document, There could be import errors if a dependency was not met. To fix this issue, Now a user can specify certain modules to be mocked. This would really come in handy with projects depending on packages with third party C extensions such as numpy, scipy, etc. {% if mock_modules %} mock_modules = [name.strip() for name in '{{ mock_modules }}'.split(',')] sys.modules.update((mod_name, mock.Mock()) for mod_name in mock_modules) {% endif %} Apart from this, if we detect a setup.py in the repository or a requirements.txt, we automatically try to install from it to meet dependencies. # autodoc imports the module while building source files. To avoid # ImportError, install any packages in requirements.txt of the project # if available if [ -f $ROOT_DIR/setup.py ]; then pip install $ROOT_DIR/ elif [ -f $ROOT_DIR/requirements.txt ]; then pip install -q -r $ROOT_DIR/requirements.txt fi We also crawl the repository to detect any packages and add them to sys.path. With these changes, a user can expected generated API docs without having to extend conf.py. {% if autoapi_python == 'true' %} for (dirpath, dirnames, filenames) in os.walk('{{ root_dir }}'): # Directory contains __init__.py. It should be a python package if '__init__.py' in filenames: # appending instead of inserting at front so that user # cannot overwrite some of our own modules. sys.path.append(os.path.abspath(os.path.dirname(dirpath))) {% endif %} The second goal is a no brainer. We would like to support as many languages as we can. With this week’s update, Java has been added to the officially supported list of languages for which Yaydoc can generate full API documentation without any manual intervention. To extract API documentation for java source files, we used a sphinx extension named javasphinx. From the official javasphinx docs,-apidoc -o source/ $ROOT_DIR/$AUTOAPI_JAVA_PATH/ sphinx-apidoc -o source/ $ROOT_DIR/$AUTOAPI_PYTHON_PATH/ For the third goal, we use the tools sphinx-apidoc and javasphinx-apidoc to generate source files.
http://blog.fossasia.org/documenting-apis-with-yaydoc/
CC-MAIN-2017-30
refinedweb
482
56.86
fimber 0.3.2 f.3.2 - remember about import in file you plan to use Fimber import 'package:fimber/fimber.dart'; Initialize logging tree on start of your application # void main() { Fimber.plantTree(DebugTree()); // app code here ... // DebugTree options for time elapsed // by default DebugTree will output timestamp of the VM/Flutter app // to enable elapsed time since planting the tree log Fimber.plantTree(DebugTree.elapsed()); }"); try { throw Exception("Exception thrown"); } catch (e, stacktrace) { // providing `stacktrace` will better show where issue was thrown // if not provided will use log line location. Fimber.i("Error caught.", ex: e, stacktrace: stacktrace); } } This will log the value and grab a TAG from stacktrace - that is little costly and if more logs will be done per second. Colorize logs - ColorizeStyle useColors property set to true will use default colors of the logos, you can change the mapping with in colorizeMap for DebugTree and CustomFormatTree The useColors by default is disabled. ColorizeStyle Aggregates list of AnsiStyle so you can combine styles together. AnsiStyle is combination of AnsiColor and AnsiSelection values Here is output of test output.; }); Custom line formatters # Use custom line formatters to define your logging format. Fimber.plantTree(FimberFileTree("my-Log-File.txt", logFormat: "${CustomFormatTree.TIME_ELAPSED_TOKEN} ${CustomFormatTree .MESSAGE_TOKEN} ${CustomFormatTree.TIME_STAMP_TOKEN}" )); Use file log tree - the logs will go to a log file (Useful in DartVM apps). There are log rolling with size and time/date interval, so it is possible to setup log output per hour/day or any other time. see: SizeRollingFileTree or TimedRollingFileTree or use abstract class RollingFileTree to create your own version of rolling log file. TODO - road map # - See Issues on Github - Add Crashlytics plugin (maybe other remote logger tools) with flutter_crashlytics Licence # Copyright 2018 Mateusz Perl. [0.3.2] - Bug fix for Time rolling tree. [0.3.1] - Bug fixes around File rolling tree - initialize outputFileNamevariable by @sceee - removed unnecessary async that caused SizeRollingFileTree constructor to not construct the first logfile correctly before writes to the uninitialized filename could happen by @sceee [0.3.0] - Code styles updates and bug fixes - Code styles updates based on pedantic lint rules. - bug fix for TAG generation taking from correct stacktrace location = index 4. [0.2.1] - Auto create directory for log files [0.2.0] - Colorize logs - Added ANSI colorized option for DebugTreeand CustomFormatTree(by default it is disabled) AnsiStyleclasses as extra for adding any colorful output for console. [0.1.11] - FileLog bugfix - FileLog bug fix for conflicts on file append. - FileLog uses flush buffer as temporary storage and writes to disk in 2 cases: 1 every 500ms and when ever buffer size exceeds 1kB. - Added unit tests for new bug. - docs update [0.1.10] - FileLog append fix, mute levels - bug fix for file log bug where new lines were overriding file not append lines. - Added log level muting from Fimber.muteand Fimber.unmute [0.1.9] - CustomFormatTree and FileLogTree - Custom format tree and File logging tree based on custom format. This will allow DartVM apps to output to defined file. [0.1.8] - Support for stacktrace optional parameter - Stacktrace optional parameter after adding excan be provided from try catchblock's second parameter try { ... } catch (ex, stacktrace) { Fimber.e("log message", ex:ex, stacktrace: stacktrace); } [0.1.7] - Changed the ex class - Accepting dynamic (any class) on exproperty of Logger. This allows to pass Error or Exception or any other value to log statement - toString()is used for printout [0.1.6] - DebugTree time options - Added Elapsed time option for debug tree logging (useful for server side/dart vm logging) - Added Time option for debug tree [0.1.5] - bug fixes - Bug fix for log tag auto creation inside constructor. - Added tests for factory method logging after constructor log tag fix. [0.1.4] - iOS exception stacktrace logging - no update on fimber, only mirror update for flutter_fimber iOS plugin [0.1.3] - iOS plugin part for logging - Added support for iOS log output. - Un-plant tree option. - Block function operation. [0.1.2] - only dart package form fimber - Small changes around packaging and removing any flutter references. - Revert to print from debugPrint for dart only support. - DebugTree got printLog method to override to support other solution to print formatted log line tou output stream, will be helpful in AndroidDebugTree (for example). - Updates to stacktrace dumping for DebugTree and added method to extract stacktrace. [0.1.1] - Small updates Small updates [0.1.0] - First Version Initial version with Fimber debugging and DebugTree example/example.dart import 'package:fimber/fimber.dart'; void main() { // plant a tree - DebugTree() Fimber.plantTree(DebugTree()); Fimber.d("Test message", ex: Exception("test error")); var parameter = 100.0; Fimber.w("Test message with parameter: $parameter"); var logger = FimberLog("MY_TAG"); logger.d("Test message", ex: Exception("test error")); logger.w("Test message with parameter: $parameter"); try { throw Exception("Exception thrown"); // ignore: avoid_catches_without_on_clauses } catch (e, stacktrace) { // providing stacktrace will better show where issue was thrown Fimber.i("Error caught.", ex: e, stacktrace: stacktrace); } // save time without auto tag generation on each call in call block. Fimber.withTag("TEST BLOCK", (log) { log.d("Started block"); for (var i = 0; i >= 1; i++) { log.d("value: $i"); } log.i("End of block"); }); } Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: fimber: ^0imber/fimber.dart'; We analyzed this package on Sep 13, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.5.0 - pana: 0.12.21 Platforms Detected platforms: Flutter, other Primary library: package:fimber/fimber.dartwith components: io. Health suggestions Fix lib/file_log.dart. (-1.49 points) Analysis of lib/file_log.dart reported 3 hints: line 64 col 9: Use isNotEmpty instead of length line 81 col 9: Future results in async function bodies must be awaited or marked unawaited using package:pedantic. line 156 col 9: Use isNotEmpty instead of length Format lib/colorize.dart. Run dartfmt to format lib/colorize.dart. Format lib/data_size.dart. Run dartfmt to format lib/data_size.dart. Format lib/filename_format.dart. Run dartfmt to format lib/filename_format.dart. Format lib/fimber.dart. Run dartfmt to format lib/fimber.dart.
https://pub.dev/packages/fimber
CC-MAIN-2019-39
refinedweb
1,030
50.53
The top choice may surprise you Don't be caught off guard Join the NASDAQ Community today and get free, instant access to portfolios, stock ratings, real-time alerts, and more! As a retiree, I am always looking for income opportunities that are relatively low risk. Preferred stocks Closed End Funds (CEFs) are often overlooked by investors and have the potential for higher income than common stock funds. Like common stocks, most preferred stocks bottomed in March of 2009 and have recovered nicely. Many of the CEFs were selling at a premium to Net Asset Value (( NAV )) until June of this year, when fear of rising rates precipitated another selloff. As a result of this decline, many of the CEFs are now selling at a discount. Considering that many of the CEFs offer high income (on the order of 7% to 8%), I decided to asses this asset class for candidates to include in a retirement portfolio. This article will review the risk versus reward over several time periods and will also touch on some issues that could affect the CEFs in the future. First let's take a quick review of the characteristics of preferred stocks. Many companies issue preferred stock since this is one way corporations can raise money without diluting the number of common shares. Preferred stock does not have voting rights but usually has a much higher dividend than the common stock. The dividend payment associated with preferred stock is not guaranteed but the preferred stock holder must be paid before the common stock holder can receive any dividends. Thus, preferred stock sits between bonds and common stock in the capital structure. It is senior to the common stock but will be paid after the interest on bonds. Suspending payments on preferred stock is a last resort but it is not considered a default like suspending payment to bondholders. After issuing a preferred stock, the price can fluctuate, with one of the key factors being interest rates. If interest rates rise, then the price of the preferred shares will likely drop because investors will demand higher yields. Also, like a bond, many of the preferred stock issues are callable at a specified date in the future. There are several closed end funds that invest primarily in preferred shares. Using data from CEFConnect .com, I selected candidates based on the following criteria: The following CEFs satisfied all of these conditions: There are also preferred stock Exchange Traded Funds (ETFs). These funds differ from CEFs in that they passively track an index rather than being actively managed. Also, the ETFs do not use leverage, so typically they are less volatile and have lower expenses than their CEF counterparts. I included the largest preferred stock ETF in the analysis so I could compare the ETF performance with CEF performance. The ETF selected was: Since preferred stock has attributes of both bonds and stocks, I also included the following ETFs in the analysis for reference: To analyze risks and return, I used the Smartfolio 3 program ( smartfolio .com) over a complete bear-bull cycle (from 12 October 2007 to the present). The results are shown in Figure 1, which plots the rate of return in excess of the risk free rate of return (called Excess Mu on the charts) against the historical volatility. (click to enlarge) Figure 1. Risk versus Reward over bear-bull cycle As is evident from the figure, there was a relatively large range of returns and volatilities. For example, FFC. Similarly, the blue line represents the Sharpe Ratio associated with TLT. Some interesting observations are apparent from Figure 1. Over the complete cycle, long-term bonds had the best risk-adjusted return. This is because they held up better than equities during the horrendous bear market of 2008. A couple of CEFs, DDT and FFC, had about the same Sharpe Ratio as TLT. All the preferred stock CEFs had better risk-reward performance than either SPY or PFF. Overall, the CEFs had high volatility but also delivered high performance. Based on this chart, the preferred stock CEFs would have made good additions to your portfolio. I next looked at the past 3 year period to see if the outperformance has continued. The results are shown in Figure 2. What a difference a few years made! Over the past 3 years, the SPY has been in a rip-roaring bull market and neither preferred stock CEFs nor the bond funds could keep pace. Figure 2. Risk versus Reward over 3 years The data shown in Figure 2 is more aligned with expectation, as the performance of the preferred stock CEFs was between that of bonds and equities. Also evident from the figure is that the preferred stock CEFs have relatively high volatility, about the same as the SPY. On the other hand, the preferred stock ETF, PFF, had substantially lower volatility but also had a lower risk-adjusted return than the CEFs. Over this period, JPC led the pack with about the same Sharpe Ratio as the SPY. FFC was not a standout during this period but did continue to perform relatively well. The decision whether or not to invest in preferred stock CEFs was not as clear-cut as it was for the longer time period. The investment landscape became even murkier in the recent past. Since June of this year, the fear of rising rates has taken its toll on preferred stocks, causing them to give back most of the year to date gains. To get a more near-term view, I ran the analysis from the beginning of 2012 to the present, a little over 1.5 years. This data is presented in Figure 3. The near term results are similar to the 3 year data. The performance of the preferred stock CEFs is better than long-term bonds but worse than the S&P 500. The volatility of these CEFs is on the same order as the stock market. Figure 3. Risk versus Reward since Jan 2012 Which is better, the preferred stock ETF or the CEFs? As you have seen, it depends on the time period under analysis. Over the longer term, CEFs had better risk-adjusted performance but over the near term, PFF has a much higher Sharpe Ratio. So it really depends on the market conditions that you expect in the future. Before leaving this analysis, there are a couple of additional factors that you should consider. In addition to interest rate risk, preferred stocks also have a re-finance risk. Since many preferred stocks are callable, the issuing company can call their preferred stock and re-issue at a lower interest rate. This is especially true in a low interest rate environment like we have had recently. In 2012, $13 billion of preferred stock was redeemed (with average coupon rate of 7.16%) and replaced with issues that had an average coupon rate of 6.37%. This puts downward pressure on preferred prices. Also, as part of the Dodd-Frank Act, non-perpetual preferred issues can no longer be used to satisfy Tier 1 capital requirements. The banks must phase out the use of these preferred stocks by 2015 and replace them with other forms of capital. One of the nuances of the Dodd-Frank Act is that it will likely allow some bank preferred trust issues to be recalled earlier than originally planned. This too will increase the headwinds against preferred issues. Bottom Line The bottom line is that preferred CEFs were once excellent candidates to add to retirement portfolios. They were always volatile but since they were relatively uncorrelated with other assets, they provided diversification as well as high income. However, in the current environment of potentially rising rates and new regulations, caution is advised. You must carefully evaluate the risk and rewards relative to your investment objectives. Using CEFs for your preferred stock exposure can be rewarding but it is not for the fainthe Workday Reports 72% Revenue?
http://www.nasdaq.com/article/assessing-preferred-stock-cefs-in-retirement-portfolios-cm264868
CC-MAIN-2014-23
refinedweb
1,332
62.17
Java Reference In-Depth Information { connec- tion. If we run the client and server in separate command windows and enter local- host as our host name in the client's GUI, the result should look similar to that shown in Fig. 2.7. Unfortunately, there is still a potential problem on some systems: since a low-numbered port (i.e., below 1024) is being used, the user may not have suffi cient specifi ed host and reports on those ports that are providing a service. This works by the program trying to cre- ate a socket on each port number in turn. If a socket is created successfully, then there is an open port; otherwise, an IOException is thrown (and ignored by the program, which simply provides an empty catch clause). The program creates a text fi eld for acceptance of the required URL(s) and sets this to an initial default value. It also provides a text area for the program's output and buttons for checking the ports and for exiting the program. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; import java.io.*; public class PortScanner extends JFrame implements ActionListener Search WWH :: Custom Search
http://what-when-how.com/Tutorial/topic-547t9a4dbp/An-Introduction-to-Network-Programming-with-Java-46.html
CC-MAIN-2019-09
refinedweb
202
58.62
address@hidden (Kim F. Storm) writes: > Eli Zaretskii <address@hidden> writes: > >>> From: address@hidden (Kim F. Storm) >>> Date: Sun, 28 May 2006 23:15:58 +0200 >>> Cc: Agustin Martin <address@hidden>, >>> Stefan Monnier <address@hidden>, address@hidden >>> >>> But I also wonder if any of the async process stuff actually works >>> without SIGCHLD ?!? Are there any systems which support async processes >>> but don't have SIGCHLD? >> >> AFAIK, MS-Windows is such a system. (I didn't track this discussion, >> so I don't know if the Windows case is relevant to it.) > > Well, there is this piece of code (in a context where signo == SIGCHLD): > > #if (defined WINDOWSNT \ > || (defined USG && !defined GNU_LINUX \ > && !(defined HPUX && defined WNOHANG))) > #if defined (USG) && ! defined (POSIX_SIGNALS) > signal (signo, sigchld_handler); > #endif > > But... if MS-Windows does not support SIGCHLD (or SIGCLD), how does > emacs detect process termination on MS-Windows?? Well, this I don't know, but on a second thought, it could be a callback. However, the word `SIGCHLD' is never used in the handler, so I guess it's kind of independent. -- | Michaël `Micha' Cadilhac | Would someone please DTRT with this | | Epita/LRDE Promo 2007 | then ACK? | | | -- Richard Stallman | `-- - JID: address@hidden --' - --' pgp6AlyESXWgU.pgp Description: PGP signature
http://lists.gnu.org/archive/html/emacs-devel/2006-05/msg01711.html
CC-MAIN-2013-48
refinedweb
202
67.55
ASF Bugzilla – Full Text Bug Listing mod_autoindex is generating invalid XHTML markup. The xhtml namespace was missing in emit_preamble(). I'm including a patch against both 2.2.6 and trunk that fixes it. Bug report 34519 is quite similar, but mentions other enhancements (and didn't include a patch). I decided to make a new bug report as I was not sure if it was OK to reply to one of the points given in the previous report. Created attachment 21003 [details] mod_autoindex was not adding the xhtml namespace Patch against 2.2.6 Created attachment 21004 [details] mod_autoindex was not adding the xhtml namespace Patch against trunk Committed to trunk as r59381 (). Thanks for the patch. Proposed for backport as r593818 (). Here's an idea: These autoindexes should not only be valid markup but promote open standards (valid markup) by linking back to W3C's Validator. If you are open to the idea it would be ideal if Apache were to include W3C valid markup logos in the /icons directory so as to distribute load of serving those icons on all the new valid autoindex URIs. In turn we can promote adoption of Apache 2.2, as apparently many are still 1.3, on the Validator's results page eg We could give an alternate markup for Apache instances >2.2.N to all users or perhaps just for sites we detect the Server: header as still Apache 1.3 or 2.0 <p> <a href=""><img src="/icons/valid-xhtml10" alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a> </p> I don't like it. to 2.2 as r596675 <> mod_autoindex is generating invalid XHTML 1.0 Transitional for fancy list. Configuration: IndexOptions Charset=utf-8 XHTML FancyIndexing FoldersFirst VersionSort IndexHeadInsert "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />" HeaderName secret.html ReadmeName secret.html There is problem with hr markups: document type does not allow element "hr" here; missing one of "button", "ins", "del" start-tag You can read it here: Its should be outside pre markup. They are created in lines 1603-1608 and 1814-1819. Problem can be solved with replece specifed lines: 1604 -> ap_rputs("</pre><hr", r); 1608 -> ap_rputs("><pre>", r); insert ap_rputs("</pre>\n", r); under 1813 1819 ap_rputs(">\n", r); delete 1821, 1822, 1823 I don't test it, because I am a new FreeBSD and Apache user, and I not able to do a lot of things now :/
https://bz.apache.org/bugzilla/show_bug.cgi?format=multiple&id=43649
CC-MAIN-2016-07
refinedweb
413
65.62
07 November 2005 14:19 [Source: ICIS news] LONDON (ICIS news)--German chemical giant BASF should divest its styrenics business and not restructure it as planned due to the limited earnings growth and the imminent challenge from Middle East-based producers, UBS said in an investment note on Monday. "We are concerned that BASF continues to try to restructure areas such as styrenics and lysine rather than consider exiting," the bank said in a note to clients. "In the case of styrenics, timing might not be right since the business is at very depressed earnings levels but ... the long-term outlook is not great, and styrenics are unlikely to be able to cover its cost of capita through the cycle." BASF's Q3 styrenics sales amounted to Euro1.14bn, down 11% from a year ago. It is the biggest of three divisions within the plastics segment, which also include performance polymers and polyurethanes.?xml:namespace> UBS, which maintained its buy rating on the company, dropped its share target price by Euro2 to Euro69, partly due to the higher pension deficit assumption and lower associates book value. It said, based on comments from BASF management, it was unlikely that the company would make a major acquisition despite being on the look-out for suitable targets. "Given the size cap they (BASF) have imposed, these acquisitions are more likely to involve parts of companies (e.g. product lines) rather than entire companies," it said. UBS said it had expected a margin improvement during the third quarter for both BASF’s plastics and performance products but plastics margin in fact declined to 9% from 9.4% in Q2 this year and performance products margin fell to 10.3% from 13% in Q2. “In the case of plastics it appears that some of the margin was due to worse product mix … and significant shutdowns in styrenics,” UBS said. “Some of these effects should not be present in Q4 05, which should help underpin profitability in what is likely to be a tougher quarter due to much higher raw material prices.” But the bank said it could not explain the more significant margin decline for performance products. BASF last week reported a 13% rise to $1.33bn (Euro1.13bn) in third quarter operating profits but warned of the continued pressure on margins from high raw material and
http://www.icis.com/Articles/2005/11/07/1018991/BASF-should-sell-styrenics-business-UBS.html
CC-MAIN-2014-52
refinedweb
392
59.84
This is a matter that has been taxing the Working Group. SeeThis is a matter that has been taxing the Working Group. SeeHello,I encounter a problem with managing namespaces in an XSLT 2.0 stylesheet. Perhaps it is a bug, or I misread the spec. The problem:a) A literal result element is constructed, and its contents are (i) a newly constructed (default) namespace node, (ii) another literal result elementb) The serialization shows that the child element did not inherit the constructed namespace nodes: the default namespace is "reset" to null.The spec says (5.7.1, point 12):."Below a test stylesheet and its output. Why does the element <p:group> contain xmlns="" ?Thank you for checking.Kind regards,Hans-JuergenStylesheet:<xsl:transform version="2.0" xmlns:xsl="http:://" " xmlns: <xsl:template <p:choice> <xsl:namespace <p:group </p:choice> </xsl:template> </xsl:transform>Output:<p:choice xmlns:p="" xmlns="" <p:group </p:choice> ------------------------------------------------------------------------------ All the data continuously generated in your IT infrastructure contains a definitive record of customers, application performance, security threats, fraudulent activity, and more. Splunk takes this data and makes sense of it. IT sense. And common sense. _______________________________________________ saxon-help mailing list archived at saxon-help@lists.sourceforge.net
https://sourceforge.net/p/saxon/mailman/attachment/4ED63D90.50606@saxonica.com/1/
CC-MAIN-2016-30
refinedweb
205
51.55
Back to article See the complete program on page 4 In part I, you learned how to use Python and PyGTK to bring up a window and draw lines and circles. Let's take that example and extend it to draw some pretty graphics. You've already seen that you can draw a line in your PyGTK app like this: widget.window.draw_line(xgc, x1, y1, x2, y2) The color, line thickness and line style will all be taken from whatever you've set in xgc, your graphics context. You can use that to make some whizzy color-changing graphics -- lines constantly redrawing in different positions and colors. You could make a screensaver! To pick each new color and position, you'll need Python's random number generator. It's very easy to use. Just import the random module. Then you can use randint to get random numbers. If you wanted a number between 0 and 10: import randomr = random.randint(0, 10) How do you use this to draw lots of lines with colors that vary? First, let's set up the skeleton of what you'll want to do. Here's the program from the previous article, except that I've replaced the contents of expose_handler with a loop that will draw 100 lines. As yet, it won't work, because there's no code to set x1, y1, x2, y2: #!/usr/bin/env pythonimport gtk, random# This function will be called whenever you click on the button:def click_handler(widget) : # quit the application: gtk.main_quit()# This function will be called whenever the drawing area is exposed:def expose_handler(widget, event) : xgc = widget.window.new_gc() # # Set up initial line endpoints and color here # for i in range(0, 200) : # # Set up color and x1, x2, y1, y2 here # widget.window.draw_line(xgc, x1, y1, x2, y2)# Create the main window:win = gtk.Window()# Organize widgets in a vertical box:vbox = gtk.VBox()win.add(vbox)# Create an area to draw in:drawing_area = gtk.DrawingArea()drawing_area.set_size_request(600, 400)vbox.pack_start(drawing_area)drawing_area.connect("expose-event", expose_handler)drawing_area.show()# Make a pushbutton:button = gtk.Button("Quit")# When it's clicked, call our handler:button.connect("clicked", click_handler)# Add it to the window:vbox.pack_start(button)button.show()# Obey the window manager quit signal:win.connect("destroy", gtk.main_quit)vbox.show()win.show()gtk.main() Let's work on those line positions first. To begin with, you'll need endpoints for your first line. They can be random, but you want them to be within the window. so you need to get the window's size, like this: w, h = widget.window.get_size() Once you have the size, it's easy to choose some random positions for a line: for instance, x1 = random.randint(0, w). So now your loop looks like this: w, h = widget.window.get_size() for i in range(0, 200) : # # Set up color and x1, x2, y1, y2 here # x1 = random.randint(0, w) x2 = random.randint(0, w) y1 = random.randint(0, h) y2 = random.randint(0, h) widget.window.draw_line(xgc, x1, y1, x2, y2) Not very impressive looking! (Figure 1.) Even aside from the lack of color, it would be better if each new line was drawn fairly close to the previous line. figure 1 To do that, instead of choosing the line endpoints completely randomly, instead just change each one a little each time. Decide on how much you'll let them move in each step, and call that movesize. Since you want to let the lines move in any direction, you'll want to pick a random number between -movesize and movesize, like this: x1 = x1 + random.randint(-movesize, movesize) Almost -- but if you try that, you'll find that it doesn't look very interesting because it almost always ends up off the screen (Figure 2). figure 2 You need to "clip" the X and Y values to the size of the screen. Python doesn't have a clipping function, but it's easy enough to write one: def clip(i, min, max) : if i < min : return min if i > max : return max return i Getting there ... (Figure 3). figure 3 Now the loop looks like this: movesize = 20 for i in range(0, 200) : # # Set up color and x1, x2, y1, y2 here # x1 = clip(x1 + random.randint(-movesize, movesize), 0, w) x2 = clip(x2 + random.randint(-movesize, movesize), 0, w) y1 = clip(y1 + random.randint(-movesize, movesize), 0, h) y2 = clip(y2 + random.randint(-movesize, movesize), 0, h) widget.window.draw_line(xgc, x1, y1, x2, y2) Getting there. But it's awfully boring without colors.
http://www.linuxplanet.com/linuxplanet/print/6760
CC-MAIN-2016-50
refinedweb
777
66.94
#include <RS485_non_blocking.h> // Lib by by Nick Gammon, v1.0#define RTS 23 // Pin used for RTS, PA14/D23size_t fWrite (const byte what) // The write function of the RS485 class{ return Serial2.write (what); }RS485 myChannel (NULL, NULL, fWrite, 0); // RS485 class, by Nick Gammon. Basically a wrapper class that complements data, makes checksums and handles packages in both transmit and recieve.void setup (){ Serial.begin (115200); // USB UART for Serial monitor Serial2.begin (115200); // USART1 for, RS485 communication myChannel.begin (); // Class initializer: mallocs buffer, resets control flags. unsigned int test = USART1->US_MR; // Read USART mode register Serial.print(test,BIN); //Reads out as 0000 0000 0000 0000 0000 1000 1100 0000, i.e. Normal mode, 8bit, 1 stop, async. Serial.println(); USART1->US_MR |= 0x00000001; // Set the mode to 0x1 = RS485 test = USART1->US_MR; // Check that the register was written (it can be write protected) Serial.print(test,BIN); //Reads out as 0000 0000 0000 0000 0000 1000 1100 0001, i.e. RS485 mode, 8bit, 1 stop, async. Serial.println(); pinMode(RTS,OUTPUT);//RTS pin as output. } // end of setupconst byte msg [5] = {0x01,0x01,0x01,0x01,0x01}; // Random messagevoid loop (){ myChannel.sendMsg (msg, sizeof (msg)); // Send message as package, implements Serial2.write() when data has been packed. delay (100); // limit loop speed} // end of loop PIOA->PIO_SODR=1<<14; //RTS pin to HIGH myChannel.sendMsg (msg, sizeof (msg)); // Send message as package, implements Serial2.write() when data has been packed. // Serial2.flush(); //Doesn't work yet, still bytes left to send while(USART1->US_CSR & US_CSR_TXEMPTY != US_CSR_TXEMPTY){}; //Wait for transmit buffer to empty. Also exits before transmit complete delayMicroseconds(150); // My busywait hack to ensure complete transmission PIOA->PIO_CODR=1<<14; //Clear RTS pin You can only write to the US_MR register (and many others) when the WPEN bit is clear, exactly how you do that I'm not sure but it involves writing a key into the US_WPMR register. PIO_Configure( g_APinDescription[PINS_USART1].pPort, g_APinDescription[PINS_USART1].ulPinType, g_APinDescription[PINS_USART1].ulPin, g_APinDescription[PINS_USART1].ulPinConfiguration); Pio *myPio = (Pio*)0x400E0E00; // create a pointer to a "structure" that is the PIO controller for port AmyPio->PIO_ABSR |= (1u << 14); pinMode(23,OUTPUT); //RTS for USART1=Serial2 set as output. USART1->US_WPMR = 0x55534100; //Unlock the USART Mode register, just in case. (mine wasn't locked). USART1->US_MR |= (1u << 0); //Set USART1 mode to RS485. PIOA->PIO_WPMR = 0x50494F00; //Unlock PIOA register, just in case. (mine wasn't locked). PIOA->PIO_ABSR |= (0u << 14); //Set PIOA14 to 0 => Choosing peripheral A = RTS for D23/PA14. (my whole port was already set to 0) PIOA->PIO_PDR |= (1u << 14); //: Disables the PIO from controlling the corresponding pin (enables peripheral control of the pin). is located on PF5 on larger chips packages
http://forum.arduino.cc/index.php?topic=176421.msg1310871
CC-MAIN-2017-22
refinedweb
450
51.24
The first sections of code are relatively simple, and, once written, can usually be reused in every game you consequently make. They will do all of the boring, generic tasks like loading modules, loading images, opening networking connections, playing music, and so on. They will also include some simple but effective error handling, and any customisation you wish to provide on top of functions provided by modules like sys and pygame. First off, you need to start off your game and load up your modules. It's always a good idea to set a few things straight at the top of the main source file, such as the name of the file, what it contains, the license it is under, and any other helpful info you might want to give those will will be looking at it. Then you can load modules, with some error checking so that Python doesn't print out a nasty traceback, which non-programmers won't understand. The code is fairly simple, so I won't bother explaining any of it: #!/usr/bin/env python # # Tom's Pong # A simple pong game with realistic physics and AI # # # Released under the GNU General Public License VERSION = "0.4" try: import sys import random import math import os import getopt import pygame from socket import * from pygame.locals import * except ImportError, err: print "couldn't load module. %s" % (err) sys.exit(2) In the Line By Line Chimp example, the first code to be written was for loading images and sounds. As these were totally independent of any game logic or game objects, they were written as separate functions, and were written first so that later code could make use of them. I generally put all my code of this nature first, in their own, classless functions; these will, generally speaking, be resource handling functions. You can of course create classes for these, so that you can group them together, and maybe have an object with which you can control all of your resources. As with any good programming environment, it's up to you to develop your own best practice and style. It's always a good idea to write your own resource handling functions, because although Pygame has methods for opening images and sounds, and other modules will have their methods of opening other resources, those methods can take up more than one line, they can require consistent modification by yourself, and they often don't provide satisfactory error handling. Writing resource handling functions gives you sophisticated, reusable code, and gives you more control over your resources. Take this example of an image loading function: def load_png(name): """ Load image and return image object""" fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message return image, image.get_rect() Here we make a more sophisticated image loading function than the one provided by Pygame (image.load). Note that the first line of the function is a documentation string describing what the function does, and what object(s) it returns. The function assumes that all of your images are in a directory called data, and so it takes the filename and creates the full pathname, for example data/ball.png, using the os module to ensure cross-platform compatibility. Then it tries to load the image, and convert any alpha regions so you can achieve transparency, and it returns a more human-readable error if there's a problem. Finally it returns the image object, and its rect. You can make similar functions for loading any other resources, such as loading sounds. You can also make resource handling classes, to give you more flexibility with more complex resources. For example, you could make a music class, with an __init__ function that loads the sound (perhaps borrowing from a load_sound() function), a function to pause the music, and a function to restart. Another handy resource handling class is for network connections. Functions to open sockets, pass data with suitable security and error checking, close sockets, finger addresses, and other network tasks, can make writing a game with network capabilities relatively painless. Remember the chief task of these functions/classes is to ensure that by the time you get around to writing game object classes, and the main loop, there's almost nothing left to do. Class inheritance can make these basic classes especially handy. Don't go overboard though; functions which will only be used by one class should be written as part of that class, not as a global function.
http://pygame.org/docs/tut/tom/games3.html
CC-MAIN-2013-48
refinedweb
779
60.65
What is the best connection pooling library available for Java/JDBC? I'm considering the 2 main candidates (free / open-source): Following is my helper class to get DB connection: I've used the C3P0 connection pooling as described here. public class DBConnection { private static DataSource dataSource; ... I'm trying to implement a solution with c3p0 for the first time. I understand how to initialize the connection pool and "checkout" a Connection from the pool as follows: ComboPooledDataSource cpds = ... Can anyone share the origin and meaning of the jdbc connection pool named c3p0. Was it inspired from star wars?. I have heavy loaded java application using hirbernate. And I used to use as connection pool DBCP, but it had problems with connections lossing. Than I switched to c3p0. But now ... I am developing a web application with database access using Spring, JDBCTemplate and c3p0. I often have a server freeze, and I am pretty sure it comes from the number of busy ... This falls under the category of 'reinventing the wheel'. There are people spending a lot of time and energy building things like database connection pools and unless you have a strong belief these implementations are flawed, better to use their work. Reminds me of an old programmer adage... "Good programmers write good code, great programmers steal good code. "
http://www.java2s.com/Questions_And_Answers/Java-Database/Connection/c3p0.htm
CC-MAIN-2013-20
refinedweb
220
66.33
Learning Perl Objects, References, and Modules By Randal L. Schwartz With Tom Phoenix June 2003 Pages: 224 ISBN 10: 0-596-00478-8 | ISBN 13: 9780596004781 (4) (Average of 2 Customer Reviews) This book has been updated—the edition you're requesting is OUT OF PRINT. Please visit the catalog page of the latest edition. The latest edition is also available on Safari Books Online. Learning Perl Objects, References & Modules picks up where Learning Perl leaves off. This new book offers a gentle introduction to the world of references, object-oriented programming, and the use of Perl modules that form the backbone of any effective Perl program. Following the successful format of Learning Perl, each chapter in the book is designed to be small enough to be read in just an hour or two. Each chapter ends with a series of exercises to help you practice what you've learned with answers in an appendix for your reference. In short, this book covers everything that separates the Perl dabbler from the Perl programmer. Full Description - Packages and namespaces - References and scoping - Manipulating complex data structures - Object-oriented programming - Writing and using modules - Contributing to CPAN Register your book | Submit Errata | Examples Browse within this book | Table of Contents | Index | Sample Chapter | ColophonBook details First Edition: June 2003 ISBN: 0-596-00478-8 Pages: 224 Average Customer Reviews: (4) (Based on 2 Reviews) Featured customer reviews Review of Learning Perl Objects, References and Modules, September 29 2004 . Learning Perl Objects, References & Modules Review, September 24 2003 . Media reviews ...In all, I think this book is needed by all newer perl programmers and those that wish to take their perl to the next level." --Shawn C. Carroll, Chicago Perl Mongers, September 2003 "What a spectacular Perl book it is...this book fills a vacancy for Perl programmers who are looking to improve their skills or to grow in their careers. O'Reilly, Schwartz, and Phoenix have put together a wonderful book. It's very personable and easy to follow. More importantly, it has the feel of a master instructing the apprentice." --Russell J.T. Dyer, UnixReview.com, June 2003
http://oreilly.com/catalog/9780596004781/reviews.html
crawl-002
refinedweb
357
52.29
Hi DemisI'm just trying out your VS Add ServiceStack Reference plugin for the first time. Seriously awesome stuff! I'm using it to keep the DTOs in sync across my mobile projects. On the whole it seems to work perfectly. However some things I'd like some clarity on:1) How can I change the default namespace of the generated dtos.cs file? Could this be a MetadataTypesConfig setting? The namespaces on the mobile apps do not necessarily map to the namespaces from the web services projects.2) In my DTOs I have enums. If the enum lives in the same namespace as the DTO object, the generated Enum names (in the metadata) are properly populated and the correct enum created in C# with it's values in code. However due to the structure of some of my projects, the enums are not necessarily defined in the same namespace at the DTO. In this situation (for enums and classes), the corresponding classes and enums do not seem to be generated in C#. I can provide you an example link privately to show you what I mean if you want. Thanks for your help! Hi Dylan,It's normal for namespaces of Server DTO's not to match up with the client project, i.e. the generated DTO's would mirror the sane C# namespaces as if you were sharing your Server DTO .dll instead.Changing the global namespace is currently only possible in languages which have all DTO's under a single namespace which atm is only F# and TypeScript, I'll look at adding this feature to C# and VB.NET as well although this will mean that every DTO will need to be uniquely named (a restriction not required with multiple namespaces).Is the enum in the same Project as Server DTO dll? i.e. would the client have access to it if you shared your Server DTO .dll instead? In which case the recommended practice is to make sure that everything the client needs to communicate with your Service is in a separate stand-alone DTO project. You can also remove the dependency on internal system enums by changing the property on the DTO to be a string. Dylan v.d Merwe: I understand about having a stand-alone DTO project with all the relevant communication items in, however this is not possible in my case due to the setup of the many client projects and dependencies.Still in this case would it not be possible to generate the code for the required enums/classes regardless? The generated code would be independent from the server's implementation (and namespaces and project are actually irrelevant at this point) which I thought would be the aim. If it's not possible I'll take a look at the generation code to see what I can tweak, otherwise I can always keep on maintaining the files manually across the projects This is really something you should be striving for as otherwise you're headed down a slippery slope where it's no longer possible to call your Services with just a url and its self-contained DTO's (irrespective as to how big or complex or large the System gets). Once you break this contract it'll become harder to recover from the situation where you've now brought a tonne of extra complexity to your Services consumers who'll now have to research the cyclical dependencies of your Servers .dlls to determine whether it's feasible or not to call your services with its typed DTO's. The problem with this heuristic of bringing it internal enums/types is that it makes it difficult to determine whether or not we're re-declaring already existing .NET enums/types will cause compilation errors. I can investigate offering custom server configuration to explicitly include external types, but as it's something I would like to discourage I don't want to add extra complexity to deal with it. IMO the best solution is you manually redeclare the internal enums on the client which as it's outside of the normal path shows that it's a code-smell (a bad one IMHO) and it's something that will let you keep track of how bad it gets and hopefully encourage refactoring it later on. Also as I mentioned earlier changing the DTO enum property to a string also breaks the explicit binary contract which is another option that's an easy workaround. Dylan v.d Merwe: I get at what you're saying, but if you had to see the project structure you'd understand. Just to clarify, all Service classes and DTOs are contained within their respective projects/dlls. This goes to what you were saying with keeping them all in-check. It's just that the DTOs themselves sometimes contain enum fields or Lists of other DTO-like classes that do not exist in the main DTO dll - these are the items which are not being properly generated. I still believe that they should be. The reason these enums or DTO like classes are not contained in the primary DTO dll is due to other references or integrations. "It's just that the DTOs themselves sometimes contain enum fields or Lists of other DTO-like classes that do not exist in the main DTO dll... The reason these enums or DTO like classes are not contained in the primary DTO dll is due to other references or integrations. "This is the slippery slope I'm saying should be avoided - in order for this to be possible your services now rely on internal types outside of your DTO's, so now clients need knowledge of your internal types. Again I'd highly discourage this, you can also avoid this dependency with a copy of the enums in the DTO .dll and just use ConvertTo to translate between them.If you want you can put together a small repro with empty/Mock Services and I can look at whether it's something that can be easily avoided without causing further regressions. ConvertTo I've added support for GlobalNamespace on C# and VB.NET as well available from next v4.0.37+ that's now on MyGet: can play around with the deployed version on:
https://forums.servicestack.net/t/dylan-v-d-merwe-362-jan-19-2015/169
CC-MAIN-2019-22
refinedweb
1,054
67.08
Introduction: Notificator The device can be connected for example to the IFTTT system and react when a new mail appears. At app.remoteme.org we will generate a link after calling which bytes will be sent to Arduino, and Arduino will display some light effect and play some mp3 from SDcard Step 1: What Is Needed - NodeMCU, WemOS or something similar - Two LED rings with WS2812B diodes ( I’ve used 16th leds rings ) - DFRobotDFPlayerMini – this is mp3 player. It plays mp3 from SDcard, and communicate with Arduino by RX/TX - Speaker - SDcard - Logic converter -I’ve used this one, the mp3 player uses 5V and Arduino 3.3 that’s why we need this converter - Knowledge and skills to make simple PCB by our selfs The tower: - cardboard – two different thicknesses - Tracing paper - aluminum foil Step 2: Tower Building Above the plan of the tower in side view (my adventure with the technical drawing ended in primary school), all dimensions in millimeters. Principle of operation - ring of LEDs shedding light on - Tracing paper - The truncated cone, made of cardboard and covered with aluminum foil, so it reflects lights from led rings, in figure 3 ‘ = the cut-out mesh - carton tube – holds the towers vertically, inside the tube are cables for leds - The height depends on you I have 85mm - The Stand inside all electronics parts All horizontal elements should be made of thicker cardboard. Step 3: Wiring Diagram The mp3 player is supplied with 5V voltage and communicates with Arduino via TX / RX, a logic converter is needed because the Arduino itself works on 3.3V voltage. The control of rings is also connected to Arduino (D5, D6) through the logic converter. At repository, You will find eagle files with PCB plans I suggest not to solder permanently Arduino and the mp3 player only to use female goldpins Step 4: Principle of Operation Our Arduino connects to the app.remoteme.org system using WebSockets (there are ready libraries) through this connection 5-byte messages are sent: - source code Whole source code You can find here in the SingleRing.cpp and SingleRing.h files there is a class to control the effects of LED rings. I suggest you start by looking at the setMode(int m) function: void SingleRing::setMode(int m) { switch (m) { case 0:setConfiguration(0, 0, 50, 0, 5, 1); break;//off =0 case 1:setConfiguration(6, 0, 50, 0, 0, 20); break;//solid standard green case 2:setConfiguration(6, 0, 0, 50, 0, 20); break;//solid standard blue case 3:setConfiguration(6, 50, 0, 0, 0, 20); break;//solid standard red case 4:setConfiguration(6, 50, 10, 0, 0, 20); break;//solid standard orange case 5:setConfiguration(1, 0, 100, 0, 5, 2); break;//police clockwise green case 6:setConfiguration(1, 0, 100, 0, 5, -2); break;// police revert green case 7:setConfiguration(1, 0, 0, 100, 5, 2); break;//police clockwise blue case 8:setConfiguration(1, 0, 0, 100, 5, -2); break;// police revert blue case 9:setConfiguration(1, 100, 0, 0, 5, 2); break;//police standard red case 10:setConfiguration(1, 100, 0, 0, 5, -2); break;// police revert red case 11:setConfiguration(1, 100, 20, 0, 5, 2); break;//police standard orange case 12:setConfiguration(1, 100, 20, 0, 5, -2); break;// police revert orange case 13:setConfiguration(2, 0, 0, 50, 8, 10); break;//cross standard blue case 14:setConfiguration(2, 0, 0, 50, 8, -10); break;// cross revert blue case 15:setConfiguration(5, 0, 50, 0, 0, 20); break;//blink standard green case 16:setConfiguration(5, 0, 50, 0, 0, -20); break;// blink odwyrtka green case 17:setConfiguration(5, 0, 0, 50, 0, 20); break;//blink standard blue case 18:setConfiguration(5, 0, 0, 50, 0, -20); break;// blink revert blue case 19:setConfiguration(5, 50, 0, 0, 0, 20); break;//blink standard red case 20:setConfiguration(5, 50, 0, 0, 0, -20); break;// blink revert red case 21:setConfiguration(5, 50, 10, 0, 0, 20); break;//blink standard orange case 22:setConfiguration(5, 50, 10, 0, 0, -20); break;// blink revert orange default: setConfiguration(0, 0, 50, 0, 5, 1); break;//off =0 } } depending on the given parameter, the ring will display the effect. You can add your own effect by calling function setConfiguration with new parameters (change of color, display speed) by adding a new mode, or adding a completely new effect – or let me know in the comments if I like it I will add new effect arduino.ino: #include "Arduino.h" #include "SoftwareSerial.h" #include "DFRobotDFPlayerMini.h" #include #include #include #include "SingleRing.h" #include #include #include #include #define WIFI_NAME "" #define WIFI_PASSWORD "" #define DEVICE_ID 205 #define DEVICE_NAME "siren" #define TOKEN "" #define DIODES_COUNT 16 SingleRing top = SingleRing(DIODES_COUNT, D5); SingleRing bottom = SingleRing(DIODES_COUNT, D6); SoftwareSerial mySoftwareSerial(D4, D3); // RX, TX DFRobotDFPlayerMini myDFPlayer; RemoteMe& remoteMe = RemoteMe::getInstance(TOKEN, DEVICE_ID); ESP8266WiFiMulti WiFiMulti; void setup() { mySoftwareSerial.begin(9600); Serial.begin(115200);.setTimeOut(500); //Set serial communictaion time out 500ms myDFPlayer.volume(30); myDFPlayer.EQ(DFPLAYER_EQ_NORMAL); myDFPlayer.outputDevice(DFPLAYER_DEVICE_SD); WiFiMulti.addAP(WIFI_NAME, WIFI_PASSWORD); while (WiFiMulti.run() != WL_CONNECTED) { delay(100); } remoteMe.setUserMessageListener(onUserMessage); remoteMe.setupTwoWayCommunication(); remoteMe.sendRegisterDeviceMessage(DEVICE_NAME); top.setup(); bottom.setup(); top.clear(); bottom.clear(); } boolean turnedOff = true; unsigned long turnOffMillis = 0;; } void loop() { remoteMe.loop(); top.loop(); bottom.loop(); if (turnOffMillis } explanation: #define WIFI_NAME "" #define WIFI_PASSWORD "" #define DEVICE_ID 205 #define DEVICE_NAME "notificator" #define TOKEN "" We need to provide above data, detailed instructions here at the link also I’ve shown how to register in remoteme.org and generate the token,; } This function will be called when the message comes to Arduino and displays the notification. The code is so clear that it describes itself. I refer to the details of the classes to the documentation here and here void loop() { remoteMe.loop(); top.loop(); bottom.loop(); if (turnOffMillis<millis()){ if (!turnedOff) { top.clear(); bottom.clear(); myDFPlayer.stop(); turnedOff = true; } } In the loop, we call the loop functions of the objects, and also if the display time of notifications has passed, we turn off the diodes and sound. Step 5: Mp3 Player It communicates with Arduino via TX / RX – Details of the player itself here, and the library here We upload mp3 files to the SD card. Files on the card are sorted alphabetically and then by calling: myDFPlayer.play(5); We play the fifth file from the SD card from the root directory. That is why it is good to give files on the SD card prefixes 01, 02 etc. In my case it looks like at the above printscreen To generate voice commands You can use this page. Step 6: Uploading the Program to Arduino Step 7: Control We send to our Arduino five bytes - (1 if it should be played in a loop) By sending bytes 07 0F 01 05 01 Top ring will be showing the police lights (mode 6) bottom one blink green (mode 15) (check out setMode function at singleRing.cpp and comments next to it). The first file form the SDcard will be played for 5 seconds. And the file will be played in the loop (check function onUserMessage at arduino.ino ) Let’s send these bytes. Look at the screen above, and click icons in order written by 1,2,3. The window appears Then look at second screen - and fill window as at the second screen The window that appears is used to send messages to the device. In field 1, select the sender device – because we have only one device, we select it (this is a mandatory field and it does not matter that it is the same device to which we send a message) In field 2 we give bytes to send (in red the value we entered in 2 will be represented as a string) then click the Send button. After sending the message, our notifier should react by displaying the appropriate lighting effects and playing the selected mp3. I encourage you to try different effects by giving the first two bytes of a number between 0 and 22 (see description in the setMode function). Step 8: Sending Messages Using URLs If we want to display notifications from an external application eg with IFTTT, we need to have a URL that will do exactly the same thing as we did in the window in the previous step. remoteme.org provides REST APi. Go to it by clicking on the swagger tab in the left (the last one). A page will be displayed, on this page we can also try our URLs. At the first screen You have the function You need to expand, then fill data as at the second screen. fill in the data as in the above screenshot. After clicking the execute we will send a message 070F010501 The receiver is the device with 205 id, the same device is also a sender. MessageId with the “No_RENEVAL” settings is irrelevant. And then click Execute. Notificator will react in the same way as when sending messages from the application. After calling REST below is the URL that was called - look at the third screen. And copy and paste to browser URL was is marked with green border. At fourth screen my chrome browser after URL was pasted In my case, the URL is:*/rest/v1/message/sendUserMessageHexString/205/1/NO_RENEWAL/1/070F010501/ Step 9: Anymous URL to Send Message At previous step You have an URL which sends data to your device. Unfortunately, after logging out of app.remoteme.org, it stops working. This is because we did not provide the authentication token, and we are no longer logged in. Let’s get our token (or create a new one) and paste it into the URL instead of the star. Look at the screen and replace * in URL with your token in my case token is: ~267_ZxoWtJ)0ph&2c so my final URL looks like:)0ph&2c/rest/v1/message/sendUserMessageHexString/205/1/NO_RENEWAL/1/070F010501/ Now we can call it even if we are not logged in. And when it is called, a message will be sent to our device 205 Step 10: Integration With IFTTT 1/7 Url created in step above is suitable for execution by external applications. How to use it I will show on the IFTTT. I will configure it so that the notifier turns on when an email comes to the email address (Gmail account). Log in to IFTTT.Then go to the My Applets tab and then “New Applet”- first screen Step 11: Integration With IFTTT 2/7 Next click “+this” Step 12: Integration With IFTTT 3/7 Then in field “Search services” write “Gmail” Then "new email in inbox" (Some configuration could be needed). Step 13: Integration With IFTTT 4/7 now we click on “+ that” Step 14: Integration With IFTTT 5/7 find “Webhooks” and click it Step 15: Integration With IFTTT 6/7 then “Make a web request” Step 16: Integration With IFTTT 7/7 we complete the URL of our url with the token. Content type to application / json and click “create action” and Finish. Now we have our applet: Step 17: Summary In this tutorial, I showed how to send to our Arduino messages from external systems. We also integrate some other system then IFTTT in a similar way. It does not necessarily have to be a “notificator” I wanted to show in this example how to send messages from outside systems to our Arduino. sourcecodes FanPage at Facebook Cheers, Maciek Discussions
https://www.instructables.com/id/Notificator/
CC-MAIN-2018-39
refinedweb
1,913
55.27
/MiddleKit/Tests/MKInheritance.mkmodel In directory usw-pr-cvs1:/tmp/cvs-serv11738/Tests/MKInheritance.mkmodel Modified Files: TestEmpty.py Log Message: - Remove ObjectStore.Store var which referred to the first store that happened to be created. - Remove the store arg to MiddleObject.__init__(store) which was little used and confusing. - Test suite clean ups. - Make MKMultipleStores test having 2 different stores. This works now. - Can now have two WebKit contexts that use MiddleKit without problems. - Add MKMultipleStores to default set of test suites. Index: TestEmpty.py =================================================================== RCS file: /cvsroot/webware/Webware/MiddleKit/Tests/MKInheritance.mkmodel/TestEmpty.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TestEmpty.py 12 Jul 2001 03:16:55 -0000 1.4 --- TestEmpty.py 3 May 2002 14:26:29 -0000 1.5 *************** *** 1,9 **** ! def test(): import os from One import One from Two import Two - - from MiddleKit.Run.ObjectStore import Store as store # Note: Two inherits One --- 1,7 ---- ! def test(store): import os from One import One from Two import Two # Note: Two inherits One
https://sourceforge.net/p/webware/mailman/message/4463708/
CC-MAIN-2017-51
refinedweb
180
56.01
I’ve made a simple program for displaying the pixels stored in a framebuffer by drawing the squares and everything is working well except I can’t explain the visible lines between the squares when I draw them with a transparent color. I am drawing the squares with the very same stroke and fill transparent colors (0x20a0a0a0) and the squares don’t overlap but there are visible darker lines between all the squares. If the color is not transparent (0xffa0a0a0) then everything is as expected. Here is the code: def setup(): global scr size(800, 600) scr = screen(50, 60, 0x20a0a0a0) # transparent color, visible lines between squares!? #scr = screen(50, 60, 0xffa0a0a0) # <-- no transparency, no lines my_point(28, 4, 0xff0000ff) # blue point noLoop() def draw(): draw_screen(10) def screen(height, width, color): s = [] for i in range(height): row = [] for j in range(width): row.append(color) s.append(row) return s def draw_screen(pixel_size): global scr for y in xrange(len(scr)): for x in xrange(len(scr[0])): stroke(scr[y][x]) fill(scr[y][x]) square(x*pixel_size, y*pixel_size, pixel_size) def my_point(x, y, color): global scr scr[y][x] = color
https://discourse.processing.org/t/transparency-not-working-as-expected/27151
CC-MAIN-2022-27
refinedweb
195
52.53
Although Visual Studio .NET Setup projects handle the most common installation requirement, some applications will need to perform some extra steps at installation time. For example, your application might install custom performance counters or create a message queue. To enable operations such as this, Windows Installer supports custom actions. A custom action is a piece of code supplied by you that will be invoked during the installation process. As Figure 6-18 shows, the Custom Actions view presents four folders. These represent various stages of the installation phase. Remember that the user sees the installation progress through three phases: information collection, installation, and confirmation. The installation phase itself, however, can go through up to four different stages, described later. You can add a custom action to any or all of these stages. Items placed in the Install stage will be run after Windows Installer has completed all other installation work, which means that by the time your custom action runs, all files and registry settings will be in place. Custom actions in the Install stage are allowed to abort the installation (see details later). If you want to run a custom action only after it is certain that the installation has completed successfully, you can place it in the Commit stage. Of course, actions in the Commit stage are not able to abort the installation. Actions in the Rollback stage will be run if the application installation aborts before completing. Actions in the Uninstall stage will be run when the user uninstalls the application. You can add items to a stage with the context menu's Add Custom Action... item. If you select this item from the Custom Action item's context menu (instead of one of the four stages), the action will be added to all four phases. When adding an action, you will be shown the usual item selection dialog shown in Figure 6-19. You can select any .exe, .dll, or script file in any of the folders from the File System view. If you specify an .exe file, Windows Installer will run the program at the chosen stage. You can specify command-line parameters with the Arguments property. You can pass installer properties by putting them in square brackets (e.g., [EDITA1] will pass the contents of the first textbox on the Textboxes (A) screen). Remember to put quotes around any properties whose values might have spaces in them. If your custom action is in the Install phase, you can abort the installation by returning a nonzero exit code. This will cause the installation to go through the rollback procedure, undoing any work the installer has done so far. If you specify a DLL, you must also tell Visual Studio .NET what entry point it should call, using the EntryPoint property. You can give the method whatever name you like, but it must use the _ _stdcall calling convention, and take an MSIHANDLE as its sole parameter. Example 6-1 shows a suitable function declaration. You should also set the custom action's InstallerClass property to false. (If you set it to true, Visual Studio .NET will presume that the DLL is a .NET assembly and will look for an installer class. See Section 6.10.2 for details on how to write a .NET custom action.) int _ _stdcall CustomAction(MSIHANDLE hInstall); You can pass data to the action by setting the CustomActionData property in Visual Studio .NET. The DLL will be able to retrieve this using the MsiGetProperty API. Any installer properties passed in square brackets will be expanded by Windows Installer before being passed to the DLL via the CustomActionData property. DLL-based custom actions should return a status code. ERROR_SUCCESS indicates that the action succeeded. It can indicate a failure in two ways: ERROR_INSTALL_USEREXIT means that the user decided to terminate the installation process during the custom action. ERROR_INSTALL_FAILURE means that the custom action was unable to complete for some reason. If you write a custom action as a script file, it will also have access to the CustomActionData property. When Windows Installer launches a script, it makes a global object named Session available. This has an indexed property named Property, which you can use to retrieve the CustomActionData property. Example 6-2 shows a snippet of VBScript illustrating this technique. data = Session.Property("CustomActionData") Custom actions in scripts cannot abort the installation process. This is a Visual Studio .NET limitationalthough Windows Installer supports this functionality, it relies on the script being contained in a function so that it can have a return code. Unfortunately, Visual Studio .NET provides no way of specifying the name of the function, so only global code can be executed, which has no means of returning a value. Scripts will be run inside a special scripting host supplied by the Windows Installer. This means that your script will not have access to the normal intrinsics that would be available in the WSH (Windows Scripting Host) host. However, it is easy enough to get hold of the standard WSH objects if you need them. Example 6-3 shows how to retrieve a registry setting using the WSH shell RegRead function from within an installer script. Dim WSHShell, CLSIDRegPath, CLSID Set WSHShell = CreateObject("WScript.Shell") CLSIDRegPath = "HKCR\EvilCorp.Engine\CLSID\" CLSID = WSHShell.RegRead(CLSIDRegPath) The code in Example 6-4 shows an example custom action DLL written in C++. It creates a text file containing the installation date of the application. The location of the file created by this installer is determined by a GetInstallFilename function, not shown here. This could use the MsiGetProperty API to retrieve the CustomActionData property, allowing installer properties to be passed in. For example, if the custom action's CustomActionData property were set to [ProgramFilesFolder][Manufacturer]\[ProductName], the custom action could create the file in the program's installation directory. extern "C" _ _declspec(dllexport) int _ _stdcall Install(MSIHANDLE hInstall) { std::string fileName; if (!GetInstallFilename(hInstall, fileName)) return ERROR_INSTALL_FAILURE; FILE* f = fopen(fileName.c_str( ), ("w")); if (f = = NULL) { return ERROR_INSTALL_FAILURE; } else { SYSTEMTIME sysTime; ::GetSystemTime(&sysTime); fprintf(f, "Installed on %d/%d/%d\n", (int) sysTime.wYear, (int) sysTime.wMonth, (int) sysTime.wDay); fclose(f); } return ERROR_SUCCESS; } static int RemoveFile(MSIHANDLE hInstall) { std::string fileName; if (!GetInstallFilename(hInstall, fileName)) return ERROR_INSTALL_FAILURE; // Silently ignore errors--it is possible that we might // not have successfully created the file during installation, // in which case deleting it won't work either... ::DeleteFile(fileName.c_str( )); return ERROR_SUCCESS; } extern "C" _ _declspec(dllexport) int _ _stdcall Rollback(MSIHANDLE hInstall) { return RemoveFile(hInstall); } extern "C" _ _declspec(dllexport) int _ _stdcall Uninstall(MSIHANDLE hInstall) { return RemoveFile(hInstall); } This particular custom action DLL provides Install, Rollback, and Uninstall methods. You would therefore add this DLL three times in the Custom Actions view, under the Install, Rollback, and Uninstall phases. (This particular code doesn't have anything useful to do at Commit time.) Each place the DLL appears in the Custom Actions view, you would set its EntryPoint property to be the name of the appropriate DLL entry point (i.e., Install, Rollback, or Uninstall). If you are writing a .NET project, automated support is available for certain operations that would normally require you to write code. If you need to configure a message queue, an event log source, or a performance counter on the target system, Visual Studio .NET can add installation components to your project that will do all of the necessary work for you. All three of the supported installation component types use the same basic model. They assume that you will configure your development system so that it has whatever message queues, event log sources or performance counters your application requires. Visual Studio .NET is then able to examine the items you have created and add an installation component to your project that can create an identically configured item on a target machine. You can add as many installation components as you like to a project, but they are all managed by a single Installer class. The Installer class will be invoked at installation time and will run each installation component in turn, in order to configure the target machine to your application's needs. This mechanism relies on installer custom actions. You must add a project that uses .NET installation components as a custom action in the usual way, but you must set the custom action's InstallerClass property to true. This changes the way that Windows Installer will use the component. Instead of executing the program (or calling a named entry point in the case of a DLL), it will search for the Installer class and allow that to control the custom action. Installer classes live in the main application project. You can add an Installer class to your application with the usual Add Project Item dialog. Simply choose Installer Class from the Code category. This will add a new class that derives from the Installer class (which is defined in the System.Configuration.Install namespace). It also marks it with the RunInstaller custom attribute, which enables Windows Installer to locate the class at installation time. A newly added Installer class will not do anything at installation time. If you want to add some code of your own, you can override any of the Install, Commit, Rollback, or Uninstall methods, which will get called at the relevant phases. But since the main point of using this mechanism is to automate the configuration of certain system resources, you will normally want to add installation components to the installer. To add an installation component for a message queue, event log source, or performance counter, your main project must be using a component that represents the item in question. If you don't already have such a component in use in your project, you could drag the relevant item from the Visual Studio .NET Server Explorer onto, say, a Form. (Any design view will do.) When you select an object, if it can have an associated installation component in the designer, the Properties window will show an Add Installer method in the verb panel. Figure 6-20 shows the Properties page for a PerformanceCounter component, with the Add Installer method visible in the middle. If you have not yet added an Installer class to your project, clicking on Add Installer will create one for you, calling it ProjectInstaller. It will then add an installation component to the Installer and will show you the Installer class's design view. (The Installer's design view consists of just the component tray.) The Installer will now contain an entry for the installation component you just added. This item's properties will contain enough information to create a new item on the target machine. (Either a message queue, event log source, or performance counter, depending on what type of component you added an Installer for.) The item it creates on the target will have all the same characteristics as the original, unless you edit its settingsinstaller components let you modify all of the information they contain, just like any other component, as Figure 6-21 shows. The Installer class will automatically install any components that you add in this fashion. You do not need to write any code; you simply need to make sure that the executable is added as a custom action for all installation phases and that its InstallerClass property is set to true. (When you add a custom action for a binary that contains an Installer class, Visual Studio .NET automatically sets the InstallerClass property to true, so you should find that the defaults are correct.) If you want to add code of your own to the Installer class, you may want to pass information such as the value of properties selected by the user earlier in the installation. Once again, the CustomActionData property should be used. However, it must use a certain format, because it will be parsed by the Installer class. It should take the form of name-value pairs, specified as /name=value. Pairs should be separated with a space. If the value contains a space, it should be enclosed in quotes. These name-value pairs are available through the Installer class's Context property. The Context has a Parameters property, which is a dictionary of strings containing the name-value pairs passed in CustomActionData. The way that we pass user input to the custom action is to place it in the CustomActionData property. For example, if the installation user interface uses the Textboxes (A) page, the installer property EDITA1 will contain the string the user entered in the first edit box on that page. Custom actions don't have access to most installer properties, so, by default, a custom action will not be able to retrieve this information. However, we can set the CustomActionData property to /FavoriteColor=EDITA1, enabling the custom action to retrieve this value using the code shown in Example 6-5. You can pass multiple values if necessary. For example, you might set the CustomActionData property to /FavoriteColor=EDITA1 /Weapon=BUTTON4VALUE to pass in a text field and a radio button setting. string somePropVal = Context.Parameters["FavoriteColor"];
http://etutorials.org/Programming/Mastering+visual+studio+.net/Chapter+6.+Setup+and+Deployment/6.10+Custom+Actions/
crawl-001
refinedweb
2,193
55.44
Hello, I'm new to HCP and looking to set up a journal and email archiving solution using HCP and Symantec Enterprise Vault. - Is there any benefit to using two tenants (one for journal and one for email) as opposed to one tenant and two namespaces? - What beneficial features of the HCP are available for using with EV, e.g. compression? - I have two sites (active/passive) - any tips on DR? - Any 'gotchas' I need to consider? Thanks Good morning, 1. One or more tenants: The disadvantage is that you loose another tenant and you only have 100. 2. Benefiets using HCP: All the HCP has (too many to listen here) 3. In the EV plugin, you specify both the primary and the secondary HCP. So I assume EV is HCP-replica aware - but I have not found written it down. 4. Have the application do disposition and retention. I.e. in case HCP disposites an object after retention, the application is not aware and possible could refer to it. Kind regards, Henk
https://community.hitachivantara.com/thread/6541-hcp-and-symantec-enterprise-vault-for-exchange
CC-MAIN-2019-13
refinedweb
173
75.3
About this talk We'll dive into the tools available inside the Rake library (hint: it's more than just rake db:migrate), and discuss how changes in Rails 5 might affect how we use it going forward. Transcript Diving into Rake and its future in Rails, yeah that's what we're going to discuss today, from the point of view of someone who doesn't really know Rake or is new to it or is new to Ruby on Rails and is sort of used Rake but doesn't know why they have to use it when they're setting up their environment or running Rake DB migrates, or something like that. So what is it? It's a task management tool that we use in Rails and in Ruby. It helps automate builds and it comes with a few main sort of task management I suppose tools, being FileTask and Task. They do two slightly different things. Task is what we mainly use to I suppose provide something to build up our environments, so our sort of Dev environment if you want to populate it with data, we'll probably create a task and then give it something to do in the block, and then, viola, out pops our information. Whereas a FileTask usually helps convert something, let's say for instance, HTML into an ePub file. If you're, you might be I don't know releasing a book on Amazon or something like that, that's what that might be used for. And again, yeah, it's really handy for setting up our environments, we use it a lot to set up our Dev environment, we're constantly dropping it, recreating it, adding new data, yeah. So, I'm going to kinda start from the somewhat basic approach I suppose, to creating a Task in Rake. And the way you can create it in a Rake file if you want, in the main Rake file right in the root directory in your app. The neater way to do it I think is to add it into your lib tasks path. And then, namespace it, give it something nice and descriptive. So in this case, we're gonna do, we're gonna rake some leaves as a chore. So we've got a chore file, which is namespace chore, and then running this task would be as simple as saying rake, chore, rake leaves. And then our output sort of appears. And then using this namespace and that sort of description command can be helpful later on, I mean it is not so necessary right now but it's useful for some of the commands that Rake provides you. So if you were actually working in a large Rails application you might loads of tasks, and loads of different files that you're running through, some that you just get from the start and some you add later, so it might come in handy, we'll discuss that later. Yeah, before I move to that slide, so this being very very basic, it's probably not very descriptive of actually what's involved for instance in raking leaves, a few things that you need to rake leaves you need to rake. You might need a paper bag as well to store the leaves in there's usually some element of travel as well, to get those things, to buy them, so one of the cool things that Rake allows is dependencies, so if we're actually building this task to kind of maybe more, mimic real life, raking leaves is actually gonna be dependent on a couple of things, one that we have a rake, and two that we've got those paper bags, that we can store those leaves in, and then to shuffle them off to the garbage man as they come around. So this is what it sort of looks like here. We've got the rake leaves task, which is gonna dependent on buying the rake, and buying the bags, and then both of those are dependent on going to the store, as we have to go to the store to then buy these things. Now what rake is also very good at is not running tasks multiple times, so if we run our task again, in this case here, so rake chore rake_leaves, you'll see the output from here starting from the go_to_store task, we've printed out once heading to the store, and then buy_paper_bags and buy_rake, we know that that task is now run, it's that dependency is satisfied, and then they can both run and thus you can complete it, rake leaves and you're happy. That's sort of the basic of that namespace, so moving on from creating the task and creating something kind of basic like this, we can jump into some neat tools that are provided. One of them being Rake Notes. So as part of your application, you're always especially in a larger one, you're always gonna encounter something that you, you might find that this needs reworking, this isn't right. But it's not within the scope of the ticket that I'm looking on right now. Well just, whatever item you're dealing with, it might be a really big rework, something that you've not really noticed, you might inherited the app, whatever it might be. Really great tool is adding a to do in a comment and then just, just listing something simple to bring your attention back to, and what you can then do is run rake notes in your terminal and it will search for anything that has todo, I believe fix me, and optimise as standard as default, and print those out in the console for you, so you can look and manage anything that might need rework, so for a later day, if you're saving things down, it's a good tool to use for that. And then as well, the other note is if you want something a bit different than todo, fix me, or optimise, you can add your own custom notes and annotations, so you provide the note and the annotation, it will go and find those notes to run your application. So Rake -D, so before we were adding the description to a chore rake_leaves task or just above it, this is what will actually pull it out. So you can output all of them, just by running that command by default, and it will print everything out that has a description in all of your tasks. So then you kind of search through there if you're looking for something specific or you might be able to if you kind of know the task you're looking for, then you can actually provide the task name, which holds that description which is under that description and it will find that for you. So if you I gave it specifically the rake_leaves task and then it just returned that one task for me. The other one is Rake -P, so it will actually list every task, if you sort of go, I think this one won't accept a pattern but it will print out everything, all of your tasks and all of their dependencies, and this, as I'll kind of show later on, is actually really helpful, or can be helpful in debugging your application or debugging a task that might not be working for whatever reason. So yeah, so that kind of shows you our little rake task rebuilt earlier. And sort of the late addition that I kind of came across is Rake Stats, which I kind of found really just, it's not immensely helpful but it's kind of good to know. You'll see here, in the application that I just sort of threw up, code to test ratio isn't great but it's good to know. Yeah I think a lot of people usually go out of their way to find a tool as well to kind of check that, that ratio, that metric, and so it's handy that it's, it comes default with Rake, you can actually just have a quick look. And sort of see where you will test it, where you're building those for your test as well. I know there's that testing pyramid that people like to try and follow so you can actually kind of see just by running this, if you are kind of following that type of metric, where most of your model, tasks, and features and so on, or integration. Yeah so before when I was describing that Rake P thing, I will sort of bring it in to how this helps with tracing in Rake. So the main way to trace in Rake, is by running the command dash trace or --trace to your tasks. So let's say we move that dependency in our previous task, which is just go_to_store, so there's a couple of things, a couple of items obviously that rely on it. So it's gonna, something's gonna break. When we run it initially, all the feedback we get is rake aborted, doesn't have know how to build the task go_to_store but when you're running rake chore, rake_leaves, you've got no idea that just from that one input that there might be a dependency go_to_store unless you've built that task yourself or built that namespace yourself. So you might, if you've got a sort of relatively small app, it might be easy, you might have a good tool for grep-ing and you can jump in, the other option is to run trace. So now this is really small and probably not great, probably should of not included this crap down there, but what this ends up doing is providing a little bit more information as to what Rake was trying to do when it broke, when it aborted basically. So you've got, invoke chore rake_leaves for the first time, and then invoke chore buy_rakes, so it's running down that sort of, that file in order, and it's looking at buy_rake and then stopping. So if we do want to kind of find out what's going on from here, what it's dependencies are, we can now run rake -p and have a quick look and see what does buy_rake depend on, oh it depends on go_to_store, and then we can, I think it was, if you run rake -w, and if you give a task, it will give you the file path and line number for it, so it's another little kind of jump ahead, so if you're still unsure as to where it is, you can't find it, you can actually run that and then we can go and then obviously fix issue, include go_to_store and everyone's happy. Yeah so I guess that's just a few that kind of maybe are standard tools that are really helpful with debugging in Rake. And then jumping on, so Rake is obviously, I'm not sure if everyone's aware, it's slightly changing how we use Rake, so we're still gonna use it going forward but it's actually gonna be encompassed in Rails 5 in the rails command. So previously, especially when you're new to Ruby on Rails, you'll be setup running rails dbmigrate I'm sorry and then rake dbmigrate and then you're using Rails to generate your models controls whatever it might be, your application in general, it's a bit of swapping around, and I knew for myself in being a beginner in Ruby on Rails, I didn't really know why, what the difference was, why run rake or why we run rails, so Rails 5 uses the rake proxy to sort of act as a wrapper around rake, and what it will do is when you run rails dbmigrate now for instance, it will check if that command is native to rails, and if it isn't, then it will hand it off to that proxy, and so then it will say, ah this is a rake command, so then it runs the command through there. So you see, things change from rake dbmigrate to rails dbmigrate, and then there's a few things as well to note, so I think now in Rails 5, you can actually also run rails roots rather than rake roots, you can provide it a path and because rails actually accepts arguments as well, you'll be using things like rails console and then provide it development. So you don't have to, it's a sort of, it's more intelligent way of I suppose providing or running commands, it can do quite a few things. It's a bit of an element of magic I suppose because now we're hiding yet another thing inside the application, which I know quite a few people don't really like about Rails I guess you could say, but it's really neat and I think it's, I think it's a neat tool for the beginners coming in and to make development a little bit easier and yeah swapping through you're just always running the same thing, just keep things consistent I suppose. And I suppose the other thing to note is there are a few rake tasks as well that actually use the rails namespace, so the rails rake proxy is done now, has actually renamed those, so they actually are, let's say rake rails update I think was one, or rake rails template, those are now, will be rails app template or rails app update, it's changing the names, just to I suppose just to be a bit more explicit I suppose in what they're doing. But yeah that was a little bit about my talk about Rake. So we just kind of went through building a really simple rake task, namespacing it, some of the neat tools you kind of get with Rake, as standard and how we can use that in some hopefully really helpful ways, and what then what it looks like in Rails 5 forward. Yeah that's me, thank you for listening.
https://www.pusher.com/sessions/meetup/north-west-ruby-user-group/diving-into-rake-and-its-future-in-rails
CC-MAIN-2019-39
refinedweb
2,417
58.39
Authenticate a Customer to Alexa with Permissions You must authenticate a customer in your system with Alexa when you respond asynchronously to a directive or when you send change reports to the Alexa event gateway. You provide the authentication information Lambda function with the AcceptGrantdirective. You must store the access and refresh tokens for a customer and include the access token in each asynchronous or change report event. Before the token expires, you should use the stored refresh token to get new access and refresh tokens. Access tokens are valid for 60 minutes. For details, see LWA Access Tokens, In addition, when a skill is migrated from v2 to v3, and you have requested permission to send events to the Alexa event gateway, there is a backfill process and you will receive an AcceptGrant directive for every customer that has enabled your skill. Be prepared to receive these messages and complete the authentication process. Steps for asynchronous message authentication. { "directive": { "header": { "namespace": "Alexa.Authorization", "name": "AcceptGrant", "messageId": "5f8a426e-01e4-4cc9-8b79-65f8bd0fd8a4", "payloadVersion": "3" }, "payload": { "grant": { "type": "OAuth2.AuthorizationCode", "code": "VGhpcyBpcyBhbiBhdXRob3JpemF0aW9uIGNvZGUuIDotKQ==" }, "grantee": { "type": "BearerToken", "token": "bearer-token-representing-user" } } } }: api.amazonalexa.com Authorization: Bearer Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR... Content-Type: application/json { "context": { "properties": [ { "namespace": "Alexa.LockController", "name": "lockState", "value": "LOCKED", "timeOfSample": "2017-02-03T16:20:50.52Z", "uncertaintyInMilliseconds": 1000 } ] }, "event": { "header": { "namespace": "Alexa", "name": "Response", ": "Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR..." }, "endpointId": "appliance-001" }, "payload": {} } }. Requesting new authorization codes If you lose the access and refresh tokens associated with a customer or customers, you will need to request new ones using our backfill process. Use the contact form on the Developer Support page to start the process. When you submit this form, you will be added to a list and we will resend AcceptGrant directives for each customer that has enabled your skill. Provide the following information: - Email address: Provide an email address for a developer account associated with your skill. - Subject: Alexa - Message: Request an authentication backfill for your skill, and provide your skill ID. You could receive up to 10 transactions per second, and if you cannot handle that number of messages, you should let us know in your contact request. You must send synchronous events until the backfill completes as any responses sent to the Alexa event gateway will fail. Notification of expired token and using the refresh token If you send a message to the Alexa event gateway with an expired token, you will receive an HTTP 401 Unauthorized response. For details, see Event gateway error codes. As a best practice, before the access token expires, use the refresh token to request new access and refresh tokens from LWA. A token expires after an hour. For details about how to use the refresh token, see Using Refresh Tokens. Revoking authorization Alexa revokes the authorization grant for the following reasons: - A skill is disabled by the customer - A customer explicitly removes consent for the skill by accessing the Your Account > Manage Login with Amazon page of their Amazon account. Notification of a revoked grant There are two main ways you are notified that a authorization grant has been revoked: - You get a HTTP 403 when you send an event with a token that has not expired. This happens when the skill is disabled or a customer removes consent, but the token you obtained has not reached its expiration time. Example 403 Response HTTP/1.1 403 Forbidden Date: Wed, 07 Mar 2018 20:25:31 GMT Connection: close { "header": { "namespace": "System", "name": "Exception", "messageId": "90c3fc62-4b2d-460c-9c8b-77251f1698a0" }, "payload": { "code": "SKILL_DISABLED_EXCEPTION", "description": "Skill is disabled. 3P needs to specifically identify that the skill is disabled by the customer so they can stop sending events for that customer" } } - You are not able to refresh a token. In this situation, when you try to refresh the token, you get an invalid_granterror code from LWA. This is a permanent state and indicates that the authorization has been revoked by the customer. For details, see the Access Token Errors. When a customer removes consent, the authorization grant is revoked and your skill is denied access to some or all resources associated with the customer account. You must have logic in your skill and supporting systems to stop sending events that rely on the grant, such as asynchronous messages to the event gateway. Other parts of the skill must function as normal.
https://developer.amazon.com/de-DE/docs/alexa/smarthome/authenticate-a-customer-permissions.html
CC-MAIN-2021-43
refinedweb
728
53.81
Python is powerful yet simple and easy to grab for beginners compared to other programming languages. The sequence is the basic data structure in Python. Each element of a sequence is assigned a number – its position or index. In a sequence, the first index is 0; the second index is 1, and so on. Python has six in-built sequential data structures. Among them all, the lists, tuple, and array is widely used in Python. This article will discuss the Python lists and how to subtract two lists in Python. Before approaching further, let’s make sure we have a good understanding of Python lists. People often messed up in between arrays and lists. For now, let’s agree Python lists are like arrays though there is a tiny difference among them. Lists are the most versatile and dynamic datatypes in Python. We can store different types of data inside a list. It doesn’t matter if they are numbers, characters, or strings. To initialize a list, we must put all the values inside a square bracket and differentiate each value using a comma. Elements of a list are known as the item. Please, note that lists are mutable. We can add, remove, modify the items anytime in a Python program. Here is an example of the Python list: demo_list1 = ['Mark', 'Alex', 1987, 2020] demo_list2 = [5, 4, 3, 2, 1 ] demo_list3 = ["x", "y", "z"] To print a list, we just need to write the print() function in Python. Like this way: print(demo_list1) Now, let’s one more step ahead to reach our goal-subtract two lists in Python. We can determine the difference between the two lists mainly in two different ways. Let’s get started. Using the set() Set is a collection-type object which can store elements of different data types. A set() doesn’t index the values in a particular order. This method converts the lists into the python sets explicitly and then finds the difference between them. Here is a sample program is given for your better understanding. def list_diff(my_list1, my_list2): return (list(set(my_list1) - set(my_list2))) my_list1 = [10, 16, 21, 26, 31, 36, 41] my_list2 = [10, 26, 41, 36] print(list_diff(my_list1, my_list2)) Output: [16, 21, 31] The set() function accepted the defined two lists in the above program and turned them out into sets. Inside the print() function, it just calculated the difference. Using a nested for-loop To calculate the subtract value between two different lists, we can simply use a nested for-loop. In this method, we’ll compare all the second list items with the first one sequentially, and while traversing, we’ll be appending every non-matching item to a new empty list. End of the program, we’ll print the list. Here you go: def list_diff(my_list1, my_list2): out = [] for ele in my_list1: if not ele in my_list2: out.append(ele) return out my_list1 = [10, 16, 21, 26, 31, 36, 41] my_list2 = [10, 26, 41, 36] print(list_diff(my_list1, my_list2)) Output: [16, 21, 31] Using the list comprehension method List comprehension is the same method as the nested for-loop. Here we will replace the for-loop with the list comprehension syntax. For instance, def list_diff(my_list1, my_list2): out = [item for item in my_list1 if not item in my_list2] return out my_list1 = [10, 16, 21, 26, 31, 36, 41] my_list2 = [10, 26, 41, 36] print(list_diff(my_list1, my_list2)) Output: [16, 21, 31] We hope that after wrapping up this tutorial, you should know several ways to subtract two Python lists. However, you may practice more with examples to gain confidence.!
https://maschituts.com/how-to-subtract-two-lists-in-python/
CC-MAIN-2021-10
refinedweb
603
71.85
Barry, Thanks for the reply. BTW, I am using Python2 parts of version 2.6.1 of PyCXX. I used simple.cxx as my starting point. But all of the methods in "new_style_class" return Py::None. How do I create and return an instance of new_style_class to the python code? (In my application, I have more than one class, and a method of one class needs to return an instance of another class.) With some help from someone who knows c++ better than me, I managed to do what I needed and it seems to work. But it felt like a herculean effort. I added a second constructor to PythonClass and modified its self() to take an optional "owned" flag. I give all the code further down. Let us call my subclasses of PythonClass A and B, they each wrap a pre-existing C++ class and hold a shared pointer to instances of those wrapped classes. Let us call the pointers a and b. I am now able to return a PythonClassInstance of B from a method A as follows: const WrappedClass* x = < something that returns an instance of WrappedClass>; return (new B(x))->self(true); I must be being monumentally stupid because there is a vast gap between what I had to do and your comment "simple.cxx is all you need". I don't see how that can be the case when simple.cxx doesn't have a single method that returns anything, let alone instances of user defined classes. Regardless of whether I did more than what was necessary, my extension works beautifully. I think PyCXX is a very nice tool. The fact that I could make changes to it is an indication of how well written it is. I am grateful for your work on PyCXX. thanks, Murali My changes to PythonClass, in header file CXX/Python2/ExtensionType.hxx: template<TEMPLATE_TYPENAME T> class PythonClass : public PythonExtensionBase { protected: [...] static PythonClassInstance* alloc_empty() { PyObject *py_optlib_expr = extension_object_new(type_object(), Tuple().ptr(), Dict().ptr()); return reinterpret_cast<PythonClassInstance*>(py_optlib_expr); } PythonClass() : PythonExtensionBase() , m_class_instance( alloc_empty() ) { reinterpret_cast< Py::PythonClassInstance * >(selfPtr())->m_pycxx_object = static_cast<PythonExtensionBase*>(this); } public: static const T* obj_from_arg(Object arg) { PythonClassInstance * b = reinterpret_cast<PythonClassInstance *> (arg.ptr()); const T *val = static_cast<T *>(b->m_pycxx_object); return val; } virtual Object self(bool owned = false) // customization: Add optional argument owned. { return Object( reinterpret_cast<PyObject *>( m_class_instance ), owned ); }
http://sourceforge.net/p/cxx/mailman/attachment/138686.39989.qm@web65413.mail.ac4.yahoo.com/1/
CC-MAIN-2015-32
refinedweb
387
58.58
I want to know the codes for each button that I use for my (car mp3 remote control), I write the following programming code: #include <IRremote.h> int Recv_Pin=8; IRrecv irrecv(Recv_Pin); decode_results results; void setup() { Serial.begin (9600); irrecv.enableIRIn(); } void loop() { if (irrecv.decode(&results)){ Serial.println (results.value); } } but when I upload it to the arduino board, it keeps giving the same code for different bottons. So is my code correct, and how to solve this problem and know the right code for each button ? Replies: 403 You first need to decode output of all the remote buttons and then code them accordingly. If you don’t know the Decoded output for your IR remote, it can be easily found, just follow these steps: For more information go through this project: IR Remote Controlled Home Automation using Arduino You voted ‘up’ Replies: 8 Writing down the codes along with keeping a track of unknown codes can help in cracking the difficulties easily. You voted ‘up’
https://circuitdigest.com/forums/microcontrollers-and-programming/ir-remote-and-arduino
CC-MAIN-2021-49
refinedweb
169
61.97
Ticket #2513 (closed defect: migrated) Problems with custom render functions and missing JSONP support Description Currently, TG 2.1rc1 does not come with a templating engine for JSONP. You can add a render function this: from tg import json_encode, response from tg.render import _get_tg_vars def render_jsonp(template_name, template_vars, **kwargs): callback = template_name or kwargs.pop('callback', None) or 'callback' for key in _get_tg_vars(): del template_vars[key] response.headers['Content-Type'] = 'text/javascript' return '%s(%s)' % (template_name, json_encode(template_vars)) from myapp.config.app_cfg import base_config base_config.render_functions['jsonp'] = render_jsonp base_config.mimetype_lookup = {'.jsonp': 'text/javascript'} But this reveals two shortcomings: - In this case, we don't want any templating vars, and need to remove them using the undocumented function _get_tg_vars(). It would be better and more performant if the templating vars would not be included in the first place. But unfortunately, the templating engines which don't use templating vars are hard coded in TG (currently 'json' and 'amf') in two places in tg.decorators and tg.render. This should be made configurable. - I don't see a way of defining a default content type for the render function, so I have to set it directly on the response object which is really not nice. The render functions should not touch the request or response objects. - After fixing 1. and 2. we may think about adding a JSONP renderer to the core. Change History Note: See TracTickets for help on using tickets. Migrated to
http://trac.turbogears.org/ticket/2513
CC-MAIN-2019-26
refinedweb
242
50.63
At last week’s Greater Buffalo IT/Dev Day, I did an overview of the Windows Azure Platform (the recently rebranded Azure Services Platform). Rather than do a tired “Hello World” example, I thought it would be more interesting to talk about a more substantial application, so NerdDinner came to mind. The fact that it’s a great application to talk about ASP.NET MVC was just a plus, and although we didn’t focus on MVC, the context of the talk highlighted the fact that an ASP.NET MVC application at some level is “just another .NET web app”. The sample code I used is available on my SkyDrive, but I wanted to give a little bit of insight into how it was developed, as well as give credit where credit is due. Michael Papasevastos, a colleague at Microsoft, did most of the work! Back in June he blogged about the steps he took to port NerdDinner to Azure, and he made the source code available as well. To that starting point, I made a few modifications. Rebranding I rebranded the application to NerdBytes, in part to eliminate confusion among the various tweaks that folks have made to NerdDinner, and also since nerddinner.cloudapp.net was already claimed by Michael’s app!I rebranded the application to NerdBytes, in part to eliminate confusion among the various tweaks that folks have made to NerdDinner, and also since nerddinner.cloudapp.net was already claimed by Michael’s app! Azure Table Storage changes I noticed an issue in Michael’s choice of PartitionKey and RowKey for Azure Table Storage. The scheme he proposes doesn’t handle multiple dinners at the same date and time (the RSVPs used only the date and time of the event as the foreign key). That was easily handled via the introduction of GUIDs and minor changes to the existing code. So, in my implementation I use: Wondering why I preface the RowKey of Dinner with the text "Host:"? When you host a dinner, the business logic is to automatically include a RSVP for yourself. So, presume that Dinner’s RowKey were just the host’s user id. If that were the case, we’d now have a record in Dinner and a record in RSVP with exactly the same PartitionKey and RowKey combination. In development storage, it doesn’t immediately appear to be a big deal, because there Azure storage is ‘faked’ by using local relational database tables, and Dinner and RSVP are different tables. In Azure storage though, there is no concept of schematized data, and every item is essentially a property bag uniquely identified by PartitionKey and RowKey. Without the “Host:” preface there would be a Dinner entity and an RSVP entity with the same key, and that is verboten, resulting in an exception (both in the Development Fabric and production). Of course, this means that my design won’t support two dinners hosted by the same person at the same time, but since I haven’t yet figured out how to break the time-space continuum, it’s not an issue for me here. In this particular case, I’m not focusing on scalability per se, but here’s an interesting look at how the choices of PartitionKey and RowKey can affect your application’s ability to scale. In this case, I’m actually in lock-step with the post’s conclusions, since the GUID is the primary key. Worker Role Addition The original implementation of NerdDinner is a fairly compact Web application, but for my demo, I really wanted to introduce a worker role and use Azure’s queue storage to communicate between it and the existing Web role. To that end, I added a feature that e-mails the host of the dinner whenever a new RSVP has been recorded. To implement an e-mail agent in Azure, take a look at fellow ‘softie David Lempher’s blog article. It’s pretty much what I stoleresearched for my own implementation; I used my live.com account as the SMTP relay, and included the information as part of the serviceConfiguration.cscfgfile. In code, I rely on the RoleManager.GetConfigurationsetting to access the SMTP account information, and since it’s in the configuration file, I can modify the settings in production via the Windows Azure Platform portal without bringing down my application. As I mentioned, to communicate between the Web role and worker role, I want to use Azure queue storage. Within the ASP.NET MVC Web role code ( RSVPController.cs), I added a call to a new method (line 12 below) to send an e-mail each time an RSVP is recorded. 1: public ActionResult Register(string partitionKey)2: {3: Dinner dinner = dinnerRepository.4: GetDinner(partitionKey);5:6: if (!dinnerRepository.IsUserRegistered7: (dinner, User.Identity.Name))8: {9: RSVP rsvp = new RSVP(dinner.PartitionKey,10: User.Identity.Name);11:12: dinnerRepository.AddRSVP(rsvp);13: dinnerRepository.Save();14:15: SendRsvpEmail(dinner, rsvp);16: }17:18: return Content("Thanks - we'll see you there!");19: } “Sending the e-mail” here really means putting a new message on a queue (one that my worker role is listening to). Below is the implementation of SendRsvpEmail. The queue name I’ve selected here is ‘rsvps’, and the code for the first 10 lines or so is more or less boilerplate to get a handle to the queue and ensure it exists before posting messages to it. 1: private void SendRsvpEmail(Dinner dinner, RSVP rsvp)2: {3: Boolean queueCreated = false;4: Boolean queueExists = false;5: QueueStorage queueStorage = QueueStorage.Create6: (StorageAccountInfo.7: GetDefaultQueueStorageAccountFromConfiguration());8: MessageQueue queue = queueStorage.GetQueue("rsvps");9:10: queueCreated = queue.CreateQueue(out queueExists);11: if (queueCreated || queueExists)12: {13: String RsvpXml = new XDocument(14: new XElement("Rsvp",15: new XElement("DinnerName", dinner.Title),16: new XElement("DinnerDate", dinner.EventDate),17: new XElement("Attendee", rsvp.AttendeeName),18: new XElement("HostName", dinner.HostedBy),19: new XElement("HostEmail",20: membershipService.GetUserEmail(21: dinner.HostedBy))22: )23: ).ToString();24:25: queue.PutMessage(new Message(RsvpXml));26: RoleManager.WriteToLog("Information", RsvpXml);27: }28: } The format of the message put in the queue is XML, and I used LINQ to XML to include the name of the dinner, the date, the attendee name, host, and the email of the host in the message (lines 13-23). The message then gets put onto the queue in line 25 and logged in the next line. On the other end, my worker role is polling for new messages on the ‘rsvps’ queue, and when it finds one, begins processing it. Here’s the code extracted from the polling loop of my worker role. It’s as simple as pulling the message off the queue, reconstituting it from the XML (I declare a simple DinnerDetailsdata transfer object to hold the information), and then calling the method in the worker role that actually sends the e-mail via the SMTP client ( SendEMail).1: Message msg = queue.GetMessage();2: if (msg != null)3: {4: // message should be an XML document5: XDocument msgXml = XDocument.Parse(6: msg.ContentAsString());7: RoleManager.WriteToLog("Information",8: msgXml.ToString());9:10: // parse out dinner details from XML message11: DinnerDetails rsvp =12: (from m in msgXml.Descendants("Rsvp")13: select new DinnerDetails()14: {15: DinnerName = m.Element("DinnerName").Value,16: DinnerDate = m.Element("DinnerDate").Value,17: Attendee = m.Element("Attendee").Value,18: HostName = m.Element("HostName").Value,19: HostEmail = m.Element("HostEmail").Value20: }21: ).FirstOrDefault();22:23: // send e-mail24: SendEMail(rsvp);25:26: // delete the message from the queue27: queue.DeleteMessage(msg);28: } Here’s the crux of the SendEMailmethod; there’s a bit more error checking in the download.SmtpClient client;MailMessage message;// set up SMTP Relayclient = new SmtpClient(SMTPHost, SMTPPort);client.EnableSsl = true;client.Credentials = new NetworkCredential(SMTPAccount, SMTPPassword);// populate new messagemessage = new MailMessage(new MailAddress("rsvp@nerdbytes.net"),new MailAddress(rsvp.HostEmail));message.Subject = "NerdBytes RSVP";message.Body = rsvp.HostName + "," +Environment.NewLine + Environment.NewLine +rsvp.Attendee + " has RSVP'd for '" +rsvp.DinnerName + "' on " +DateTime.Parse(rsvp.DinnerDate).ToShortDateString() +" at " +DateTime.Parse(rsvp.DinnerDate).ToShortTimeString(); Now, in order to get the host’s email address, I modified the Dinners controller ( DinnersController.csin the ASP.NET MVC application/Web role) as well, so that the IMembershipServicewas dependency-injected along with the Dinner repository service. That necessitated a few additional code changes in the original port that Michael did.public class DinnersController : Controller {IDinnerRepository dinnerRepository;IMembershipService membershipService;//// Dependency Injection enabled constructorspublic DinnersController(): this(new DinnerRepository(),new AccountMembershipService()){}public DinnersController(IDinnerRepository repository,IMembershipService membership){dinnerRepository = repository;membershipService = membership;} And that was pretty much it. Note, if you’re following along, the NerdDinner project on CodePlex has advanced a bit since Michael worked on his port to Azure, so code may look a bit different, but the approach is the same. The other, and pretty major, thing to note is that all the work he did to set up Azure storage will largely be unnecessary once SQL Azure is available (late summer). SQL Azure is essentially SQL Server in the cloud, and would allow me to store the NerdDinner data (and the ASP.NET membership database) in the cloud in the same relational format that the original authors used. That alone would probably have cut out 2/3rds of the work (or more) for the original port to Azure. Mobilizing NerdBytes But there’s more… My other session at the Greater Buffalo IT/Dev Day was on Windows Mobile Development. While I spent most of the time there talking about and building Compact Framework applications, I wanted to touch on mobile for the web as well – including new features in “IE6 on 6”, widgets, and Silverlight. For the IE6 aspect, what better way to show the features than the cloud adaptation of NerdDinner. As you may know, Mobile IE has a Desktop and a Mobile rendering mode option. When using the Desktop mode, Mobile IE sends the same user-agent string as the desktop version of IE, so you get a display something like that on the right – functional but not optimal for the device’s form factor. To improve the user experience, we need to introduce a different user-interface for those on mobile devices, one triggered by the “Mobile” mode of IE. That’s where this post by Scott Hanselman comes in. He’d already done the work and checked it in… alas to a build that was after what Michael had ported to Azure (which was my starting point). Since I was committed to the Azure port, I cobbled together incorporated Scott’s work to my existing code base, so what you get in the download is not quite what he blogged about.. but close. By the way, I wandered on to a very helpful utility when doing the work with the mobile device. Since my application was deployed to the cloud, waiting for the deployment (which can take several minutes) to see what the site looked like wasn’t very productive. Bayden UAPick is a very cool IE add-on that allows you to modify what user-agent string is sent by the browser. So, for testing I could work with my Azure Development Fabric on my laptop and test with IE8, but use UAPick (which installs itself in IE as a menu item under Tools) to spoof the user-agent string sent by a mobile device (or other browsers for that matter) – like this: Well, that pretty much covers how I got to where I did. NerdBytes is live now, so if you want to test it out while looking over the code, feel free. Or load it up yourself in your own little spot in the cloud – Windows Azure is still in CTP, and more importantly FREE!, until PDC in November. Also, drop me a line if you’re running into trouble, I undoubtedly left out some critical detail in my overview here!
https://blogs.msdn.microsoft.com/jimoneil/2009/07/27/nerddinner-on-azure-take-2/
CC-MAIN-2017-22
refinedweb
1,982
54.42
Linux raspberrypi 4.9.59-v7+ #1047 SMP Sun Oct 29 12:19:23 GMT 2017 armv7l GNU/Linux Deluged: 1.3.13 Libtorrent: 1.1.1.0 Note: when I try to look up the version of deluged, I get the following return Code: Select all deluged --version deluged: 1.3.13 /usr/lib/python2.7/dist-packages/deluge/_libtorrent.py:59: RuntimeWarning: to-Python converter for boost::shared_ptr<libtorrent::alert> already registered; second conversion method ignored. import libtorrent as lt libtorrent: 1.1.1.0 When I run Deluged I get the following return Code: Select all pi@raspberrypi:~ $ deluged deluge-web pi@raspberrypi:~ $ [ERROR ] 17:28:30 main:243 There is a deluge daemon running with this config directory! [ERROR ] 17:28:30 main:244 You cannot run multiple daemons with the same config directory set. [ERROR ] 17:28:30 main:245 If you believe this is an error, you can force a start by deleting /home/pi/.config/deluge/deluged.pid. Any help would be greatly appreciated
http://forum.deluge-torrent.org/viewtopic.php?f=7&t=54781&sid=46a1f1fb3f039e8f0477fd13a4a002d5
CC-MAIN-2018-09
refinedweb
171
50.33
This Tutorial Explains What is Stack in Java, Java Stack Class, Stack API Methods, Stack Implementation using Array & Linked List with the help of Examples: A stack is an ordered data structure belonging to the Java Collection Framework. In this collection, the elements are added and removed from one end only. The end at which the elements are added and removed is called “Top of the Stack”. As addition and deletion are done only at one end, the first element added to the stack happens to be the last element removed from the stack. Thus stack is called a LIFO (Last-in, First-out) data structure. => Take A Look At The Java Beginners Guide Here What You Will Learn: - Java Stack Collection - Stack Class In Java - Create A Stack In Java - Stack API Methods In Java - Stack Size - Print / Iterate Stack Elements - Stack Using Java 8 - Stack Implementation In Java - Frequently Asked Questions - Conclusion Java Stack Collection A pictorial representation of the stack is given below. As shown in the above sequence of representation, initially the stack is empty and the top of the stack is set to -1. Then we initiate a “push” operation that is used to add an element to the stack. So in the second representation, we push element 10. At this point, the top is incremented. We again push element 20 in the stack thereby incrementing the top furthermore. In the last representation, we initiate a “pop” operation. This operation is used to remove an element from the stack. An element currently pointed to ‘Top’ is removed by the pop operation. A stack data structure supports the following operations: - Push: Adds an element to the stack. As a result, the value of the top is incremented. - Pop: An element is removed from the stack. After the pop operation, the value of the top is decremented. - Peek: This operation is used to look up or search for an element. The value of the top is not modified. The top of the stack that is used as an end to add/remove elements from the stack can also have various values at a particular instant. If the size of the stack is N, then the top of the stack will have the following values at different conditions depending on what state the stack is in. Stack Class In Java Java Collection Framework provides a class named “Stack”. This Stack class extends the Vector class and implements the functionality of the Stack data structure. The below diagram shows the hierarchy of the Stack class. As shown in the above diagram, the Stack class inherits the Vector class which in turn implements the List Interface of Collection interface. The Stack class is a part of java.util package. To include Stack class in the program, we can use the import statement as follows. import java.util.*; or import java.util.Stack; Create A Stack In Java Once we import the Stack class, we can create a Stack object as shown below: Stack mystack = new Stack(); We can also create a generic type of Stack class object as follows: Stack<data_type> myStack = new Stack<data_type>; Here data_type can be any valid data type in Java. For example, we can create the following Stack class objects. Stack<Integer> stack_obj = new Stack<>(); Stack<String> str_stack = new Stack<>(); Stack API Methods In Java The Stack class provides methods to add, remove, and search data in the Stack. It also provides a method to check if the stack is empty. We will discuss these methods in the below section. Stack Push Operation The push operation is used to push or add elements into the stack. Once we create a stack instance, we can use the push operation to add the elements of the stack object type to the stack. The following piece of code is used to initialize an integer stack with the values. Stack<Integer> myStack = new Stack<>(); myStack.push(10); myStack.push(15); myStack.push(20); The initial stack obtained as a result of the above piece of code execution is shown below: If we perform another push() operation as shown below, push(25); The resultant stack will be: Stack Pop Operation We can remove the element from the stack using the “pop” operation. The element pointed by the Top at present is popped off the stack. The following piece of code achieves this. Stack<Integer> intStack = new Stack<>(); intStack.push(100); intStack.push(200); int val = intStack.pop(); The variable val will contain the value 200 as it was the last element pushed into the stack. The stack representation for push and pop operation is as follows: Stack Peek Operation The peek operation returns the Top of the stack without removing the element. In the above stack example, “intStack.peek ()” will return 200. Stack isEmpty Operation The isEmpty () operation of the Stack class checks if the stack object is empty. It returns true if the Stack has no elements in it else returns false. Stack Search Operation We can search for an element on the stack using the search () operation. The search () operation returns the index of the element being searched for. This index is counted from the top of the stack. Stack<Integer> intStack = new Stack<> (); intStack.push (100); intStack.push (200); int index = inStack.search(100); //index will have the value 2. Stack Size The size of the Stack object is given by the java.util.Stack.size () method. It returns the total number of elements in the stack. The following example prints the stack size. Stack<Integer> myStack = new Stack<Integer>(); myStack.push(100); myStack.push(200); myStack.push(300); System.out.println("Stack size:" + myStack.size()); //Stack size: 3 Print / Iterate Stack Elements We can declare an iterator for the Stack and then traverse through the entire Stack using this iterator. This way we can visit and print each stack element one by one. The following program shows the way to iterate Stack using an iterator. import java.util.*; public class Main { public static void main(String[] args) { //declare and initialize a stack object Stack<String> stack = new Stack<String>(); stack.push("PUNE"); stack.push("MUMBAI"); stack.push("NASHIK"); System.out.println("Stack elements:"); //get an iterator for the stack Iterator iterator = stack.iterator(); //traverse the stack using iterator in a loop and print each element while(iterator.hasNext()){ System.out.print(iterator.next() + " "); } } } Output: Stack elements: PUNE MUMBAI NASHIK Stack Using Java 8 We can also print or traverse the stack elements using Java 8 features like Stream APIs, forEach, and forEachRemaining constructs. The following program demonstrates the usage of Java 8 constructs to traverse through the stack. import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { //declare and initialize a stack object Stack<String> stack = new Stack<String>(); stack.push("PUNE"); stack.push("MUMBAI"); stack.push("NASHIK"); System.out.println("Stack elements using Java 8 forEach:"); //get a stream for the stack Stream stream = stack.stream(); //traverse though each stream object using forEach construct of Java 8 stream.forEach((element) -> { System.out.print(element + " "); // print element }); System.out.println("\nStack elements using Java 8 forEachRemaining:"); //define an iterator for the stack Iterator<String> stackIterator = stack.iterator(); //use forEachRemaining construct to print each stack element stackIterator.forEachRemaining(val -> { System.out.print(val + " "); }); } } Output: Stack elements using Java 8 forEach: PUNE MUMBAI NASHIK Stack elements using Java 8 forEachRemaining: PUNE MUMBAI NASHIK Stack Implementation In Java The following program implements the detailed stack demonstrating the various stack operations. import java.util.Stack; public class Main { public static void main(String a[]){ //declare a stack object Stack<Integer> stack = new Stack<>(); //print initial stack System.out.println("Initial stack : " + stack); //isEmpty () System.out.println("Is stack Empty? : " + stack.isEmpty()); //push () operation stack.push(10); stack.push(20); stack.push(30); stack.push(40); //print non-empty stack System.out.println("Stack after push operation: " + stack); //pop () operation System.out.println("Element popped out:" + stack.pop()); System.out.println("Stack after Pop Operation : " + stack); //search () operation System.out.println("Element 10 found at position: " + stack.search(10)); System.out.println("Is Stack empty? : " + stack.isEmpty()); } } Output: Initial stack : [] Is stack Empty? : true Stack after push operation: [10, 20, 30, 40] Element popped out:40 Stack after Pop Operation : [10, 20, 30] Element 10 found at position: 3 Is Stack empty? : false Stack To Array In Java The stack data structure can be converted to an Array using ‘toArray()’ method of the Stack class. The following program demonstrates this conversion. import java.util.*; import java.util.stream.*; public class Main { public static void main(String[] args) { //declare and initialize a stack object Stack<String> stack = new Stack<String>(); stack.push("PUNE"); stack.push("MUMBAI"); stack.push("NASHIK"); //print the stack System.out.println("The Stack contents: " + stack); // Create the array and use toArray() method to convert stack to array Object[] strArray = stack.toArray(); //print the array System.out.println("The Array contents:"); for (int j = 0; j < strArray.length; j++) System.out.print(strArray[j]+ " "); } } Output: The Stack contents: [PUNE, MUMBAI, NASHIK] The Array contents: PUNE MUMBAI NASHIK Stack Implementation In Java Using Array The stack can be implemented using an Array. All the stack operations are carried out using an array. The below program demonstrates the Stack implementation using an array. import java.util.*; //Stack class class Stack { int top; //define top of stack int maxsize = 5; //max size of the stack int[] stack_arry = new int[maxsize]; //define array that will hold stack elements Stack(){ //stack constructor; initially top = -1 top = -1; } boolean isEmpty(){ //isEmpty () method return (top < 0); } boolean push (int val){ //push () method if(top == maxsize-1) { System.out.println("Stack Overflow !!"); return false; } else { top++; stack_arry[top]=val; return true; } } boolean pop () { //pop () method if (top == -1) { System.out.println("Stack Underflow !!"); return false; } else { System.out.println("\nItem popped: " + stack_arry[top--]); return true; } } void display () { //print the stack elements System.out.println("Printing stack elements ....."); for(int i = top; i>=0;i--) { System.out.print(stack_arry[i] + " "); } } } public class Main { public static void main(String[] args) { //define a stack object Stack stck = new Stack(); System.out.println("Initial Stack Empty : " + stck.isEmpty()); //push elements stck.push(10); stck.push(20); stck.push(30); stck.push(40); System.out.println("After Push Operation..."); //print the elements stck.display(); //pop two elements from stack stck.pop(); stck.pop(); System.out.println("After Pop Operation..."); //print the stack again stck.display(); } } Output: Initial Stack Empty : true After Push Operation… Printing stack elements ….. 40 30 20 10 Item popped: 40 Item popped: 30 After Pop Operation… Printing stack elements ….. 20 10 Stack Implementation Using Linked List The stack can also be implemented using a linked list just like how we have done using arrays. One advantage of using a linked list for implementing stack is that it can grow or shrink dynamically. We need not have a maximum size restriction like in arrays. The following program implements a linked list to perform stack operations. import static java.lang.System.exit; // Stack class using LinkedList class Stack_Linkedlist { // Define Node of LinkedList private class Node { int data; // node data Node nlink; // Node link } // top of the stack Node top; // stack class Constructor Stack_Linkedlist() { this.top = null; } // push () operation public void push(int val) { // create a new node Node temp = new Node(); // checks if the stack is full if (temp == null) { System.out.print("\nStack Overflow"); return; } // assign val to node temp.data = val; // set top of the stack to node link temp.nlink = top; // update top top = temp; } // isEmpty () operation public boolean isEmpty() { return top == null; } // peek () operation public int peek() { // check if the stack is empty if (!isEmpty()) { return top.data; } else { System.out.println("Stack is empty!"); return -1; } } // pop () operation public void pop() { // check if stack is out of elements if (top == null) { System.out.print("\nStack Underflow!!"); return; } // set top to point to next node top = (top).nlink; } //print stack contents public void display() { // check for stack underflow if (top == null) { System.out.printf("\nStack Underflow!!"); exit(1); } else { Node temp = top; System.out.println("Stack elements:"); while (temp != null) { // print node data System.out.print(temp.data + "->"); // assign temp link to temp temp = temp.nlink; } } } } public class Main { public static void main(String[] args) { // Create a stack class object Stack_Linkedlist stack_obj = new Stack_Linkedlist(); // push values into the stack stack_obj.push(9); stack_obj.push(7); stack_obj.push(5); stack_obj.push(3); stack_obj.push(1); // print Stack elements stack_obj.display(); // print current stack top System.out.println("\nStack top : " + stack_obj.peek()); // Pop elements twice System.out.println("Pop two elements"); stack_obj.pop(); stack_obj.pop(); // print Stack elements stack_obj.display(); // print new stack top System.out.println("\nNew Stack top:" + stack_obj.peek()); } } Output: Stack elements: 1->3->5->7->9-> Stack top : 1 Pop two elements Stack elements: 5->7->9-> New Stack top:5 Frequently Asked Questions Q #1) What are Stacks in Java? Answer: A stack is a LIFO (Last in, First out) data structure for storing elements. The stack elements are added or removed from the stack from one end called Top of the stack. The addition of an element to the stack is done using the Push operation. The deletion of elements is done using pop operation. In Java, a stack is implemented using the Stack class. Q #2) Is Stack a Collection in Java? Answer: Yes. The stack is a legacy collection in Java that is available from Collection API in Java 1.0 onwards. Stack inherits the Vector class of the List interface. Q #3) Is Stack an Interface? Answer: Interface<E> stack is an interface that describes the last-in, first-out structure and is used for storing the state of recursive problems. Q #4) What are Stacks used for? Answer: Following are the main applications of the stack: - Expression evaluation and conversions: Stack is used for converting expressions into postfix, infix, and prefix. It is also used to evaluate these expressions. - The stack is also used for parsing syntax trees. - The stack is used to check parentheses in an expression. - The stack is used for solving backtracking problems. - Function calls are evaluated using stacks. Q #5) What are the Advantages of the Stack? Answer: Variables stored on stack are destroyed automatically when returned. Stacks are a better choice when memory is allocated and deallocated. Stacks also clean up the memory. Apart from that stacks can be used effectively to evaluate expressions and parse the expressions. Conclusion This completes our tutorial on Stacks in Java. Stack class is a part of the collection API and supports push, pop, peek, and search operations. The elements are added or removed to/from the stack at one end only. This end is called the top of the stack. In this tutorial, we have seen all the methods supported by the stack class. We have also implemented the stack using arrays and linked lists. We will proceed with other collection classes in our subsequent tutorials. => Read Through The Easy Java Training Series
https://www.softwaretestinghelp.com/java-stack-tutorial/
CC-MAIN-2021-17
refinedweb
2,513
58.48
Transparent Distributed Processing (TDP) allows you to leverage the processing power of your entire network by sharing resources and services transparently over the network. TDP uses Neutrino native network protocol Qnet to link the devices in your network. This chapter contains the following topics: Qnet is Neutrino's protocol for distributed networking. Using Qnet, you can build a transparent distributed-processing platform that is fast and scalable. This is accomplished by extending the Neutrino message passing architecture over a network. This creates a group of tightly integrated Neutrino nodes (systems) or CPUs — a Neutrino native network. A program running on a Neutrino node in this Qnet network can transparently access any resource, whether it's a file, device, or another process. These resources reside on any other node (a computer, a workstation or a CPU in a system) in the Qnet network. The Qnet protocol builds an optimized network that provides a fast and seamless interface between Neutrino nodes.. For more information about message passing and Qnet, see Advanced Qnet Topics appendix. The Qnet protocol is deployed as a network of trusted machines. It lets these machines share all their resources efficiently with minimum overhead. This is accomplished by allowing a client process to send a message to a remote manager in the same way that it sends a message to a local one. See the “How does it work?” section of this chapter. For example, using Qnet, you can use the Neutrino utilities (cp, mv and so on) to manipulate files anywhere on the Qnet Network as if they were on your machine — by communicating with the filesystem manager on the remote nodes. In addition, the Qnet protocol doesn't do any authentication of remote requests. Files are protected by the normal permissions that apply to users and groups (see “File ownership and permissions” in Working with Files in the User's Guide). Qnet, through its distributed processing platform, lets you do the following tasks efficiently: Since Qnet extends Neutrino message passing over the network, other forms of interprocess communication (e.g. signals, message queues, and named semaphores) also work over the network. Any application that inherently needs more than one computer, due to its processing or physical layout requirements, could likely benefit from Qnet. For example, you can apply Qnet networking successfully in many industrial-automation applications (e.g. a fabrication plant, with computers scattered around). From an application standpoint, Qnet provides an efficient form of distributed computing where all computers look like one big computer because Qnet extends the fundamental Neutrino message passing across all the computers. Another useful application is in the telecom space, where you need to implement large routers that have several processors. From an architectural standpoint, these routers generally have some interface cards and a central processor that runs a set of server processes. Each interface card, in turn, has a processor that runs another set of interface (e.g. client) processes. These client processes communicate via Qnet using Neutrino message passing with the server processes on the central processor, as if they were all running on the same processor. The scalability of Qnet allows more and more interface cards to be plugged into the router, without any code changes required to the application. As explained in the System Architecture guide, Neutrino client and server applications communicate by Neutrino message passing. Function calls that need to communicate with a manager application, such as the POSIX functions open(), write(), read(), ioctl(), or other functions such as devctl() are all built on Neutrino message passing. Qnet allows these messages to be sent over a network. If these messages are being sent over a network, how is a message sent to a remote manager vs a local manager? When you access local devices or manager processes (such as a serial device, TCP/IP socket, or mqueue), you access these devices by opening a pathname under /dev. This may be apparent in the application source code: /*Open a serial device*/ fd = open("/dev/ser1",O_RDWR....); or it may not. For example, when you open a socket: /*Create a UDP socket*/ sock = socket(AF_INET, SOCK_DGRAM, 0); The socket() function opens a pathname under /dev called /dev/socket/2 (in the case of AF_INET, which is address family two). The socket() function call uses this pathname to establish a connection with the socket manager (io-pkt*), just as the open() call above established a connection to the serial device manager (devc-ser8250). The magic of this is that you access all managers by the name that they added to the pathname space. For more information, see the Writing a Resource Manager guide. When you enable the Qnet native network protocol, the pathname spaces of all the nodes in your Qnet network are added to yours. The pathname space of remote nodes appears (by default) under the prefix /net. The /net directory is created by the Qnet protocol manager (lsm-qnet.so). If, for example, the other node is called node1, its pathname space appears as follows: /net/node1/dev/socket /net/node1/dev/ser1 /net/node1/home /net/node1/bin .... So with Qnet, you can now open pathnames (files or managers) on other remote Qnet nodes, in the same way that you open files locally. This means that you can access regular files or manager processes on other Qnet nodes as if they were executing on your local node. First, let's see some basic examples of Qnet use: less /net/node1/etc/TIMEZONE $ pidin net pidin -n node1 | less on -f node date In all of these uses, the application source or the libraries (for example libc) they depend on, simply open the pathnames under /net. For example, if you wish to make use of a serial device on another node node1, perform an open() function with the pathname /net/node1/dev/ser1 i.e. fd = open("/net/node1/dev/ser1",O_RDWR...); As you can see, the code required for accessing remote resources and local resources is identical. The only change is the pathname used. In the TCP/IP socket() case, it's the same, but implemented differently. In the socket case, you don't directly open a filename. This is done inside the socket library. In this case, an environment variable is provided to set the pathname for the socket call (the SOCK environment variable — see io-pkt*). Some other applications are: This brings up an important issue for the client application or libraries that a client application uses. If you think that your application will be distributed over a network, you will want to include the capability to specify another pathname for connecting to your services. This way, your application will have the flexibility of being able to connect to local or remote services via a user-configuration adjustment. This could be as simple as the ability to pass a node name. In your code, you would add the prefix /net/node_name to any pathname that may be opened on the remote node. In the local case, or default case if appropriate, you could omit this prefix when accessing local managers. In this example, you're using standard resource managers, such as would be developed using the resource manager framework (see the Writing a Resource Manager guide). For further information, or for a more in-depth view of Qnet, see Advanced Qnet Topics appendix. There is another design issue to contend with at this point: the above design is a static one. If you have services at known locations, or the user will be placing services at known locations, then this may be sufficient. It would be convenient, though, if your client application could locate these services automatically, without the need to know what nodes exist in the Qnet network, or what pathname they've added to the namespace. You can now use the Global Name Service (gns) manager to locate services with an arbitrary name representing that service. For example, you can locate a service with a name such as printer instead of opening a pathname of /net/node/dev/par1 for a parallel port device. The printer name locates the parallel port manager process, whether it's running locally or remotely. You use gns, the Global Name Service or GNS manager to locate services. GNS is a standalone resource manager. With the help of this utility, an application can advertise, look up, and use (connect to) a service across Qnet network, without knowing the details of where the service is, or who the provider is. The gns utility runs in two different modes: server- and client-mode. A server-mode manager is a central database that stores advertised services, and handles lookup and connect requests. A client-mode manager relays advertisement, lookup, and connect requests between local application and the GNS server(s). For more information on starting and configuring GNS, see the gns utility in the Utilities Reference. Here's a simple layout for a GNS client and a GNS server distributed over a network: A simple GNS setup. In this example, there's one gns client and one gns server. As far as an application is concerned, the GNS service is one entity. The client-server relationship is only between gns processes (we'll examine this later). The server GNS process keeps track of the globally registered services, while the client GNS process on the other node relays gns requests for that node to the gns server. When a client and server application interacts with the GNS service, they use the following APIs: In order to use GNS, you need to first register the manager process with GNS, by calling name_attach(). When you register a service, you need to decide whether to register this manager's service locally or globally. If you register your service locally, only the local node is able to see this service; another node is not able to see it. This allows you to have client applications that look for service names rather than pathnames on the node it is executing on. This document highlights registering services globally. When you register GNS service globally, any node on the network running a client application can use this service, provided the node is running a gns client process and is connected to the gns server, along with client applications on the nodes running the gns server process. You can use a typical name_attach() call as follows: if ((attach = name_attach(NULL, "printer", NAME_FLAG_ATTACH_GLOBAL)) == NULL) { return EXIT_FAILURE; } First thing you do is to pass the flag NAME_FLAG_ATTACH_GLOBAL. This causes your service to be registered globally instead locally. The last thing to note is the name. This is the name that clients search for. This name can have a single level, as above, or it can be nested, such as printer/ps. The call looks like this: if ((attach = name_attach(NULL, "printer/ps", NAME_FLAG_ATTACH_GLOBAL)) == NULL) { return EXIT_FAILURE; } Nested names have no impact on how the service works. The only difference is how the services are organized in the filesystem generated by gns. For example: $ ls -l /dev/name/global/ total 2 dr-xr-xr-x 0 root techies 1 Feb 06 16:20 net dr-xr-xr-x 0 root techies 1 Feb 06 16:21 printer $ ls -l /dev/name/global/printer total 1 dr-xr-xr-x 0 root techies 1 Feb 06 16:21 ps The first argument to the name_attach() function is the dispatch handle. You pass a dispatch handle to name_attach() once you've already created a dispatch structure. If this argument is NULL, a dispatch structure is created automatically. What happens if more than one instance of the server application (or two or more applications that register the same service name) are started and registered with GNS? This is treated as a redundant service. If one application terminates or detaches its service, the other service takes over. However, it's not a round-robin configuration; all requests go to one application until it's no longer available. At that point, the requests resolve to another application that had registered the same service. There is no guaranteed ordering. There's no credential restriction for applications that are attached as local services. An application can attach a service globally only if the application has root privilege. When your application is to terminate, or you wish not to provide access to the service via GNS, you should call name_detach(). This removes the service from GNS. For more information, see name_attach() and name_detach(). Your client should call name_open() to locate the service. If you wish to locate a global service, you need to pass the flag NAME_FLAG_ATTACH_GLOBAL: if ((fd = name_open("printer", NAME_FLAG_ATTACH_GLOBAL)) == -1) { return EXIT_FAILURE; } or: if ((fd = name_open("printer/ps", NAME_FLAG_ATTACH_GLOBAL)) == -1) { return EXIT_FAILURE; } If you don't specify this flag, GNS looks only for a local service. The function returns an fd that you can then use to access the service manager by sending messages, just as if you it had opened the service directly as /dev/par1, or /net/node/dev/par1. A service is represented by a path namespace (without a leading “/”) and is registered under /dev/name/global or /dev/name/local, depending on how it attaches itself. Every machine running a gns client or server on the same network has the same view of the /dev/name/global namespace. Each machine has its own local namespace /dev/name/local that reflects its own local services. Here's an example after a service called printer has attached itself globally: $ ls -l /dev/name/global/ total 2 dr-xr-xr-x 0 root techies 1 Feb 06 16:20 net dr-xr-xr-x 0 root techies 1 Feb 06 16:21 printer When you deploy the gns processes on your network, you start the gns process in two modes: server and client. You need at least one gns process running as a server on one node, and you can have one or more gns clients running on the remaining nodes. The role of the gns server process is to maintain the database that stores the advertised services. The role of a client gns process is to relay requests from its node to the gns server process on the other node. A gns process must be running on each node that wishes to access GNS. It's possible to start multiple global name service managers (gns process) in server mode on different nodes. You can deploy server-mode gns processes in two ways: as redundant servers, or as servers that handle two or more different global domains. In the first scenario, you have two or more servers with identical database information. The gns client processes are started with contact information for both servers. Operations are then sent to all gns server processes. The gns servers, however, don't communicate with each other. This means that if an application on one gns server node wants to register a global service, another gns server can't do it. This doesn't affect other applications on the network, because when they connect to that service, both GNS servers are contacted. A redundant GNS setup. You don't have to start all redundant gns servers at the same time. You can start one gns server process first, and then start a second gns server process at a later time. In this case, use the special option -s backup_server on the second gns server process to make it download the current service database from another node that's already running the gns server process. When you do this, the clients connected to the first node (that's already running the gns server process) are notified of the existence of the other server. In the second scenario, you maintain more than one global domain. For example, assume you have two nodes, each running a gns server process. You also have a client node that's running a gns client process and is connecting to one of the servers. A different client node connects to the other server. Each server node has unique services registered by each client. A client connected to server node1 can't see the service registered on the server node2. Separate global domains. What is demonstrated in each scenario is that it's the client that determines whether a server is acting as a redundant server or not. If a client is configured to connect to two or more servers, then those servers are redundant servers for that client's services. The client can see the services that exist on those servers, and it registers its services with those servers. There's no limit to the number of server mode gns processes that can be run on the network. Increasing the number of servers, however, in a redundant environment can increase network use and make gns function calls such as name_attach() more expensive as clients send requests to each server that exists in its configuration. It's recommended that you run only as many gns servers in a redundant configuration as your system design requires and no more than that. For more information, see gns documentation in the Utilities Reference. Quality of Service (QoS) is an issue that often arises in high-availability networks as well as realtime control systems. In the Qnet context, QoS really boils down to transmission media selection — in a system with two or more network interfaces, Qnet chooses which one to use, according to the policy you specify. Qnet supports transmission over multiple networks and provides the following policies for specifying how Qnet should select a network interface for transmission: switches to the next available link. By default,.) The time required to switch to another link can be set to whatever is appropriate for your application using command-line options of Qnet. See lsm-qnet.so documentation. Using these options, you can create a redundant behavior by minimizing the latency that occurs when switching to another interface in case one of the interfaces fail. While load-balancing among the live links, Qnet sends periodic maintenance packets on the failed link in order to detect recovery. When the link recovers, Qnet places it back into the pool of available links. With this policy, you specify a preferred link to use for transmissions. Qnet uses only that one link until it fails. If your preferred link fails, Qnet then turns to the other available links and resumes transmission, using the loadbalance policy. Once your preferred link is available again, Qnet again uses if the fast one fails. You specify the QoS policy as part of the pathname. For example, to access /net/node1/dev/ser1 with a QoS of exclusive, you could use the following pathname: /net/node/note1~preferred:en1 /remote/sql_server This assigns an “abstracted” name of /remote/sql_server to the node node node1 fails, then a monitoring program could detect this and effectively issue: rm /remote/sql_server ln -sP /net/magenta /remote/sql_server This removes node1 and reassigns the service to node2. The real advantage here is that applications can be coded based on the abstract “service name” rather than be bound to a specific node name. For a real world example of choosing appropriate QoS policy in an application, see the following section on designing a system using Qnet. In order to explain the design of a system that takes advantage of the power of Qnet by performing distributed processing, consider a multiprocessor hardware configuration that is suitable for a typical telecom box. This configuration has a generic controller card and several data cards to start with. These cards are interconnected by a high-speed transport (HST) bus. The controller card configures the box by communicating with the data cards, and establishes/enables data transport in and out of the box (i.e. data cards) by routing packets. The typical challenges to consider for this type of box include: You need several pieces of software components (along with the hardware) to build your distributed system. Before going into further details, you may review the following sections from Using Qnet for Transparent Distributed Processing chapter in the Neutrino User's Guide: Power Configure. Qnet provides design choices to improve the reliability of a high-speed transport bus, most often a single-point of failure in such type of telecom box. You can choose between different transport selections to achieve a different Quality of Service (or QoS), such as: These selections allow you to control how data will flow via different transports. In order to do that, first, find out what interfaces are available. Use the following command at the prompt of any card: ls /dev/io-net You see the following: hs0 hs1 These are the interfaces available: HST 0 and HST 1. Select your choice of transport as follows: You can have another economical variation of the above hardware configuration: This configuration has asymmetric transport: a High-Speed Transport (HST) and a reliable and economical Low-Speed Transport (LST). You might use the HST for user data, and the LST exclusively for out-of-band control (which can be very helpful for diagnosis and during booting). For example, if you use generic Ethernet as the LST, you could use a bootp ROM on the data cards to economically boot — no flash would be required on the data cards. With asymmetric transport, use of the QoS policy as described above likely becomes even more useful. You might want some applications to use the HST link first, but use the LST if the HST fails. You might want applications that transfer large amounts of data to exclusively use the HST, to avoid swamping the LST. The reliability of such a telecom box also hinges on the controller card, that's a critical component and certainly a potential SPOF (single point of failure). You can increase the reliability of this telecom box by using additional controller cards. The additional controller card is for redundancy. Add another controller card as shown below: Once the (second) controller card is installed, the challenge is in the determination of the primary controller card. This is done by the software running on the controller cards. By default, applications on the data cards access the primary controller card. Assuming cc0 is the primary controller card, Use the following command to access this card in /cc directory: ln -s /net/cc0 /cc The above indirection makes communication between data card and controller card transparent. In fact, the data cards remain unaware of the number of controller cards, or which card is the primary controller card. Applications on the data cards access the primary controller card. In the event of failure of the primary controller card, the secondary controller card takes over. The applications on the data cards redirect their communications via Qnet to the secondary controller card.. When you're creating a network of resolve the remote Qnet node's name only via the file used by the Qnet file resolver. In your network design, when should you use Qnet, TCP/IP, or NFS? The decision depends on what your intended application is and what machines you need to connect. The advantage of using Qnet is that it lets you build a truly distributed processing system with incredible scalability. For many applications, it could be a benefit to be able to share resources among your application systems (nodes). Qnet implements a native network protocol to build this distributed processing system. The basic purpose of Qnet is to extend Neutrino message passing to work over a network link. It lets these machines share all their resources with little overhead. A Qnet network is a trusted environment where resources are tightly integrated, and remote manager processes can be accessed transparently. For example, with remote requests. Also, the application really doesn't know whether it's accessing a resource on a remote system; and most importantly, the application doesn't need any special code to handle this capability. If you're developing a system that requires remote procedure calling (RPC), or remote file access, Qnet provides this capability transparently. In fact, you use a form of remote procedure call (a Neutrino message pass) every time you access a manager on your Neutrino system. Since Qnet creates an environment where there's no difference between accessing a manager locally or remotely, remote procedure calling (capability) is builtin. You don't need to write source code to distribute your services. Also, since you are sharing the filesystem between systems, there's no need for NFS to access files on other Neutrino hosts (of the same endian), because you can access remote filesystem managers the same way you access your local one. Files are protected by the normal permissions that apply to users and groups (see “File ownership and permissions” in the Working with Files chapter in the User's Guide). There are several ways to control access to a Qnet node, if required: You can also configure Qnet to be used on a local LAN, or routed over to a WAN if necessary (encapsulated in the IP protocol). Depending on your system design, you may need to include TCP/IP protocols along with Qnet, or instead of Qnet. For example, you could use a TCP/IP-based protocol to connect your Qnet cluster to a host that's running another operating system, such as a monitoring station that controls your system, or another host providing remote access to your system. You'll probably want to deploy standard protocols (e.g., SNMP, HTTP, or a telnet console) for this purpose. If all the hosts in your system are running different operating systems, then your likely choice to connect them would be TCP/IP. The TCP/IP protocols typically do authentication to control access; it's useful for connecting machines that you don't necessarily trust. Another issue may be the required behavior. For example, NFS has been designed for filesystem operations between all hosts and all endians. It's widely supported and a connectionless protocol. In NFS, the server can be shut down and restarted, and the client resumes automatically. NFS also uses authentication and controls directory access. However, NFS retries forever to reach a remote host if it doesn't respond, whereas Qnet can return an error if connectivity is lost to a remote host. For more information, see “NFS filesystem” in Working with Filesystems in the User's Guide). If you require broadcast or multicast services, you need to look at TCP/IP functionalities, because Qnet is based on Neutrino message passing, and has no concept of broadcasting or multicasting. You don't need a specific driver for your hardware, for example, for implementing a local area network using Ethernet hardware or for implementing TCP/IP networking that require IP encapsulation. In these cases, the underlying io-pkt* and TCP/IP layer is sufficient to interface with the Qnet layer for transmitting and receiving packets. You use standard the details of the Ethernet hardware or driver. So, if you simply want new Ethernet hardware supported, you don't need to write a Qnet-specific driver. What you need is just a normal Ethernet driver that knows how to interface to io-pkt*. There is a bit of code at the very bottom of Qnet that's specific to io-pkt* and has knowledge of exactly how io-pkt* likes to transmit and receive packets. This is the L4 driver API abstraction layer. Let's take a look at the arrangement of layers that exist in the node when Qnet is run with the optional binding of IP encapsulation (e.g. bind=ip): As far as Qnet is concerned, the TCP/IP stack is now its driver. This stack is responsible for transmitting and receiving packets.
http://www.qnx.com/developers/docs/6.5.0_sp1/topic/com.qnx.doc.neutrino_prog/qnet.html
CC-MAIN-2019-51
refinedweb
4,628
51.99
- Script that Navigates Page needs Javascript Functionality - RE:xlrd question - How to pass a reference to the current module - Sorting Unix mailboxes - regexp problem in Python - amra and py2exe - ANNOUNCE: Spiff Workflow 0.0.1 (Initial Release) - libpq.dll for pgdb - os.listdir path error - Announcing Wing IDE 101 for teaching intro programming courses - draggable Tkinter.Text widget - downloading files - Re: Using cursor.callproc with zxJDBC - Global package variable, is it possible? - Eclipse and Python - Coroutine API - Trying to find zip codes/rest example - xlrd question - How to log python Shell results - Eclipse/PyDev question. - Replacing _xmlplus.dom.minidom with xml.dom.minidom - wxpython TreeCtrl with os.listdir - How to create python script which can create csv we file with relationship - How to read information from tables in HTML? - suppress pop up windwo - Help: GIS - ANN: SonomaSunshine for Django v0.01 - Job Fair F/OSS project - PYTHON PROGRAMMING HELP PLSSS !!URGENT - PYTHON PROGRAMMING HELP PLSSS !! - Efficient Rank Ordering of Nested Lists - Tkinter or wxpython? - (no) fast boolean evaluation ? - Bug in time, part 2 - Best way to capture output from an exec'ed (or such) script? - Berkely Db. How to iterate over large number of keys "quickly" - XML Processing - Bug in execfile? - problems playing with dates from any month. - File access - Error subclassing datetime.date and pickling - python 3.0, pywin32 and scipy - Cross compiling 2.5.1 - Memory Leak with Tkinter Canvas (Python 2.5 Win32) - __call__ considered harmful or indispensable? - Determining if file is valid image file - Case study: library class inheritance with property declarations - IWCIA 08 - USA, 7-9 April 2008: Invitation - Catching SystemExit in C API code when embedding Python? - Use variable in regular expression - i am new to python-Please somebody help - backup/restore postgresql database - No module named DBUtils.PooledDB - a dict trick - calling superclass __init__ when superclass is object - DBUtil with modepython - Re: sending very large packets over the network - frequency analysis of a DB column - Re: Wing IDE for Python v. 3.0 beta1 released - Re: sending very large packets over the network - Is shelve/dbm supposed to be this inefficient? - Representation of new-style instance - Re: Wing IDE for Python v. 3.0 beta1 released - Bug in Time module, or in my understanding? - Filemaker interactions - Buffering HTML as HTMLParser reads it? - Python IMAP web-access - Awkward format string - Assertion in list comprehension - force unicode strings - Extending doctest - Emacs + python - Equivalent to gzinflate() function in PHP. - wxPython version question - Plain old SAX and minidom useable? But how then? - MIMEText breaking the rules? - Floats as keys in dict - calling a .net application from Python 2.5 - access the name of my method inside it - Problem with subprocess.Popen() - Strange problems with subprocess - How does xmlrpc work ? - Scipy and Mcafee Site Advisor? - Python end of file marker similar to perl's __END__ - Any way to monitor windows network connection? - http client module - (May be OT) developing in jython, using in java? - Reload after an exception, not possible ? - Python Package Index hostname change - Live editing... - split a string of space separated substrings - elegant solution? - Extending Python by Adding Keywords & Data types - MailingLogger 3.2.0 Released! - Creating a shared object in python - Wing IDE for Python v. 3.0 beta1 released - Error with Tkinter and tkMessageBox - Encryption recommendation - encode() question - standalone process to interact with the web - get directory and file names - how to add a toolbar to a Frame using wxpython - Plotting Images - interaction of 'with' and 'yield' - simple string backspace question - [2.5] Reading a two-column file into an array? - Free SMS from Computer Worldwide - Where can I get a complete user interface about pylibpcap? - Pysqlite storing file as blob example - Help text embedding in C code? - Re: win32 question in Python - What is the "functional" way of doing this? - Utilizing a raw IDispatch Pointer from Python - Directory - yield keyword usage - Fwd: Re: Comparing Dictionaries - Database objects? Persistence? Sql Server woes - Python-URL! - weekly Python news and links (Jul 30) - Bug? exec converts '\n' to newline in docstrings!? - Replacing overloaded functions with closures. - Subprocess and pipe-fork-exec primitive - File handle not being released by close - Making Gridded Widgets Expandable - Detecting __future__ features - TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? - Cross platform Python app deployment - import struct in Python z/OS - Xinetd & python server script. problem to get data from from client - How to write GUI and event separately in wxPython?? - What is the difference about "pycap" and "pylibpcap"? - problems with logging module - Hex editor display - can this be more pythonic? - UK Ordnance survey coordinates and Geocoding anyone ? - Understanding mxODBC Insert Error - Why Is This The Best Program Online ? - Split a string based on change of character - Compiling 2.5.1 on OpenBSD 4.1 - Memory utilization (linux v. openbsd) - Events: The Python Way - Crunchy security advisory - How to stop print printing spaces? - this must be a stupid question ... - How to write a warning to my log file? - Why no maintained wrapper to Win32? - replacement for execfile - Python 2.5.1 can't find win32file? - pythonic parsing of URL - Packages - problem with change to exceptions - "struct" module problem w/ pyinstaller - Tkinter -- Show Data in an Excel like Read-Only Grid - Tkinter program with a usable interpreter console - Process Control Help - Is access to locals() of "parent" namespace possible? - Problem embedding in small Win32 App - ANN: M2Crypto 0.18 - Removing certain tags from html files - Re: Imported globals? - Compiling python2.5.1 results in 3.5MB python lib? - 128 or 96 bit integer types? - encoding misunderstanding - OOP in Python book? - a simple string question - Imported globals? - Re: [python-list] pdf read & write - Re: <> vs != - [python-list] pdf read & write - [python-list] pdf read & write - Wikicodia - The code snippets wiki - Internet surveying with EZquestionnaire - Re: <> vs != - Submit form, open result in a browser - Filtering content of a text file - Compile python with Mingw - slow emails - Factory pattern again - Problem with authentification - Weekly Python Patch/Bug Summary - instantiate a 'classobj' - Another C API Question - C API -- Two questions - generating objects of a type from a name. - zip() function troubles - automatic type conversion for comparison operators - Learning Jython? - Re: SQLObject 0.9.1 - CSV Issue - Comparing Dictionaries - question about math module notation - pyparser and recursion problem - Re: removing items from a dictionary ? - encode/decode misunderstanding - removing items from a dictionary ? - Why is "for line in f" faster than readline() - ctypes:passing python class instances through c and back - ANN: eGenix EuroPython 2007 Presentations & Videos - SQLObject 0.9.1 - SQLObject 0.8.5 - SQLObject 0.7.8 - Generating PDF reports - Scope <or> PyQt question - os.path.walk usage on WinXP - Tix.Tk() on Mac Intel - Re: wxGlade: Who knows how to drive this application? - python static with Numeric - Any reason why cStringIO in 2.5 behaves different from 2.4? - compiling sip on vista - Locale-specific string comparasion - cls & self - Keyword argument 'from'; invalid syntax - curses/urwid simple menu - Re: TypeError: 'int' object is not callable for max(2,3) - Bug in cPickle with packages and 'object' inherited class - Re: first, second, etc line of text file - first, second, etc line of text file - making a variable available in a function from decorator - Relative-importing * - Windows error 126 loading a dll on windows 2000 - wxGlade: Who knows how to drive this application? - This One is ULTIMATE. (Dont' Miss) - Flatten a list/tuple and Call a function with tuples - Python course around Boston - How to tell when a socket is closed on the other end? - 16-bit colour representation - adding a docstring to an instancemethod - Interactive remote debugging by redirecting sys.stdin and sys.stdout to a socket or pipe - Unable to abort a FTP command? - How to create a single executable of a Python program - ANN: python-ldap-2.3.1 - Base class for file-like objects? (a.k.a "Stream" in Java) - pg8000 (PostgreSQL DB-API 2.0) under IronPython - how to analyse music stream - printing unicode strings - [ANNOUNCE] PyKota v1.26 is out - Cleaning up a string - Good String Tokenizer - Problem in Socket..... - Memory Logging - Any python module for Traversing HTML files - datetime.time() class - How to pass it a time string? - wxPython - How to add sorting to a ListCtrl? - Closures / Blocks in Python - Re: Tix not properly installed on OS X? - How to programmatically insert pages into MDI. - how to get next month string? - From D - display image through cgi python html - Python pearls required for iteration across fields of data structure - some parts of wxPython broken on Mac - Recursive lists
http://www.velocityreviews.com/forums/archive/f-43-p-129.html
CC-MAIN-2013-20
refinedweb
1,409
59.7
scene.rect - misha_turnbull Hello - I am still working on a chess game. It's coming along nicely, with one exception: the GUI. I've had some trouble with loading the images from files but got that to work, but now run into this problem: As you can see, the grid is not being drawn correctly. Here is the code from the draw()method of the scene: def draw(self): background(0, 0, 0) fill(1, 1, 1) # this loop displays the pieces (works fine) for piece in self.game.board.pieces: tint(1, 1, 1, 0.5) pos = piece.coord.as_screen() img = self.img_names[piece.pythonista_gui_imgname] image(img, pos.x, pos.y, scale_factor, scale_factor) tint(1, 1, 1, 1) # this loop displays the grid (doesn't work) for tile in self.game.board.tiles: # this returns either (0.27462, 0.26326, 0.27367) if the piece is white # or (0.86174, 0.85795, 0.85417) if the piece is black color = tile.color.tilecolor color += (0.3,) # alpha value # get the position of the tile in screen coords # this method DOES function correctly as shown by the above `for piece in pieces` loop pos = tile.coord.as_screen() # draw fill(*color) rect(scale_factor, scale_factor, pos.x, pos.y) fill(1, 1, 1) I think the problem is either in the fill()or rect()function, but I'm not sure which. Any ideas? It looks like you're using pos.xand pos.yas width and height of the rect. I think the order of parameters should be: rect(pos.x, pos.y, scale_factor, scale_factor) - misha_turnbull That was indeed the issue. Thank you!
https://forum.omz-software.com/topic/1597/scene-rect/1
CC-MAIN-2020-40
refinedweb
270
77.23
Re: [Zope] Problem with zope mailing list Since longtime now I have a problem with the Zope mailing list : I always receive, the messages from "[EMAIL PROTECTED] " not from the name of the right person (for 97% messages) ? Any idea ? Take a look at the headers of a Zope list message (ctrl-U in Messenger). It correctly states the Re: [Zope] Adding to an XMLDocument through web forms I Re: [Zope] script or external method ? [EMAIL PROTECTED] wrote: Hi all, i'm a new user of Zope; i'm studing it since two weeks and i think it's very interesting, 'cause has the same power of j2ee application server but it is much more easy to use! While i was developing my first Zope application i fell into this trouble: i would like Re: [Zope] Programatically setting advanced settings in zsql methods Jeff Gentry wrote: Hello ... I have a python based product where I am creating a few zsql methods at the time of instantiation. I recently realized that there is the default 1000 row maximum limit on query rows. While this can be changed through the management interface, I am trying to figure] Q: Embedding documentation in Page Templates? Stephen Nesbitt wrote: All: Does anyone know of a way of embedding documentation directly into a page template without using !-- --? In other words is there some construct which tells the rendering engine to simply ignore some content.? I usually use tal:comment replace=nothing comment in] Some problem about Data.fs Fu-Ming_Tsai wrote: What I meant is that if there are more and more objects, maybe it cause some problem because there are a big Data.fs. Doesn't it cause any problem if there are a big big Data.fs? Not particularly. If you hit the upper limit of your disk or filesystem limits on file Re: [Zope] Restart button in Control Panel Jake wrote: You are starting it in Debug mode, which means it will not allow for the restart button. /etc/zope.conf (edit debug mode) Also, try running it with: /bin/zopectl start I don't think that debug mode has anything to do with it. Rather, if you're using runzope it's not running in daemon Re: [Zope] Convert Photos to ExtImage store David Chandek-Stark wrote: I have a few PhotoFolders containing Photos that are stored in the ZODB which I would like to convert to ExtImage storage. Since the number is large enough to make a manual process painful, I'd like to write a conversion script. Seems simple enough in principle, but Re: [Zope] Adding Carriage return/line feed to a text field MCDONNELL, LARRY wrote: I have a form that the field length for that element is set to 65k in the database. Using a textbox, the person can enter their information. I now want to view the text. I can again use a text box but what I want to do is this dtml-var mytext If I use this format, Re: [Zope] Re: Zeo ken wood wrote: Re: [Zope] Which sound I learn? Ryan Smiderle wrote: I'm planning on making a website with Zope, and plan to do a lot of custumization. Should I learn Zope 2 or Zope 3? If it's from scratch and you don't need any existing third-party Products, then probably Zope 3. Zope 2.8 will include Five, which makes Zope 3-style stuff Re: [Zope] Generating and Downloading PDF. Fernando Lujan wrote: Hi guys, I'm creating a pdf using reportlab, after the canvas.close() I put the following code inside a External Method: R = self.REQUEST.RESPONSE R.setHeader('content-type', 'application/rtf') R.setHeader('content-length', str(len(data))) R.write(data) But I receive the Re: [Zope] Generating and Downloading PDF. Fernando Lujan wrote: J Cameron Cooper wrote: The method that contains your code must have at least the first parameter 'self':: def pdfwrite(self): R = self.REQUEST.RESPONSE R.setHeader('content-type', 'application/rtf') R.setHeader('content-length', str(len(data))) R.write Re: [Zope] Generating and Downloading PDF. Fernando Lujan wrote: J Cameron Cooper wrote: Fernando Lujan wrote: J Cameron Cooper wrote: The method that contains your code must have at least the first parameter 'self':: def pdfwrite(self): R = self.REQUEST.RESPONSE R.setHeader('content-type', 'application/rtf') R.setHeader Re: [Zope] Exporting Plone objects to Zope CMF Kanealii, Priam Mr KRS wrote: Dear Re: [Zope] Help.. I accidentally deleted admin at the root acl_users u Re: [Zope] Sending mail with attachments via Python Kirk Strauser wrote: I'm currently trying to replace a bit of DTML with a Python script. Here's what I currently have: dtml-sendmail mailhost=outboundserver To: dtml-var recipientemail From: dtml-var senderemail Subject: dtml-var subject dtml-mime type=text/plain encode=7bit Attention dtml. That's what I was afraid Re: [Zope] Sending mail with attachments via Python Kirk Strauser wrote: On Tuesday 03 May 2005 16:09, J Cameron Cooper wrote: So you have it in DTML and want to re-write in Python but you don't want to do it in Python? What's wrong with External Methods? It takes all of about 5 seconds more than a TTW Python script. They're a necessary Re: [Zope] HTML post processing in Zope Cyrille Bonnet wrote: Re: [Zope] i am completely new to zope Lukman Salifu Nayendi wrote: i am a new user of zope, i really want to learn alot about it and know more please help. Well, first, how about you look at the page that shows up when you install Zope. I believe it points to the quick-start and some examples. You'll also find online help in your Re: [Zope] Debugging product init with zopectl? Konrad Rokicki wrote: Hi all, I'm new to Zope, getting started with the minimal project (). For whatever reason, minimal doesn't work out of the box. That would be fine except that when I start Zope with zopectl it reports status as fine and the Re: [Zope] Hiding HTML URL Allen Huang wrote: I just want to show my root URL address whenever people browse into other pages of my site. How do I do this in dtml or python script or external method?? If I understand what you're asking, there's only one good way to do that: place your content in an iframe (or regular Re: [Zope] formatting tuple to feed to mysql David Siedband wrote: I SelectedIDs=[ai[0] for ai in Re: [Zope] Underscoring Inaugural Address Dan Pozmanter wrote: Hello there Zopatistas, In my inaugural post, I should like to enquire about getting to a url like so: Getting to the object __init__.py is difficult (it acts like it doesn't exist.) Is there a Re: [Zope] How to find out the full URL Hong Yuan wrote: I have a page template, say 'products.pt', which takes traverse_subpath[0] as one of the variables, so e.g. the URL: will actually call products.pt, which get 100 from the URL and displays it in the template. Now my question is how can I get the Re: [Zope] How to make a ZPT-based form that calls itself? Ken Winter wrote: Hi Zopers - Re: [Zope] How to make a ZPT-based form that calls itself? Ken Winter wrote: -Original Message- From: J Cameron Cooper [mailto:[EMAIL PROTECTED] Sent: Wednesday, May 11, 2005 4:27 PM To: [EMAIL PROTECTED] Cc: zope@zope.org Subject: Re: [Zope] How to make a ZPT-based form that calls itself? Ken Winter wrote: Hi Zopers - I'm trying to make a ZPT Re: [Zope] ack! Zope stopped starting as a Windows Service Chris Curvey wrote: Everything was going so well today, too Zope was installed as part of the Plone 2 installer on Win2K. Has been running fine for several months. I was adding some issues to my collector, and things started hanging up on my system. After reboot, the Zope service did not Re: [Zope] UserFolder problem Phil Beardmore wrote: Hi All, hope you can help... I have a problem trying to use the LDAPUserFolder product. Basically I have a site named, and the site is Plone powered. I have a normal UserFolder at the top level folder which holds the members who have manager roles etc. Re: [Zope] upload folder contents garry saddington wrote: If a set of web pages is generated by for instance the output of a Docbook transformation or by the new eXe XHTML editor, is there any way of uploading all the resulting pages into Zope in one go and maintaining the individual file names so that links remain working. I Re: [Zope] Equivalent of context ZPT variable in DTML ? KLEIN Stéphane wrote: What is the equivalent in DTML of ZPT context variable ? There is no precise equivalent. The current context in DTML is folded into the DTML namespace, along with the request and call parameters and anything else that might be put in the namespace. --jcc -- Re: [Zope] newbie question Phillip Hutchings wrote: Re: [Zope] Namespace for PythonScript Hong Yuan wrote: If a PythonScript is called from a Page Template, how can it access the variables defined using: tal:define=global ... / in the calling script? Of course, one can pass the variables to the PythonScript explicitly as parameters, but is there any other way to let the Re: [Zope] LDAPUserFolder at Zope root with an intent to instanciate a LDAPUSerFolder afterwards but that locked me out Re: [Zope] Accessing file object to upload in an external method Simon ALEXANDRE wrote: I'm new in zope and I'm trying to upload a file on zope using localfs. I already done it through a little basic html page + python script. I would like now use it in an external method. Here is the line added in the external method: Re: [Zope] LDAPUserFolder at Zope root Jens Vagelpohl wrote: On May 26, 2005, at 22:34, J Cameron Cooper wrote: Re: [Zope] Receiving mails Varun Parange wrote: i have downloaded an SMTP server and using it i can send mails with the help of Zope MailHost however i would also like to recieve mails how do i do this. which additional products do i need to download... I recall some people talking about actually turning Re: [Zope] python question Kate Legere wrote: I may be asking this in the wrong place but I have a tal page where I want to use python to display only the most recent addition to a folder of files. I can sort the folder and return all the files easily with: return sequence.sort(files, (('bobobase_modification_time',: Many thanks for your suggestion. Is there a worked example of doing this anywhere? There seem to be quite a few Re: [Zope] Creating links dynamically John Poltorak wrote: On Tue, May 31, 2005 at 02:51:18PM -0500, J Cameron Cooper wrote: John Poltorak wrote: Well, it's really easy. Create 'linkList' (Python Script) in the folder where you page lives or somewhere higher in folder hierarchy: ## Script (Python) linkList return [ ('http Re: [Zope] Re: Creating links dynamically Josef Meile wrote: Re: [Zope] Calling a page template from a DTML document John Poltorak wrote: Is there any way of getting a DTML document to use a page template to build part of a page? Some sample code would be handy as an illustration if what I want to do is possible. Just call it exactly like you might do with, well, anything else:: dtml-var Re: [Zope] recommend a provider Also in the Zope hosting game is iMeme: --jcc -- Building Websites with Plone ___ Zope maillist - Zope@zope.org ** No cross posts or HTML Re: [Zope] DiskBased Product question Haim Ashkenazi wrote: Re: [Zope] Transferring Zope Settings jlegris wrote: Hello All, I need to transfer Plone/Zope settings from a test instance to a live instance of the Zope server. Aside from transferring the entire Data.fs file or manually copying scripts and replicating configuration settings, is there a simple way to do this? Any advice Re: [Zope] undo many things Rakotomandimby (R12y) Mihamina wrote: Re: [Zope] backing up a running zodb fileStorage gabor wrote: i am trying to backup a zodb filestorage of a running zope. i'm on linux. i've read that you simply make a copy of the Data.fs file.. but what about the modifications/transactions that are happening when i make the copy. will not the database be in a corrupt state then? The Re: [Zope] Form Variables David Ayres wrote: I've been working around this issue for literally years and finally have the time to seek a real solution. :) I can't find much information, so I'm assuming I'm just taking the wrong approach. Whenever a form is posted, the text fields always show up in the request.form, Re: [Zope] Exiting a Loop Asad Habib wrote: Is there a way to exit a dtml-in based loop? I searched numerous resources but did not find anything on this topic that relates to the dtml-in tag. Any help would be greatly appreciated. Thanks. There is no such provision. You shouldn't be doing such a thing anyway: that Re: [Zope] Exiting a Loop Asad Habib wrote: Yes, I should not be doing this but I am using DTML not ZPT and since DTML provides programming functionality and in this case the ability to loop, there should be a way to exit a loop as well. DTML is not a complete programming language; it simply provides some (too-) Re: [Zope] Form Variables David Ayres wrote: Thanks for the information. I have been pulling my hair out because I have some lengthy forms (wizards) and it can be harrowing at times. :) I think the best solution for my situation is to do a JS/CSS tabbed solution, so it's one form. Are you aware of any limitations on the Re: [Zope] Python Scripts We have been seeing a number of instances where python scripts fail due to an apparent syntax error but the syntax is correct and simply storing the method restores it to functionality. Anyone else seeing this? How do you mean fail? Often times, if you have an error, save, test, and then Re: [Zope] Passing parameters using DTML John Poltorak wrote: On Fri, Jun 17, 2005 at 07:09:04PM +0200, Dieter Maurer wrote: Tino Wildenhain wrote at 2005-6-17 10:57 +0200: ... Not at all. You could either have tried it out ;) Or looked at the DTML documentation in the Zope book *wink* ;) dtml-var Re: [Zope] Passing parameters using DTML John Poltorak wrote: On Fri, Jun 17, 2005 at 05:07:32PM -0400, Paul Winkler wrote: On Fri, Jun 17, 2005 at 08:24:23PM +0100, John Poltorak wrote: Is there also something which explains how to call ZPTs from a DTML object? I'm unable to pick up a passed parameter. This is what I've Re: [Zope] ZODB error when trying to index object (Input/output error) Felix Ulrich-Oltean wrote: Re: [Zope] ZPT tutorial John Poltorak wrote: Does a ZPT tutorial exist anywhere? How about: Specifically: There's something odd about the rendering of the second one, but Re: [Zope] Factory-based Type Information Denis Mishunoff wrote: I have a problem with my product. I use Zope 2.7.5 and Plone 2.0.5. I need to create the copy of Document content-type on my product's install the same way as it is done in portal_types via Factory-based Type Information option of dropdown. I just need to have the copy Re: [Zope] ZPT code sample John Poltorak wrote: On Tue, Jun 21, 2005 at 06:07:36PM +0200, Andreas Jung wrote: --On 21. Juni 2005 11:58:52 -0400 Fred Drake [EMAIL PROTECTED] wrote: On 6/21/05, John Poltorak [EMAIL PROTECTED] wrote: Is there anything wrong with this ZPT code sample? Re: [Zope] ZPT tutorial John Poltorak wrote: Re: [Zope] ZPT contents slot John Poltorak wrote: If I create a macro which defines a slot called 'content', is there any way to have that slot populated by a file with a specific name if it exists in a folder? What I'd like to do is create a structure text file, in each of the folders A B C and have it automatically Re: [Zope] ZPT contents slot John Poltorak wrote: On Tue, Jun 21, 2005 at 03:16:11PM -0500, J Cameron Cooper wrote: John Poltorak wrote: If I create a macro which defines a slot called 'content', is there any way to have that slot populated by a file with a specific name if it exists in a folder? What I'd like to do Re: [Zope] ZPT contents slot John Poltorak wrote: On Tue, Jun 21, 2005 at 04:46:55PM -0500, J Cameron Cooper wrote: John Poltorak wrote: Is 'stxfile' the actual filename? I'm not concerned about it being structured initially - just want to see it working in principle with any file containg some text. It's the name Re: [Zope] Reading lines from a Zope File object John Poltorak wrote: What function is used to read lines from a Zope File object using Python? Is there any example of this anywhere? Doing a search for 'python read zope object' is just too generic to find any python code to do this. You can get the main contents of a File with the 'data' Re: [Zope] Reading lines from a Zope File object Andy McKay wrote: J Cameron Cooper wrote: You can get the main contents of a File with the 'data' attribute. It returns a string. I think it actually returns an object (for large file support), if you want the data as a string you need to string it. So for small files: datastr = str Re: [Zope] Tweaking Zope DB- and connection parameters Apache is set to MaxClients 50 Zope.conf has set zserver-threads 5 and zodb_db main cache-size 500 pool-size 25 ... /zodb_db I will note that a cache-size of 500 is ridiculously low. (Even though old versions of Zope shipped configured like this!) It needs to be at least 5000. Frankly, Re: [Zope] loading an url from a restricted python script santiago.. There Re: [Zope] Sequencing pages John Poltorak wrote: If I create individual pages for a website as sub folders of a sites main folder, how do I control the sequence of pages if I automatically generate a set of links to all the folders? I presume that under normal circumstances that sequence would be in alphabetical order of Re: [Zope] Sequencing pages John Poltorak wrote: On Tue, Jun 28, 2005 at 03:45:01PM -0500, J Cameron Cooper wrote: John Poltorak wrote: If I create individual pages for a website as sub folders of a sites main folder, how do I control the sequence of pages if I automatically generate a set of links to all the folders Re: [Zope] TAL and Javascript Rob Boyd wrote: I'm stuck this, and would appreciate help or pointers. I have a form with 2 selection drop-downs. I want the user's choice of select 1 to drive the options displayed in select 2. When the user makes a selection in select 1, onChange calls a Javascript function that should write Re: [Zope] TAL and Javascript Rob Boyd wrote: Thanks to all the responders. It gave me some ideas, but alas no luck. To clarify, I am not trying to do everything in one request. Request one generates the page, a user event (selecting an option from a form) fires another request via javascript. I do not see it creating Re: [Zope] Re: [ZPT] Recursive structures Nikko Wolf wrote: Ian Bicking wrote: I'm surprised this has never come up for me before, but now I want to render a recursive data structure and I'm at a loss how I might do that in ZPT. Or, what the best workaround would be. E.g.: ['a', 'b', ['c', ['d', 'e']]] Becomes: ul lia/li Re: [Zope] Zope update Josef Burger wrote: Hi, I want to update from Zope 2.7.4 to Zope 2.7.6 What is the easiest way? Unfortunately there is no description of how an update of Zope is done. I'm running Plone on it. I tried to newly install Zope 2.7.6 and then copied the backed-up Data.fs file and the content of Re: [Zope] Passing a variable to RESPONSE.redirect Asad Habib wrote: Is it possible to pass a variable to RESPONSE.redirect or does the page name have to be a literal string? I was unable to pass in a variable via the REQUEST object (i.e. REQUEST.get('pageName')) or the SESSION attribute of the REQUEST object (i.e. Re: [Zope] How to upload a file and save it in a physical path? There are several products to do this: LocalFS, Re: [Zope] Python formatting question [EMAIL PROTECTED] wrote: In a Python script, how can I break up a SQL statement over more than one line? For example, to transform #generate the sql statement sql=DELETE FROM tblUsers WHERE user_name LIKE '%' to: #generate the sql statement sql=DELETE FROM tblUsersWHERE user_name Re: [Zope] ZPyIRC and Zope 2.7 David wrote: Hi I installed ZPyIRC version 0.1.3 in Zope 2.7.5 and I get Zope Template Errors on two of the frames when trying to start a chat client. I don't know ZTP very well. (Python is 2.3.5) I was hoping that maybe somebody has fixed the templates for 2.7. Any help very welcome! Re: [Zope] getting atachments with python - pop3 Jonathan Salazar Santos wrote: Hi, im making a email client in python for zope, but a im stopped because i cant find the way to get the attacments with python, do you have a idea how can i do this?, i have studied the email package already but is a little confused. A Python-specific list might Re: [Zope] product organization N Re: [Zope] What Maximum age of a cache entry (seconds) means in RAM Cache Manager? Litao Wei wrote: I have read the zope book and zope online help about RAM Cache Manager. But all of them didn't say anything about the parameter What Maximum age of a cache entry (seconds) mean. It looks that this parameter like Cleanup interval (seconds), which zope book explained as The Re: [Zope] rendering the contents of .. David Bear wrote: I Re: [Zope] rendering the contents of .. David Bear wrote: On 8/1/05, J Cameron Cooper [EMAIL PROTECTED] wrote: David Bear wrote: I am looking at a couple way of producing a qotd solution. one way is to put quotes in a folder. Then use objectvalues on the folder and randomly select one of the items. I get get the objectid. but I Re: [Zope] Re: localhost:8080 not found on windows michael nt milne wrote: Ok, thanks. Yes, Apache would be much better to route traffic through. And also it looks like a complete pain to try and route traffic through IIS. That's my understanding. You can either look up the ASP404 hack or use something like Re: [Zope] Re: dtml-var variable from REQUEST not shown in input tag if it has spaces?? Josef Meile wrote: Re: [Zope] max 2 levels of indirection? Sean Dunn wrote: I’m running Zope 2.0.7, and I’m having a problem.. Consider me a newbie, as I’ve only been using Zope for a few weeks. After boiling the problem down to a test case, it seemed that I couldn’t have a DTML method call a DTML method which then calls a Python script. But then I Re: [Zope] SQL Problem Philip Beardmore wrote: I'm having a really annoying SQL problem which I think (or hope) can easily be sorted but I'm not sure how to do it. I have a ZPT which is collecting data in a form - Both text boxes and checkboxes. The form then passes the variables on to a DTML Method which does a few Re: [Zope] Zope scalabilty and problems Re: [Zope] Same product in multiple instances automatically? Kirk Strauser wrote: On Friday 09 September 2005 10:25, Paul Winkler wrote: To be honest, I'd expect something a little different, namely that each instance would automatically pull in all the products in the site installation (like [1] and [2] above), but that doesn't seem to be the case. Is Re: [Zope] Same product in multiple instances automatically? Kirk Strauser wrote: On Friday 09 September 2005 13:56, J Cameron Cooper wrote: I don't know why, either. That simply says that there is a default Products directory ($SOFTWARE_HOME/lib/python/Products), you can't get rid of it, and you shouldn't try to configure it here. The problem I'm Re: [Zope] Same product in multiple instances automatically? Kirk Strauser wrote: On Friday 09 September 2005 15:37, J Cameron Cooper wrote: Anything in $SOFTWARE_HOME/lib/python/Products is available in any instances that use that SOFTWARE_HOME. You can see this quite easily by looking at the /Control_Panel/Products of an instance with nothing in its Re: [Zope] Zope scalability / efficiency question mark hellewell wrote: Hi Re: [Zope] How to show field names from sql query? Thomas Apostolou wrote: Hello all, i use the following to get to show the results from an sql query. What are the expresions to show the field names? table dtml-in expr=TestODBCEM(sysDSN=sysDSN, usr=usr, mypass=mypass, sSQL=sSQL) dtml-if sequence-even tr bgcolor=lightgreen Re: [Zope] emergency access problems michael nt milne wrote: Hi I appear to be having difficulty logging into the ZMI using the password created on install. I did change some settings to my root login using the Samplex member product etc but didn't change the password, login etc. Anyway I've followed all the instructions in Re: [Zope] Re: DTML-tree Custom sort Chris Beaven wrote: It's really more a cool way to do lists than if statements :) It's technically list comprehension. Sort of a one-line list transform tool. I recommend reading through some of Dive Into Python () for lots more cool hands-on tips on Python Re: [Zope] selected in select lists anything that works. Can anyone see what I am doing Re: [Zope] selected in select lists Garry Saddington wrote: J Cameron Cooper wrote: Re: [Zope] selected in select lists Garry Saddington wrote: Nicolas Gouzy wrote: I think this code works : select name=groupabbrev dtml-in getpastoralgroups option value=dtml-var expr=_['sequence-item'] dtml-if expr=groupabbrev==_['sequence-item'] selected/dtml-if dtml-var expr=_['sequence-item']/option /dtml-in /select --
https://www.mail-archive.com/search?l=zope@zope.org&q=from:%22J+Cameron+Cooper%22
CC-MAIN-2021-25
refinedweb
4,499
67.79
Hi everyone, its been a while since i last posted, i started teaching myself C a while ago and i'm trying to get back to it. Been really busy at work with fun languages like Ocean! Anyway, i like to learn by having a project and working towards it. So i thought i would try to write a program which could display a truth table given a boolean expression. My first stumbling block has been dynamic arrays. I searched through the forums and found references to malloc(). I'm not asking these to be explained but i thought now would be a good time to ask if anyone has a better method of how to go about this? I don't know how well C deals with binary. This is what i have so far: of course this doesn't work, cause i'm stupid and didn't know you couldn't do that with arrays. This is only the part which will walk through the binary representation of 0 to 15 (for example)of course this doesn't work, cause i'm stupid and didn't know you couldn't do that with arrays. This is only the part which will walk through the binary representation of 0 to 15 (for example)Code: #include <stdio.h> int main() { //Initialise Variables int x, i; int max_value; int inputs[x]; int bcd_dec; int count; int bit; int reg; x = 4; //width of array max_value = 1; for (i = 0; i < 2; i++) { max_value *= x; //Given 'x' binary bits, max_value is all bits set to 1 +1 } printf("max_value = %d\n", max_value); for (i = max_value - 1; i >= 0; i--) //for each value { count = max_value / 2; //MSB printf("i = %d\n", i); bit = 0; reg = i; while(count > 0) { printf("count = %d\n", count); //Count corresponds to value of each bit. printf("reg = %d\n", reg); bit = x - bit; printf("bit = %d\n", bit); if (reg >= count) //if value is greater than or equal to //corresponding bit, set it { printf("reg>count"); inputs[bit] = 1; reg = reg - count; } else //or not { printf("reg<count"); inputs[bit] = 0; } printf("[%d]", inputs[bit]); bit = bit++; //move to next bit count = count / 2; //and corresponding value } printf("\n"); } } Sorry for the long post. Your help would be appreciated. Also, does anyone have any ideas for projects? Maybe someone wants to set me a not to difficult task? Kai.
https://cboard.cprogramming.com/c-programming/106577-truth-tables-binary-printable-thread.html
CC-MAIN-2017-22
refinedweb
402
73.61
Re: Help With PyParsing of output from win32pdhutil.ShowAllProcesses() - From: Paul McGuire <ptmcg@xxxxxxxxxxxxx> - Date: Wed, 12 Sep 2007 01:21:08 -0700 On Sep 11, 1:12 pm, Steve <sreissc...@xxxxxxxxx> wrote: Hi All (especially Paul McGuire!)<snip> Could you lend a hand in the grammar and paring of the output from the function win32pdhutil.ShowAllProcesses()? This is the code that I have so far (it is very clumsy at the moment) : Many thanks! Steve Steve - Well, your first issue is not a pyparsing one, but one of redirecting stdout. win32pdhutil.ShowAllProcesses does not *return* the output you listed, it just prints it to stdout. The value returned is None, which is why you are having trouble parsing it (even after converting None to a string). For you to parse out this data, you will need to redirect stdout to a string buffer, run ShowAllProcesses, and then put stdout back the way it was. Python's cStringIO module is perfect for this: from cStringIO import StringIO import sys import win32pdhutil save_stdout = sys.stdout process_info = StringIO() sys.stdout = process_info win32pdhutil.ShowAllProcesses() sys.stdout = save_stdout sProcess_Info = process_info.getvalue() *Now* you have all that data captured into a processable string. As others have mentioned, this data is pretty predictably formatted, so pyparsing may be more than you need. How about plain old split? for line in sProcess_Info.splitlines()[1:]: data = line.split() print data Done! Still have an urge to parse with pyparsing? Here are some comments on your grammar: - Your definition of process_name was not sufficient on my system. I had some processes running whose names includes numeric digits and other non-alphas. I needed to modify process_name to: process_name = pyparsing.Word(pyparsing.alphanums+"_.-") - Similarly, some of my values returned by ShowAllProcesses had negative values, so your definition of integer needs to comprehend an optional leading '-' sign. (This actually sounds like a bug in win32pdhutil - I don't think any of these listed quantities should report a negative value.) - Whenever I have integers in a grammar, I usually convert them to ints at parse time, using a parse action: integer.setParseAction( lambda tokens : int(tokens[0]) ) - The tabular format of this data, and the fact that the initial entry in each row appears to be a label of some sort invites the use of the pyparsing Dict class. I note that you are already trying to extract keys from the parsed data, so it looks like you are already thinking along these lines. (Unfortunately, it is very likely you will get duplicate keys, since process names do not have to be unique - this will involve some loss of data in this example.) The Dict class auto- generates results names in the parsed results. Dict turns out to be awkward to use directly, so I added the dictOf method to simplify things. The concept of dictOf(keyExpr,valueExpr) is "parse a list of dict entries, each of which is a key-value pair; while parsing, label each entry with the parsed key." In your example, this would be: ProcessList = heading + pyparsing.dictOf(process_name, pyparsing.OneOrMore(integer) ) The key is a leading process_name, and the value is the following list of integers. With this, you can print out the results using: data = ProcessList.parseString(sProcess_Info) print "data keys:", data.keys() for k in sorted(data.keys()): print k, ":", data[k] Getting: BCMWLTRY : [684, 0, 0, 0, 54353920, 53010432] CLI : [248, 0, 0, 0, 171941888, 153014272] D4 : [2904, 0, 0, 0, 37527552, 36413440] F-StopW : [2064, 0, 0, 0, 33669120, 30121984] .... (again, note that the multiple entries for "CLI" have been reduced to a single dict entry) You could get similar results using something like: data = dict((vals[0],vals[1:]) for vals in map(str.split,sProcess_Info.splitlines())) But then you would never have learned about dictOf! Enjoy! -- Paul . - References: - Prev by Date: How can I work on VIM for python code such as cscope for C code? - Next by Date: Re: Excel process still running after program completion - SOLVED - Previous by thread: Re: Help With PyParsing of output from win32pdhutil.ShowAllProcesses() - Next by thread: Lost in __setstate__() in C++ and swig - Index(es):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2007-09/msg01451.html
crawl-002
refinedweb
692
64.81
Hi, I am working on a project which uses stlport and Oracle Class Library. I have run some demo projects for OCL which work fine. However when I use stlport and OCL together in the project; It generates a runtime error "Illegal instruction". the part of code giving this error is given below #include "ocl.h" using namespace ocl; int main() { OraConnection connection; char* connectString = "uName/password@dbName"; connection.setConnectString(connectString); connection.open(); // "Illegal instruction" connection.close(); } This program compiles and links right. It gives the error at runtime. Please help me with this Regards, Sudarshan conflict between OCL and stlport Discussion of open issues, suggestions and bugs regarding database management and development tools for Oracle Post Reply 2 posts • Page 1 of 1 - Posts: 1 - Joined: Wed 07 Jan 2009 11:54 Post Reply 2 posts • Page 1 of 1
https://forums.devart.com/viewtopic.php?f=22&t=13823
CC-MAIN-2018-34
refinedweb
141
56.45
NAME tar.h - extended tar definitions SYNOPSIS #include <tar.h> DESCRIPTION The <tar.h> header shall define header block definitions as follows. General definitions: Name Description Value TMAGIC "ustar" ustar plus null byte. TMAGLEN 6 Length of the above. TVERSION "00" 00 without a null byte. TVERSLEN 2 Length of the above. Typeflag field definitions: Name Description Value REGTYPE ’0’ Regular file. AREGTYPE ’\0’ Regular file. LNKTYPE ’1’ Link. SYMTYPE ’2’ Symbolic link. CHRTYPE ’3’ Character special. BLKTYPE ’4’ Block special. DIRTYPE ’5’ Directory. FIFOTYPE ’6’ FIFO special. CONTTYPE ’7’ Reserved. Mode field bit definitions (octal): Name Description Value TSUID 04000 Set UID on execution. TSGID 02000 Set GID on execution. TSVTX 01000 On directories, restricted deletion flag. TUREAD 00400 Read by owner. TUWRITE 00200 Write by owner special. TUEXEC 00100 Execute/search by owner. TGREAD 00040 Read by group. TGWRITE 00020 Write by group. TGEXEC 00010 Execute/search by group. TOREAD 00004 Read by other. TOWRITE 00002 Write by other. TOEXEC 00001 Execute/search by other. .
http://manpages.ubuntu.com/manpages/dapper/man7/tar.h.7posix.html
CC-MAIN-2014-42
refinedweb
167
57.13
fattach - attach a STREAMS-based file descriptor to a file in the file system name space #include <stropts.h> int fattach(int fildes, const char *path); The fattach() function attaches a STREAMS-based file descriptor to a file, effectively associating a pathname with fildes. The fildes argument must be a valid open file descriptor associated with a STREAMS file. The path argument points to a pathname of an existing file. The process must have appropriate privileges, or must be the owner of the file named by path and have write permission. A successful call to fattach() causes are initialised are affected. File descriptors referring to the underlying file, opened prior to an fattach() call, continue to refer to the underlying file. Upon successful completion, fattach() returns 0. Otherwise, -1 is returned and errno is set to indicate the error. The fattach() function will. - [EBUSY] - The file named by path is currently a mount point or has a STREAMS file attached to it. - [ENAMETOOLONG] - The size of path exceeds {PATH_MAX}, or a component of path is longer than {NAME_MAX}. - [ELOOP] - Too many symbolic links were encountered in resolving path. The fattach() function may fail if: - [EINVAL] - The fildes argument does not refer to a STREAMS file. - [ENAMETOOLONG] - Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. - [EXDEV] - A link to a file on another file system was attempted. None.. None. fdetach(), isastream(), <stropts.h>.
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/fattach.html
CC-MAIN-2014-41
refinedweb
238
57.57
I'm trying to remove the 3d border from a windows popup menu and replace it with a simple 'flat' border (like ws_border). Whenever I try to set WS_BORDER and remove all styles and ex styles that would create a 3d border it doesn't work. I have now subclassed the window so I can paint it myself, but when I call the old window proc I get a stack overflow. Am I trying to make a flat border the wrong way?Am I trying to make a flat border the wrong way?Code:... lpfnMainMenuWndProc = (WNDPROC) SetWindowLong ( hMenuWnd, GWL_WNDPROC, (DWORD) MainMenuWndProc ) ; ... LRESULT CALLBACK MainMenuWndProc ( ... ) { ... return ( CallWindowProc ( lpfnMainMenuWndProc, hWnd, uMsg, wParam, lParam ) ) ; } Thanks
http://cboard.cprogramming.com/windows-programming/67547-flat-menu-problem.html
CC-MAIN-2015-14
refinedweb
112
74.69
So i am writing a program and i made a function which stores user data in a txt file.It is like a simple registration function.The user gives the username and password to store.Problem is i can't store user input in the file. My code is : def reguser(): #Function name. fwu = open('user.txt','w') #create or open user.txt file. user = input("Username: ") #takes the user input.e.g what username to register fwu.write(user) #this command should write input into the file fwp = open('pass.txt','w') #create or open pass.txt file. pas = input ("Password: ") #takes user input e.g what password to register fwp.write(pas) #write the password into the file print ("To check for registraion completion, please login.") askuser() You didn't fwu.close() or fwp.close() (you didn't save it). Also a quick look up next time would save you some time. .write not working in Python
https://codedump.io/share/1RwbbgfO9Baa/1/how-to-store-user-input-in-txt-filepython-3
CC-MAIN-2018-13
refinedweb
159
72.32
Visual C++ Express, like all the Express versions, offers a free, almost full function implementation IDE for developing C++ applications on Microsoft Windows. While the Express Edition provides a number of skeleton projects, it does not include the ability to create custom wizards; a serious deficiency in my opinion. However, all is not lost, as it is still possible to create a custom wizard by hand which should provide for the needs of the most demanding developer. This article attempts to demonstrate the steps necessary to 'roll your own' wizard. The details presented here are based on Visual C++ 2008 Express Edition, but with a few modifications, it can be adapted to the 2005 or (I hope) future versions. The information presented here assumes a knowledge of C/C++ (for obvious reasons), and also HTML and JavaScript; although in depth understanding of the latter two is not essential. The concept behind the custom wizard is that the developer can create a skeleton project which contains the main source and resource files to build various flavours of a 'standard' application, which can then be modified to the specific needs of the job in hand. The skeleton project is a buildable set of source modules that contains the most common features of a project, thus easing the development cycle. While it is still quite simple to use copy and paste to copy blocks of code from one project to another, the custom wizard is able to generate all the files needed for a project with just a few dialogs. In addition to providing the skeleton source and resource files, the wizard allows for selective generation of files or parts of files, project build options and customized content based on user selected options and wizard variables. The wizard engine contains a number of standard variables, and new ones may be added to the custom wizard as described below. The source tree for the custom wizard project follows the source tree structure in the $(VCInstallDir) directory, which is at C:\Program Files\Microsoft Visual Studio 9.0\VC on my system. The custom wizard files are installed in the VCProjects and VCWizards directories in this tree which look like this: The Express\VCProjects directory holds the registration files for the custom wizard, and the VCWizards directory holds the control and template files to build a new project. The first thing we need for a custom wizard is a skeleton project, and I always start by copying the directory tree of the AppWiz\Generic\Application project under the VCWizards directory into my project workspace. I can then edit these files as necessary for my custom wizard without the risk of damaging the Microsoft supplied version. The completed solution is downloadable from the link at the start of this article. The project I am creating here is a fairly basic one which will produce either a simple Win32 application or a dialog based one, but I hope it demonstrates some of the possible options. The second thing we need is to create the control files that drive the wizard engine dialogs which allow us to select the project type and any optional settings in order to generate our new project. Finally we need to register our wizard with the Visual C++ Express system so that we can select it from the New Project dialog. It is not very easy to test the new wizard without having it registered so we will take these steps in the wrong order, which I hope will actually help you understand how it all fits together. In the sample I have created, I have named the wizard CustomWiz but you are free to name it anything you like as long as it does not conflict with one already registered. CustomWiz A final note: All the files in the wizard are effectively text files so do not need to be built in the traditional sense. They do, however, need to be copied to the wizard location in the VCWizards tree, and I use a custom build step similar to the following to achieve this: VCWizards copy "$(InputPath)" "$(VCInstallDir)VCWizards\CustomWiz\Generic\Application\html\1033" copying $(InputFileName) to $(VCInstallDir)VCWizards\CustomWiz\Generic\Application\html\1033 $(VCInstallDir)VCWizards\CustomWiz\Generic\Application\html\1033\$(InputFileName) Note that the destination paths will need to point to the correct part of the tree for each group of files; see the sample project for further information. Note also that under Windows 7 (and probably Vista), you will need to run VC++ Express as Administrator the first time you build the project, as it will need to create new directories in $(VCInstallDir) which is a protected location. $(VCInstallDir) The definition files in the Express\VCProjects directory identify the name and location of the wizard, whose control and template files are stored under the VCWizards directory thus: VSWIZARD 7.0 Wizard=VsWizard.VsWizardEngine.9.0 Param="WIZARD_NAME = Application" Param="RELATIVE_PATH = VCWizards\CustomWiz\Generic" Param="WIZARD_ID = 103" VSWIZARD Wizard RELATIVE_PATH WIZARD_NAME WIZARD_ID # Field contents are as follows: see Inside Visual C++ Wizards[<a title=""New" href="%22" target=""_blank"">^</a>] # RelPathName - relative path from here to the .vsz file # {clsidPackage} - always zero for user defined wizards # LocalizedName - name that appears in the Add New Project dialog box # SortPriority - sort order and relative priority of the Wizard, # with 1 being highest # Description - A localizable description as it will appear in the # Add New Project dialog when the item is selected # DLLPath - always zero for user defined wizards # IconResourceId - always zero for user defined wizards # Flags - generally zero # BaseName - suggested base name for the generated item, # displayed in the Name field in the Add New Project dialog # ..\CustomWiz.vsz|0|Custom Windows application|1|Create a Custom Windows application or dialog|0|0|0|WinApp Having created the above files, they may now be copied to the Express\VCProjects directory (see notes above for build rules), and the wizard should now show up in response to the following: Win32 Windows application Note that if you actually do press OK on the dialog at this time, you will get an error message as there is no wizard to run yet; that is addressed in the next section. The wizard control files are stored in the VCWizards\CustomWiz\Generic\Application directory (see CustomWiz.vsz above). Note that in these directory trees 1033 is the numeric representation of the Windows language code for English; check on your own system for the correct value and adjust as appropriate. The actual control files are modified versions of Microsoft's originals, so be careful not to offer your custom wizard for sale, as that would infringe Microsoft's copyright. The actual directory tree structure is as follows: 1033 The first page to be displayed by the wizard engine is generated by the default.htm file which can be seen in the section titled "Using the Wizard" below. The modified markup for this is shown within the file itself, with each change marked by a comment of the form: <!-- CustomWiz 1. change comment --> and in some cases the original Microsoft code will be enclosed in a HTML comment block. The actual changes are as follows: This file contains the markup to select the project type and options for the generated project, and can also be seen in the "Using the Wizard" section below. It is annotated in the same manner as default.htm with the CustomWiz tag. The changes are not numbered, but fall into the following categories as shown in the file itself. The individual changes are not listed here but broadly speaking they are used to disable some of the options offered by the Microsoft Win32 wizard, from which this was derived, and to add the options for creating the two project types offered by this wizard; use the Edit->Find option to locate the changes. The addition of other project types and options is left as an exercise for the reader. This file contains further JavaScript which is invoked by the wizard when the user presses the OK button to generate the new project. There is very little information on the functions in this module, so I will list here what I have discovered by trial and (lots of) error; modify to your own needs as required. OnFinish() SetFileProperties() GetTargetName() GetAppType() AddSpecificConfig() The following changes have been made to the foregoing, and are annotated as described earlier. The wizard template files are the remaining files that are used to build the skeleton project. In its simplest form, a skeleton project contains one set of source files which will always build into the same basic application. There is little to be gained from such a project being generated by a wizard however. The point of using the wizard is to allow the user to select a different project type, and to customize the project by selecting various options, as described in the following sections. All of the template files are stored in the VCWizards\CustomWiz\Generic\Application directory as follows: Optional selections made in the wizard dialogs are held as property items within the wizard engine and allow the project control files to amend the project itself, but also allows the template files to contain statements controlling the generation or suppression of parts of the source. This is where the real power of the code wizard lies, as it allows us to start from a single source file which is customizable by the user. The sample code I have provided here will generate two applications as defined earlier, a simple Windows or Dialog application. I have tried to keep both applications as simple as possible to demonstrate the basics of the wizard without the clutter of a sophisticated end product. The source files for these applications are as follows: Note that although the source file names take the form root.xxx or rootXXX.xxx their names are generally changed by the scripts such that 'root' is replaced by the project name. This change is as defined in the GetTargetName() function in default.js. In all cases, the source code can be generated or suppressed by control statements in each module, similar to preprocessor directives. However, this source is modified at the time the project is generated rather than at compile time. The format of these statements is: [!if {expression}] source line(s) if expression is TRUE [!else] source line if expression is FALSE [!endif] Other information may be injected into these files by use of the [!output {e}] directive, for example a line of the form... [!output {e}] #include "[!output PROJECT_NAME].h" ... in a source file whose project name is 'winapp' would then become... winapp #include "winapp.h" ... in the generated source file. Further information on template directives may be found in the MSDN on creating wizards, in the Template Directives[^] section. The Templates.inf file is used to define the source files that will be copied to the new project when the wizard executes. It may contain wizard directives to select certain files based on project type, and will be used by the default.js file. The sample for the CustomWiz wizard looks like this: StdAfx.h StdAfx.cpp root.h [!if WIN_APP] OpenFile | root.cpp [!else] OpenFile | rootDlg.cpp [!endif] root.rc CopyOnly | root.ico The OpenFile directive means that the referenced file will be opened in the IDE when the project is first created. The CopyOnly directive indicates that the wizard should not inspect the content for directives; this is useful for icons, bitmaps and other non-source files. OpenFile CopyOnly Having created the control and template files, we are now ready to test the wizard. Firstly we need to copy all of the wizard files into the VCWizards directory as defined above. Assuming that we have correctly set the build properties on each of the files, we can simply press the Build CustomWiz button, and all will be copied to their correct locations. Build CustomWiz Using the wizard is simply a matter of selecting File->New->Project form the menu, or Ctl+Shift+N from the keyboard. As we saw above, this will bring up the New Project dialog: which should still include our CustomWiz option in the Project Types box. Select the appropriate Template type and name for the project and press OK. This brings up the Custom Wizard dialog: OK which shows the base details of the current selection. Pressing Next forwards to the page, which allows selection of the project type and additional options. Finally pressing Finish should cause the wizard to generate the project from the template files as appropriate, and open the new project ready to be modified as required by the user. Finish The structure of the wizards is moderately complex but once I got to grips with how the different pieces fit together it became slightly easier to make changes. The main problem was the paucity of documentation for the Express versions; I report this as a fact, not a criticism, as I still think the Express editions are excellent products. If you create a syntax error or misname a variable within the HTML or JavaScript, then the wizard is likely to fail with a very cryptic message box. So you know there is something wrong but there is not likely to be anything as useful as a script line number to help you - good luck! There are probably more things to learn about this process, but I'm more interested in getting a quick working baseline program to solve whatever problem I am working on. This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL) Richard MacCutchan wrote:downvoted Richard MacCutchan wrote:needs to be kicked Richard MacCutchan wrote:needs to be kicked Lazy<Dog> Param="WIZARD_ID = 103" The WIZARD_ID field should be unique among all the wizards registered on the system. Ahmed Charfeddine wrote:After the Wizard is completed, how can one distribute it ? coder112 wrote:it was a brilliant insight to use a 'solution' to implement this, though it was not something I caught on to immediately - it might be worthwhile to make this a bit more 'obvious' in the text. coder112 wrote:Also the fact that it seems one can use the 'Debug' version only. Unless there is something I missed in this respect - though, I thought I'd read the article several times rather carefully. coder112 wrote:Also, I am curious why I can't find the commands to do the copying in the 'Solution Explorer' under the Project Properties -> Build Events and only in the .vcproj file. Properties'? .vcproj coder112 wrote:Since you've automated the creation of a new wizard, another potential 'improvement' would be to also automate 'project clean' to remove any failed attempts, so one can start all over with a 'new and improved' version. Richard MacCutchan wrote: coder112 wrote: it was a brilliant insight to use a 'solution' to implement this, though it was not something I caught on to immediately - it might be worthwhile to make this a bit more 'obvious' in the text. Not sure I understand what you mean here. The title says this is a "Custom Wizard" so creating the wizard has to be via a solution. Richard MacCutchan wrote: coder112 wrote: Also the fact that it seems one can use the 'Debug' version only. Unless there is something I missed in this respect - though, I thought I'd read the article several times rather carefully. Again I don't understand your question. The wizard should produce a sample solution which can create both a Debug and Release version of your project. Richard MacCutchan wrote: coder112 wrote: Also, I am curious why I can't find the commands to do the copying in the 'Solution Explorer' under the Project Properties -> Build Events and only in the .vcproj file. These are two separate issues. Project Build events are extra events run during the build process at particular intervals and are not required by this project. The actual copy statements (aka build command) exists for each individual file, right click on any file and select Properties. This is necessitated by the VC++ Express project model. Richard MacCutchan wrote:'? No, you just change the source file; the resulting modified file will still require the same copy command as before. If you add a new source file entry to the project then you must add the correct build statements (use copy and paste) via the properties for the new file. .. Richard MacCutchan wrote: coder112 wrote: Since you've automated the creation of a new wizard, another potential 'improvement' would be to also automate 'project clean' to remove any failed attempts, so one can start all over with a 'new and improved' version. If you mean cleaning out the wizard files from the system, the clean function already does that. coder112 wrote:When I load the CustomWizard .sln file in MSVC 2008 Express, and select the 'Release' version it tries to compile the template files. coder112 wrote:Yes it does clean out the files, though it leaves the directories - which is what fooled me initially. General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/43653/Visual-C-Express-Custom-Wizard
CC-MAIN-2014-52
refinedweb
2,885
56.29
Reference Index Table of Contents sem_init, sem_wait, sem_trywait, sem_post, sem_getvalue, sem_destroy - operations on semaphores #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); int sem_wait(sem_t * sem); int sem_timedwait(sem_t * sem, const struct timespec *abstime); int sem_trywait(sem_t * sem); int sem_post(sem_t * sem); int sem_post_multiple(sem_t * sem, int number); int sem_getvalue(sem_t * sem, int * sval); int sem_destroy(sem_t * sem);). Pthreads-w32 currently does not support process-shared semaphores, thus sem_init always returns with error EPERM if pshared is not zero. sem_wait atomically decrements sem's count if it is greater than 0 and returns immediately or it suspends the calling thread until it can resume following a call to sem_post or sem_post_multiple. sem_timedwait atomically decrements sem's count if it is greater than 0 and returns immediately, or it suspends the calling thread. If abstime time arrives before the thread can resume following a call to sem_post or sem_post_multiple, then sem_timedwait returns with a return code of -1 after having set errno to ETIMEDOUT. If the call can return without suspending then abstime is not checked. sem_trywait atomically decrements sem's count if it is greater than 0 and returns immediately, or it returns immediately with a return code of -1 after having set errno to EAGAIN. sem_trywait never blocks. sem_post either releases one thread if there are any waiting on sem, or it atomically increments sem's count. sem_post_multiple either releases multiple threads if there are any waiting on sem and/or it atomically increases sem's count. If there are currently n waiters, where n the largest number less than or equal to number, then n waiters are released and sem's count is incremented by number minus n. sem_getvalue stores in the location pointed to by sval the current count of the semaphore sem. In the Pthreads-w32 implementation: if the value returned in sval is greater than or equal to 0 it was the sem's count at some point during the call to sem_getvalue. If the value returned in sval is less than 0 then it's absolute value represents the number of threads waiting on sem at some point during the call to sem_getvalue. POSIX does not require an implementation of sem_getvalue to return a value in sval that is less than 0, but if it does then it's absolute value must represent the number of waiters. sem_destroy destroys a semaphore object, freeing the resources it might hold. No threads should be waiting on the semaphore at the time sem_destroy is called. sem_wait and sem_timedwait are cancellation points. These routines are not async-cancel safe. All semaphore functions return 0 on success, or -1 on error in which case they write an error code in errno. The sem_init function sets errno to the following codes on error: pshared is not zero The sem_timedwait function sets errno to the following error code on error: if abstime arrives before the waiting thread can resume following a call to sem_post or sem_post_multiple. The sem_trywait function sets errno to the following error code on error: if the semaphore count is currently 0 The sem_post and sem_post_multiple functions set errno to the following error code on error: The sem_destroy function sets errno to the following error code on error: Xavier Leroy <Xavier.Leroy@inria.fr> Modified by Ross Johnson for use with Pthreads-w32. pthread_mutex_init(3) , pthread_cond_init(3) , pthread_cancel(3) . Table of Contents
http://www.sourceware.org/pthreads-win32/manual/sem_init.html
CC-MAIN-2014-49
refinedweb
568
50.46
Red Hat Bugzilla – Bug 126252 Printconf doesn't allow queue names that start with numbers Last modified: 2007-11-30 17:10:44 EST Description of problem: Printconf chokes when it encounters any queue name that starts with a number. While it is not possible to create such queues through printtool directly, this can happen if the user does it through the CUPS interface, or through a third-party program. Version-Release number of selected component (if applicable): Has been happening since at least Redhat 9. How reproducible: Consistent Steps to Reproduce: 1. Create a queue with a name that starts with a digit (like 123printer), through the CUPS web interface. 2. Run printtool 3. Witness the stack dump. Actual results: printtool is unusable until the queue is removed manually. Expected results: No crash should occur. It is also unnecessary to restrict the queue names this way, as numeric queue names are perfectly well supported by both CUPS and LPRng. Here is a typical Python stack dump : Traceback (most recent call last): File "/usr/sbin/printconf", line 9, in ? import queueTree File "/usr/share/printconf/util/queueTree.py", line 1235, in ? queueTree() File "/usr/share/printconf/util/queueTree.py", line 140, in __init__ cups_import.import_cups_queues () File "/usr/share/printconf/util/cups_import.py", line 183, in import_cups_queues line[i][1] == "D") File "/usr/share/printconf/util/cups_import.py", line 132, in _discover_queue construct_queue (type_space, data_dict, driver_tuple) File "/usr/share/printconf/util/printconf_conf.py", line 879, in construct_queue queue = queue_edit.dynamic_queue_ctx.data["/printconf/print_queues"].addData(AdmListType, queue_name) ValueError: "105brightq" is an invalid name. This is an alchemist limitation. Worked around in Fedora development.
https://bugzilla.redhat.com/show_bug.cgi?id=126252
CC-MAIN-2017-30
refinedweb
271
52.46
> Then there is another problem (which also exists in the current > design): does Xen need to emulate NVDIMM _DSM for dom0? Take the _DSM > that access label storage area (for namespace) for example: No. And it really can't as each vendors _DSM is different - and there is no ACPI AML interpreter inside Xen hypervisor. > > The way Linux reserving space on pmem mode NVDIMM is to leave the > reserved space at the beginning of pmem mode NVDIMM and create a pmem > namespace which starts from the end of the reserved space. Because the > reservation information is written in the namespace in the NVDIMM > label storage area, every OS that follows the namespace spec would not > mistakenly write files in the reserved area. I prefer to the same way > if Xen is going to do the reservation. We definitely don't want dom0 > to break the label storage area, so Xen seemingly needs to emulate the > corresponding _DSM functions for dom0? If so, which part, the > hypervisor or the toolstack, should do the emulation? But we do not want Xen to do the reservation. The control guest (Dom0) is the one that will mount the NVDIMM, and extract the system ranges from the files on the NVDIMM - and glue them to a guest. It is also the job of Dom0 to do the actually partition the NVDIMM as fit. Actually let me step back. It is the job of the guest who has the full NVDIMM in it. At bootup it is Dom0 - but you can very well 'unplug' the NVDIMM from Dom0 and assign it wholesale to a guest. Granted at that point the _DSM operations have to go through QEMU which ends up calling the dom0 ioctls on PMEM to do the operation (like getting the SMART data). > >.
https://lists.xenproject.org/archives/html/xen-devel/2016-03/msg02300.html
CC-MAIN-2018-26
refinedweb
299
68.3
random method in setter method in C# I am new to C#. I am trying to figure how to use the random method inside a setter. This is how my code looks right now: public class star_wars_figures { private string charactor; private int bounty; public star_wars_figures(string charactor) { Charactor = charactor; } public string Charactor { get { return charactor.ToUpper(); } set { if (value == "Han Solo" || value == "Leia") { charactor = value; } else charactor = "INCORRECT CHARACTOR!!!!"; } } public int Bounty { get { return bounty; } set { Random rnd = new Random(); bounty = rnd.Next(1, 10); bounty = value; } } } In my main I insatiate with the following: star_wars_figures sw1 = new star_wars_figures("Han Solo"); Console.WriteLine($"Character is: {sw1.Charactor}"); Console.WriteLine($"Money: {sw1.Bounty}"); I am trying to generate a random int number in the setter method of the bounty attribute. Its just returning 0. What have I missed out here? -thanks Because you don't set the bounty in object constructor. You use only getter for bounty property. Try to use: public star_wars_figures(string charactor) { Charactor = charactor; Random rnd = new Random(); bounty = rnd.Next(1, 10); } C# Property Examples, A property is a method that gets or sets a value. C# program that uses private setter in property using System; class Example { public Id = new Random(). C# | Random.Next () Method The Next () Method of System.Random class in C# is used to get a random integer number. This method can be overloaded by passing different parameters to it as follows: "value" (your last assignment) is the value received while calling the setter. Currently "bounty" is set twice : firstly but your random generator result, and immediately after with "value". Therefore the first value set is lost and not usable anywhere. You could just remove "bounty = value;" to have it working. Nevertheless, a property setter is not the right place to do what you seem to want, I think you have fundamental misunderstanding of how to work with properties and backing fields. Beginning Object-Oriented Programming with C#, passCount property method has a set statement block. (In some states, if you had a setter for the odometer property, you might find yourself a 2. Generate a random integer number that falls within the range of 1 to DECKSIZE, inclusively. The NextDouble() Method of System.Random class in C# is used to return a random floating-point number which is greater than or equal to 0.0, and less than 1.0. Syntax: public virtual double NextDouble(); Return Value: This method returns a double-precision floating point number which is greater than or equal to 0.0, and less than 1.0. The random number generator needs to be initialized once only, as it used the CPU ticks at the time of initialization for the random number seed. Best practice is to include it into a private static field. Change your code to public class StarWarsFigures { // Define one instance of the random number generator static readonly Random rng = new Random(); ... } Now as far as using it inside a setter, it is bad design, as the purpose of the setter is to set a property to a specified value. If you want to set the property to a random number initially, then do it at the constructor. public StarWarsFigures(string character) { this.Character = character; this.Bounty = rng.Next(1, 10); } public int Bounty { get { return bounty; } set { bounty = value; } } Finally, there are some issues with the character string. I assume you want to store it as upper case only, since the getter converts it as such. It is better to do the conversion once at the setter instead. Additionally, when comparing strings, always use .Equals() instead of == as they mean different things for strings. Finally, you need to convert the set value to upper case also before comparing, or use the StringComparison.OrdinalIgnoreCase option. public string Character { get { return character; } set { if (value.Equals("Han Solo", StringComparison.OrdinalIgnoreCase) || value.Equals("Leia", StringComparison.OrdinalIgnoreCase)) { character = value.ToUpper(); } else { character = "INCORRECT CHARACTER!!!!"; } } } PS. You might want to fix the typos. Character is the correct spelling, not Charactor. Lesson 15.1 – Getting random numbers for the game – ScottLilly.com, This game, like many games, needs to get random numbers. Step 3: Decide which method you want to use, and paste the code below into the RandomNumberGenerator class. All lessons: Learn C# by Building a Simple RPG Index It doesn't have a getter and/or setter, which is what would make it a property. Replace getter and setter methods with corresponding properties. The property's name should be the same as its originating methods, but without "Get" and "Set". For example, if the method had a name int GetSize(), then the property should have type int and name Size. Leave all access modifiers the same: private setters should stay private Java: Help with getters and setters in random number program , Java: Help with getters and setters in random number program This is why I chose to set only the max for the random number generator with the I always were learning using the traditional school method, going to an Exam, studying alot When new to C#, it may be tempting to just give all properties both getters and setters, which unless they explicitly need to be mutable, is bad practice. “Tell an object what to do, don’t ask it for information and manipulate it yourself”. property() function in Python, The property() function in Python is used to define properties in the class. Module · Math Module · Statistics Module · Collections Module · Random Module script which defines the person class as having the getter and setter methods. It encapsulates instance attributes and provides a property, same as Java and C#. Returns a random floating-point number between 0.0 and 1.0. using namespace System; // This derived class converts the uniformly distributed random // numbers generated by base.Sample( ) to another distribution. public ref class RandomProportional : Random { // The Sample method generates a GenFu, using an internal database of values or randomly created data. Use GenFu's static methods to new up new objects for testing, design-time data or If your project uses one-parameter setter methods, you can use GenFu too! Phone Windws Live Writer Winnipeg bower c# compiling jQuery jQuery UI node npm open To generate random numbers, use Random class. Create an object − Random r = new Random(); Now, use the Next() method to get random numbers in between a range − r.Next(10,50); The following is the complete code − Example. Live Demo
http://thetopsites.net/article/58219468.shtml
CC-MAIN-2020-34
refinedweb
1,075
56.66
The QPrinter class is a paint device that paints on a printer. More... #include <QPrinter> Inherits QPaintDevice.. QPrinter supports a number of parameters, most of which can be changed by the end user through a print dialog. In general, QPrinter passes these functions onto the underlying QPrintEngine. The most important parameters are: Printing with Qt. This enum type is used to indicate whether QPrinter should print in color or not. This enum type (not to be confused with Orientation) is used to specify each page's orientation. This type interacts with QPrinter::PageS.: With setFullPage(false) (the default), the metrics will be a bit smaller; how much depends on the printer in use.. Used to specify the print range selection option. See also QAbstractPrintDialog::PrintRange. This enum describes the mode the printer should work in. It basically presets a certain resolution and working mode. Creates a new printer object with the given mode. Destroys the printer object and frees any allocated resources. If the printer is destroyed while a print job is in progress this may or may not affect the print job.. Returns true if collation is turned on when multiple copies is selected. Returns false if it is turned off when multiple copies is selected. This function was introduced in Qt 4.1. See also setCollateCopies(). Returns the current color mode. See also setColorMode(). Returns the name of the application that created the document. See also setCreator(). Returns the document name. See also setDocName(). Returns true if double side printing is enabled. Currently this option is only supported on X11. This function was introduced in Qt 4.2. See also setDoubleSidedPrinting(). Returns true if font embedding is enabled. Currently this option is only supported on X11. This function was introduced in Qt 4.1. See also setFontEmbeddingEnabled(). Returns the from-page setting. The default value is 0. If fromPage() and toPage() both return 0 this signifies 'print the whole document'. PageSize. Tells the printer to eject the current page and to continue printing on a new page. Returns true if this was successful; otherwise returns false. Returns the number of copies to be printed. The default value is 1. On Windows, Mac OS X and X11 systems that support CUPS, this will always return 1 as these operating systems can internally handle the number of copies. On X11, this value will return the number of times the application is required to print in order to match the number specified in the printer setup dialog. This has been done since some printer drivers are not capable of buffering up the copies and in those cases the application must make an explicit call to the print code for each copy. See also setNumCopies(). Returns the orientation setting. This is driver-dependent, but is usually QPrinter::Portrait. See also setOrientation(). Returns the name of the output file. By default, this is an empty string (indicating that the printer shouldn't print to file). See also setOutputFileName().. See also pageSize(). Returns the printer page size. The default value is driver-dependent. See also setPageSize(), pageRect(), and paperRect(). Returns the paint engine used by the printer. Reimplemented from QPaintDevice. Returns the paper's rectangle; this is usually larger than the pageRect(). See also pageRect(). Returns the printer's paper source. This is Manual or a printer tray or paper cassette. See also setPaperSource().. See also colorMode(). Sets the name of the application that created the document to creator. This function is only applicable to the X11 version of Qt. If no creator name is specified, the creator will be set to "Qt" followed by some version number. See also creator(). Sets the document name to name. See also docName(). Enables double sided printing if doubleSided is true; otherwise disables it. Currently this option is only supported on X11. This function was introduced in Qt 4.2. See also doubleSidedPrint(). Enabled or disables font embedding depending on enable. Currently this option is only supported on X11. This function was introduced in Qt 4.1. See also fontEmbeddingEnabled(). Sets the from-page and to-page settings to from and to respectively. The from-page and to-page settings specify what pages to print. If from and to both return 0 this signifies 'print the whole document'. This function is useful mostly to set a default value that the user can override in the print dialog when you call setup(). This function was introduced in Qt 4.1. See also fromPage() and toPage(). PageSize. It may not be possible to print on the entire physical page because of the printer's margins, so the application must account for the margins itself. See also fullPage(), setPageSize(), width(), height(), and Printing with Qt. Sets the number of copies to be printed to numCopies. The printer driver reads this setting and prints the specified number of copies. See also numCopies(). Sets the print orientation to orientation. The orientation can be either QPrinter::Portrait or QPrinter::Landscape. The printer driver reads this setting and prints using the specified orientation. On Windows and Mac OS X, this option can be changed while printing and will take effect from the next call to newPage().. QPrinter will use().. See also pageOrder(). Sets the printer page size to newPageSize if that size is supported. The result if undefined if newPageSize is not supported. The default page size is driver-dependent. This function is useful mostly for setting a default value that the user can override in the print dialog. See also pageSize(), PageSize, setFullPage(), setResolution(), pageRect(), and paperRect().().. Warning: This function is not available on Windows. See also printerSelectionOption().PageSize(). Sets the page size to be used by the printer under Windows to pageSize. Warning: This function is not portable so you may prefer to use setPageSize() instead. See also winPageSize(). the to-page setting. The default value is 0. If fromPage() and toPage() both return 0 this signifies 'print the whole document'. pageSize() instead. See also setWinPageSize(). Use QAbstractPrintDialog::PrintDialogOption instead. Use printerState() == QPrinter::Aborted instead. Returns true if the printer is set up to collate copies of printed documents; otherwise returns false. Use QPrintDialog::isOptionEnabled(QPrintDialog::PrintCollateCopies) instead. See also setCollateCopiesEnabled() and collateCopies(). Use QPrintDialog instead. Sets *top, *left, *bottom, *right to be the top, left, bottom, and right margins. This function has been superseded by paperRect() and pageRect(). Use paperRect().top() - pageRect().top() for the top margin, paperRect().left() - pageRect().left() for the left margin, paperRect().bottom() - pageRect().bottom() for the bottom margin, and papaerRect().right() - pageRect().right() for the right margin. For example, if you have code like uint rightMargin; uint bottomMargin; printer->margins(0, 0, &bottomMargin, &rightMargin); you can rewrite it as int rightMargin = printer->paperRect().right() - printer->pageRect().right(); int bottomMargin = printer->paperRect().bottom() - printer->pageRect().bottom(); This is an overloaded member function, provided for convenience. Returns a QSize containing the left margin and the top margin. This function has been superseded by paperRect() and pageRect(). Use paperRect().left() - pageRect().left() for the left margin, and paperRect().top() - pageRect().top() for the top margin. For example, if you have code like QSize margins = printer->margins(); int leftMargin = margins.width(); int topMargin = margins.height(); you can rewrite it as int leftMargin = printer->paperRect().left() - printer->pageRect().left(); int topMargin = printer->paperRect().top() - printer->pageRect().top(); Use QPrintDialog::maxPage() instead. Use QPrintDialog::minPage() instead. Returns true if the output should be written to a file, or false if the output should be sent directly to the printer. The default setting is false. See also setOutputToFile() and setOutputFileName(). Executes a page setup dialog so that the user can configure the type of page used for printing. Returns true if the contents of the dialog are accepted; returns false if the dialog is canceled. Executes a print setup dialog so that the user can configure the printing process. Returns true if the contents of the dialog are accepted; returns false if the dialog is canceled. Use QPrintDialog::addEnabledOption(QPrintDialog::PrintCollateCopies) or QPrintDialog::setEnabledOptions(QPrintDialog::enabledOptions() & ~QPrintDialog::PrintCollateCopies) instead, depending on enable. See also collateCopiesEnabled(). Use QPrintDialog::setMinMax() instead. Use QPrintDialog instead. See also isOptionEnabled(). Specifies whether the output should be written to a file or sent directly to the printer. Will output to a file if enable is true, or will output directly to the printer if enable is false. See also outputToFile() and setOutputFileName(). Use QPrintDialog instead. For example, if you have code like if (printer->setup(parent)) ... you can rewrite it as QPrintDialog dialog(printer, parent); if (dialog.exec()) ...
http://doc.trolltech.com/4.2/qprinter.html
crawl-002
refinedweb
1,419
53.98
First solution in Clear category for House Password by reviewboy # migrated from python 2.7 def checkio(data): # password strength criteria: minLength = 10 # must be 10+ characters, # must be alphanumeric (no special chars) Digit = 0 # must have at least one digit LC = 0 # must have at least one lowercase letter UC = 0 # must have at least one uppercase letter # parse password for character type counts (0 = False) for c in data: UC +=1 if c.islower() else UC LC +=1 if c.isupper() else LC Digit +=1 if c.isdigit() else Digit strength = data.isalnum() and Digit and LC and UC and len(data) >= minLength return bool(strength)" Sept. 20, 2014 Forum Price Global Activity ClassRoom Manager Leaderboard Coding games Python programming for beginners
https://py.checkio.org/mission/house-password/publications/reviewboy/python-3/first/share/969b8bf151fec0d8f1d550b1d7cb9141/
CC-MAIN-2020-45
refinedweb
124
63.09
JTabbedPane tab components First, thank you for adding the "arbitrary tab components" feature to JTabbedPane. Finally we'll have a good answer for all the people who ask in the forums how to add close buttons to their tabs! I've been playing with this feature for several days now, and I'd like to share some issues I've encountered. I'll submit bug reports if they're called for, but I want to get some feedback first, and also discover whether these issues are already being worked on. The sample code below demonstrates what I'm talking about. Insets The UI delegate uses an Insets object to position the tab's contents within the tab. This margin works well enough for the icon+text label that JTabbedPane has always used, but it isn't necessarily right for an arbitrary tab component. For example, the close buttons in the sample program should be right near the edges of the tabs, but the default Insets adds an unsightly gap--in the case of Metal L&F, a whopping nine pixels' worth. It also leaves no gap at all between the top of the button and the tab's top border. These defaults can be overridden easily enough, as shown in the main() method below, but that's no solution: they would need to be overridden differently depending on both the L&F and the tab positions. It seems to me the UI delegate should generate a minimal Insets for use with user-supplied tab components, taking into account any L&F-specific issues like the extra six pixels needed at whichever end has the corner notch under Metal/Ocean. Opaque components The javadoc should caution users to always use transparent tab components. I originally used a JPanel as the basis of my tab components, but the selected tab looked really screwed up until I added a call to setOpaque(false). (The default FlowLayout also adds a lot of unwanted padding; Box seems to be the ideal container for tab components.) Focus When I first run the sample program, there are no focus indicators visible anywhere, pressing the Tab key or the spacebar has no effect, and traversing the tabs with Ctrl-Tab (Windows) or the arrow keys (Metal) doesn't work. If I close a tab by clicking on its close button, one of the remaining close buttons gets the keyboard focus. Thereafter the tab traversal keys work correctly, and pressing the Tab key cycles the focus through all the remaining close buttons plus the selected tab. If I uncomment the "setFocusable" line (which should only affect the buttons), keyboard focus and tab traversal never work at all. Actually, the issue doesn't seem to be specific to tab components, because if I comment out the "setTabComponentAt" line, they still don't work (but they work if I run the program under jdk 1.5). Is this a bug, or am I doing something wrong? Finally, I can't help wondering why JTabbedPane didn't just use a JLabel to render the tabs from the beginning? It seems like it would have made things so much easier... import java.awt.*;<br /> import java.awt.event.*;<br /> import javax.swing.*;</p> <p>public class Test<br /> {<br /> public Test()<br /> {<br /> JTabbedPane tp = new JTabbedPane();</p> <p> String[] fillers = new String[] { "One", "Two", "Three", "Four" };<br /> for (String str : fillers)<br /> {<br /> JLabel comp = new JLabel("" + str + "");<br /> comp.setHorizontalAlignment(JLabel.CENTER);<br /> comp.setForeground(Color.BLUE);<br /> tp.add(str, comp);<br /> tp.setTabComponentAt(tp.indexOfComponent(comp),<br /> createTabComponent(tp, comp, str));<br /> }</p> <p> JFrame frame = new JFrame("JTabbedPane Test");<br /> frame.add(tp);<br /> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br /> frame.setSize(new Dimension(400, 150));<br /> frame.setLocationRelativeTo(null);<br /> frame.setVisible(true);<br /> }</p> <p> private JComponent createTabComponent(final JTabbedPane tp,<br /> final Component comp,<br /> String title)<br /> {<br /> JButton btn = new JButton("X");<br /> // btn.setFocusable(false);<br /> btn.setForeground(Color.RED);<br /> btn.setMargin(new Insets(0, 2, 0, 1));<br /> btn.addActionListener(<br /> new ActionListener()<br /> {<br /> public void actionPerformed(ActionEvent evt)<br /> {<br /> tp.remove(comp);<br /> }<br /> }<br /> );</p> <p> JComponent tabComp = Box.createHorizontalBox();<br /> tabComp.add(new JLabel(title));<br /> tabComp.add(Box.createHorizontalStrut(6));<br /> tabComp.add(btn);</p> <p> return tabComp;<br /> }</p> <p> public static void main(String[] args)<br /> {<br /> /* Insets for Metal/Ocean L&F - default is (0, 9, 1, 9) */<br /> UIManager.put("TabbedPane.tabInsets", new Insets(1, 6, 1, 1));</p> <p>// try<br /> // {<br /> // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());<br /> // }<br /> // catch (Exception ex)<br /> // {<br /> // ex.printStackTrace();<br /> // }<br /> // /* Insets for Windows (XP) L&F - default is (0, 4, 1, 4) */<br /> // UIManager.put("TabbedPane.tabInsets", new Insets(1, 4, 1, 1));</p> <p> new Test();<br /> }</p> <p>} Related to tabbed panes could we get Tim's tab component pulled out of Netbeans and officially put in the JRE? The code is written. It just needs a little cleanup. Keep JTabbedPane, just give me a model driven alternative. I pulled it out once already... However, the Netbeans code has moved forward again to the point Tim's build scripts don't work.
https://www.java.net/node/644137
CC-MAIN-2014-10
refinedweb
871
54.32
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). On 14/03/2017 at 10:16, xxxxxxxx wrote: Hi everyone, I'm experiencing some strange behaviour where polygons generated from a Python generator (this can also be replicated in an objectData plugin context) are disappearing from the viewport. This only occurs when the coordinate of the generator object cannot be seen in the viewport. This applies for Polygons but not primitives. Here's an example: import c4d from c4d import utils as u, Matrix as m, Vector as v w = 200 h = 200 off = v(1000,0,0) def main() : pol = c4d.BaseObject(c4d.Opolygon) pol.ResizeObject(4,1) pol.SetPoint(0,v(-w,0,-h)+off) pol.SetPoint(1,v( w,0,-h)+off) pol.SetPoint(2,v( w,0, h)+off) pol.SetPoint(3,v(-w,0, h)+off) pol.SetPolygon(0,c4d.CPolygon(0,1,2,3)) null = c4d.BaseObject(c4d.Onull) null.SetName("PIP - Group") pol.InsertUnderLast(null) cube = c4d.BaseObject(c4d.Ocube) cube.SetAbsPos(-off) cube.InsertUnderLast(null) return null In this case, the origin is the vector where the Python Generator is located in space. If I move the camera so that the Polygon is visible but the origin is not, the polygon disappears. If I have the primitive cube in shot but not the origin, the cube still displays properly. Can anyone shed any light on this? Is there a camera culling feature I don't know about or something Thanks Adam On 15/03/2017 at 02:53, xxxxxxxx wrote: Hi Adam, like shown in the Py-RoundedTube example you need to send a MSG_UPDATE ( pol.Message (c4d.MSG_UPDATE) ) to the PolygonObject after its construction, so it can update its bounding box. Unfortunately this is mentioned in documentation for the PointObject, only. Something we definitely should improve. On 15/03/2017 at 03:49, xxxxxxxx wrote: Thanks! I'm really glad it was that simple.
https://plugincafe.maxon.net/topic/10015/13481_python-generator--culling-issue
CC-MAIN-2021-31
refinedweb
357
58.99
Refactoring Substitute Algorithm Problem So you want to replace an existing algorithm with a new one? Solution Replace the body of the method that implements the algorithm with a new algorithm. String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals("Don")){ return "Don"; } if (people[i].equals("John")){ return "John"; } if (people[i].equals("Kent")){ return "Kent"; } } return ""; } String foundPerson(String[] people){ List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (int i=0; i < people.length; i++) { if (candidates.contains(people[i])) { return people[i]; } } return ""; } string FoundPerson(string[] people) { for (int i = 0; i < people.Length; i++) { if (people[i].Equals("Don")) { return "Don"; } if (people[i].Equals("John")) { return "John"; } if (people[i].Equals("Kent")) { return "Kent"; } } return String.Empty; } string FoundPerson(string[] people) { List<string> candidates = new List<string>() {"Don", "John", "Kent"}; for (int i = 0; i < people.Length; i++) { if (candidates.Contains(people[i])) { return people[i]; } } return String.Empty; } function foundPerson(array $people){ for ($i = 0; $i < count($people); $i++) { if ($people[$i] === "Don") { return "Don"; } if ($people[$i] === "John") { return "John"; } if ($people[$i] === "Kent") { return "Kent"; } } return ""; } function foundPerson(array $people){ foreach (["Don", "John", "Kent"] as $needle) { $id = array_search($needle, $people, true); if ($id !== false) { return $people[$id]; } } return ""; } def foundPerson(people): for i in range(len(people)): if people[i] == "Don": return "Don" if people[i] == "John": return "John" if people[i] == "Kent": return "Kent" return "" def foundPerson(people): candidates = ["Don", "John", "Kent"] for i in range(len(people)): if people[i] in candidates: return people[i] return "" foundPerson(people: string[]): string{ for (let person of people) { if (person.equals("Don")){ return "Don"; } if (person.equals("John")){ return "John"; } if (person.equals("Kent")){ return "Kent"; } } return ""; } foundPerson(people: string[]): string{ let candidates = ["Don", "John", "Kent"]; for (let person of people) { if (candidates.contains(person)) { return person; } } return ""; } Why Refactor Gradual refactoring isn’t the only method for improving a program. Sometimes a method is so cluttered with issues that it’s easier to tear down the method and start fresh. And perhaps you have found an algorithm that’s much simpler and more efficient. If this is the case, you should simply replace the old algorithm with the new one. As time goes on, your algorithm may be incorporated into a well-known library or framework and you want to get rid of your independent implementation, in order to simplify maintenance. The requirements for your program may change so heavily that your existing algorithm can’t be salvaged for the task. How to Refactor Make sure that you have simplified the existing algorithm as much as possible. Move unimportant code to other methods using Extract Method. The fewer moving parts in your algorithm, the easier it’s to replace. Create your new algorithm in a new method. Replace the old algorithm with the new one and start testing the program. If the results don’t match, return to the old implementation and compare the results. Identify the causes of the discrepancy. While the cause is often an error in the old algorithm, it’s more likely due to something not working in the new one. When all tests are successfully completed, delete the old algorithm for good!
https://refactoring.guru/substitute-algorithm
CC-MAIN-2019-04
refinedweb
544
58.69
On 25 Apr 2002, Ken Kinder wrote: > The reason I ask is, I don't think threading is compiled into this > instance of python. However, I can use the debugger on individual file > (no CGI) just fine... So I didn't think of threading to be the > problem. I'm not 100% sure but I think mod_python is threaded by default. To clarify the source of the calls, you could add something like this to wingdbstub.py to see more clearly how it is being imported: import thread print "****** THREAD", thread.get_ident() import traceback traceback.print_stack() I have heard of at least one other user that uses Wing with mod_python but they made it sound like it just worked, so I may indeed be barking up the wrong tree. Other stuff to try: 1) You might also try moving the line in wingdbstub.py that says: os.environ['WINGDB_ACTIVE'] = "1" To the start of that block (just after the check of this env). This may block the second attempt at starting the debug machinery, which I believe might be happening before the first start is complete. 2) It's also possible mod_python is messing with os.environ (seems fairly likely given how CGI works)... so you may need to add other code of some type to avoid the second invocation. 3) Another approach would be moving the 'import wingdbstub' closer to the code you want to debug... this may work around the problem. - Stephan
http://wingware.com/pipermail/wingide-users/2002-April/001068.html
CC-MAIN-2014-42
refinedweb
244
74.49
Okay... Centigrade = 5/9(FahrenheitString - 32); hint: Computers don't know to multiply automatically... parenthesis help with order of operations... and Where does temp go; can't just slam a string in a numeric field... JOptionPane.showMessageDialog (null, "The temperature in CENTIGRADES is "+ C=5/9(Fahrenheit-32") Hint: Watch your quotes and parentheses... And why not use the variable that you set up so nicely... Don't want to give you the answer, just point you in the right direction. Let me know if you need more help. :) Regarding your errors Mike, The errors in the two statements are the same errors. You don't learn as much if I just tell you the answer, so I'm going to hint at it. The formula C = 5/9(Farenheight-32) is correct math syntax, but is actually a shortcut. I suggest that you read the formula out loud, and figure out what you're saying that isn't written down. I also somewhat expect that you will get an answer of 0 from that formula. It has to do with another difference between doing math on paper and doing it with a computer. Let me know how it goes! -- Leolore Arithmetic in Java Just glancing at the table of contents for your textbook, it does not seem immediately obvious which chapter would explain how math works in Java. I'm guessing chapter 2 on using data within a program? In Java (and most other programming languages) the 4 basic operators for addition, subtraction, multiplication, and division are +, -, *, and /, respectively. You must always explicitly include the multiply operator to multiply 2 terms. In algebra, you learned to write "x times y" as xy or (x)(y). In programming, you must write x*y or (x)*(y). JAVA compilation errors I'm trying to write a script that can convert Fahrenheit to Centigrade, but I can't seem to resolve my last few errors. import javax.swing.JOptionPane; public class TEST { public static void main(String[] args) { String FahrenheitString; double Fahrenheit; double Centigrade; FahrenheitString = JOptionPane.showInputDialog(null,"Enter the Temperature in Fahrenheit ", "Temperature in FAHRENHEIT", JOptionPane.INFORMATION_MESSAGE); Temp = Double.parseDouble(FahrenheitString); Centigrade = 5/9(FahrenheitString - 32); JOptionPane.showMessageDialog (null, "The temperature in CENTIGRADES is + C=5/9(Fahrenheit-32"); System.exit(0); } } Seems I have 3 errors due to "Centigrade = 5/9(FahrenheitString - 32);" and 3 due to "JOptionPane.showMessageDialog (null, "The temperature in CENTIGRADES is "+ C=5/9(Fahrenheit-32"); I just can't figure it out. Any guidance will be GREATLY appreciated. This conversation is currently closed to new comments.
https://www.techrepublic.com/forums/discussions/java-compilation-errors/
CC-MAIN-2018-43
refinedweb
431
58.58
I was delighted to receive not just one but two responses to my last article, see the preceding articles. Before I go any further let me respond to the substance of these items. The introduction of exceptions into C++ raises a number of design issues and it has taken several years for the best C++ programmers to refine their understanding of their correct use. The concept of an exception specification caused considerable trouble. It is my understanding that the UK originally wanted them removed because they could not be used for static checking of code. That left the problem that they required a runtime feature to support them. While in the strictest terms this is correct, exception specifications provide a number of positive benefits. While complete static checking cannot be provided, some static checking is possible. For example: void fn() throw() { Mytype * ptr = new Mytype; // rest of function } Can be checked. It does not catch the bad_alloc exception that new can produce and so is clearly making a promise that cannot be kept. Any halfway reasonable compiler should raise an objection to such code. The second thing, that exception specifiers provide, is a statement of intent for the benefit of other programmers. It is a condition applied to the function, and like all other features of a declaration it provides a constraint that users can (or should be able to) rely on. Once I decide, as part of my low-level design, that a function does not allow exceptions to leak it is a commitment that I must abide by. Like the return type, a throw specifier is part of the signature of a function that cannot be overloaded. Readers of the latest edition of 'The C++ Programming Language' will know that there are some clever fixes that can be applied to handle functions that are not supposed to throw exceptions by providing special versions of the handler for 'unexpected', but I will leave that to experts. Whether read functions should or should not have an empty exception specifier is a class design decision, however the logic of Detlef's letter would be that we should never use exception specifiers because they commit us for all time to a specific policy with regards to a function. I find this too negative. So, let me explore some options. The first is to provide overloading via an extra dummy parameter. For example, suppose we declare a global enum type: enum CanThrow {canThrow}; Now suitable pairs of functions can co-exist: string const & getName() const throw(); string const & getName(CanThrow) const; This empowers the user of the Customer class to write either: cout << customer.getName(); or cout << customer.getName(canThrow); depending on whether the user wants to handle exceptions or not. That means that the version with an empty exception specifier must handle exceptions internally and provide some dummy return if no genuine value is available. The definition of the 'throwing' version should use the anonymous parameter facility to handle the CanThrow parameter because there is no practical use of the parameter in the body of the function. The parameter is purely to provide overloading, and the type name and value are chosen to alert the user to the need to handle exceptions. The second option is to have a specific exception type as the only one that can be thrown by the function. Something along the lines of: enum NoName{noName}; string const & getName() const throw(NoName); and the definition would be: string const & getName() const throw(NoName) { try { // body of function } catch (…) { throw noName; } } Of course there could be many more catch clauses that handled individual problems but each would terminate with either a return of some string or with throw(noName). Programmers should know which exceptions they may have to handle. Until library designers get in the habit of providing exception specifiers, programmers must assume that all exceptions may need handling. We can argue about the merits of different strategies, but pretending that we need do nothing isn't a professional option. Like too many things however, exception specifiers are going to be ignored by most authors of books because they will seem like just another complication. While I agree with Detlef that it is a (low-level) design decision as to what exception specifier should be attached to ordinary member functions I completely disagree when it comes to destructors. I think he has misunderstood the purpose of uncaught_ exception(). But I will return to that in a moment. Constructors can and should be able to throw exceptions. If something goes wrong during the process of constructing an object some way is needed to get your program back onto safe ground. The biggest problem was finding a mechanism to handle an exception thrown from some part of a constructor-initialiser list. I believe that this problem actually generated some new syntax so that entire function definitions could be encapsulated in a try block but I have never seen this used. Suffice to say that the exception mechanism is particularly useful for dealing with problems during the process of construction. But what about the other end of an object's life? Suppose that a destructor throws an exception, what am I supposed to do? In general all I will know is that I am handling an exception, no clue that I have an incompletely destroyed object on my hands. For example, suppose that I have some local object that handles a file and a serial port. The destructor is called for the object when the function is cleaning up before returning. Something happens during the process of closing the file that results in an exception, unless that exception is handled locally the serial port is never released. OK that is a bit obvious and the programmer of the destructor should handle that but what if he doesn't? Your program is now unstable and should raise an 'unexpected' exception. I am not going to claim that no destructor should ever, under any circumstances, throw an exception. What I do claim is that if a designer finds it necessary to allow a destructor to throw then the exact nature of the exception must be documented and a full justification for allowing it should be required. In my opinion, destructors should always have exception specifiers. In the overwhelming majority such a specifier should be empty. I believe that writing a destructor without an exception specifier is unprofessional and a sign of incompetence or ignorance. Yes we all forget sometimes, but we should be embarrassed if it happens very often. Now a brief word about 'uncaught_exception'. When we write functions that may be used inside exception handlers we have to consider that possibility and arrange some tolerable behaviour (if possible) when they would normally throw an exception. The purpose of uncaught_exception() is to provide the tool that programmers can use when they have no other viable alternative. This is particularly true of mission critical programs that must not abort. Every effort should be made to ensure that functions used during the process of handling an exception do not throw exceptions. Only in the most unusual circumstances might you tolerate different behaviour from a function depending upon whether it was called during exception handling or otherwise. Such special behaviour during EH would be some compromise (such as letting a resource leak) that was undesirable but less so than aborting the process. I would welcome alternative views on this subject because I currently can see no justification for allowing a destructor licence to throw anything and everything. I am very grateful for Roger Lever's thoughtful commentary on the subject of design. I think one problem is that the term is used in several ways. I think that I ma largely focused on the low-level aspects. To me, design is a matter of deciding what a class (or function) shall do while implementation is a matter of deciding how it shall do it. I consider design to be a matter of deciding what the interfaces of a class shall be. Roger, quite correctly, is taking the broader view that design is a matter of deciding what a class is for. Let me try to elucidate, and Roger can come back next time to correct me as appropriate. What constitutes a 'room' depends upon whose viewpoint you take. An architect has one view, and architectural engineer (responsible for considering such things as the loading on floors, the stresses on walls etc.) has another. The architect might be concerned about the placement of windows, the shape of the room, the location of a fireplace etc. without too much regard as to other rooms adjacent to the one in focus. The architectural engineer has to consider what is adjacent. It is her job to note external walls and the potential for heat loss, the existence of upper floors with the consequential requirements for load bearing walls. One of the UK TV channels has been running a series of programs on design. The second of these was about designing a new toilet for a leading UK manufacturer of bathroom suites. They had commissioned two designers. It became clear during the course of the program that the designers and the company directors meant very different things be a design and design brief. The company was mainly concerned with the external appearance and just wanted a new (but not too new) 'shape'. The designers wanted to consider the function and produce something that better met the needs of male and female users, was easier to keep clean etc. There was another aspect to this in that those actually responsible for production (the 'implementors') had another view - what could practically be produced by the equipment available. Moulds must work, the items must be fired without too much wastage etc. Professional designers should provide design documents for their code. These should be based on an understanding as to what aspects of objects are to be represented. The hotel designer, the builder and the receptionist have very different views as to what is important about a room. In the days before we focused strongly on reuse the context of the application we were writing implicitly defined the design (making it explicit would have been a good thing and much of the abuse of code by cut and paste coding might have been avoided had programmers had a better understanding of the relevance of viewpoint to code design). Now that we increasingly focus on reuse we need to be conscious of reuse at all levels. My view (and I think that intended by Paul) is that of the manager of the hotel. Roger suggests that we should up this a level to that of the manager of a chain of hotels. I think this is an excellent extension and the kind of thing that comes with increased experience of using object-oriented techniques. However I am mainly focusing on low-level design because, no matter how elegant the high-level design, without good low-level design everything falls apart. Look at an ordinary building brick. There is a lot of low-level design involved. For example, the shape is a cuboid whose dimensions are approximately 3:2:1. The dimensions are intended to be exactly 3:2:1 when the thickness of the mortar is taken into account. If you did not know how bricks were used you might be puzzled by the approximations. There seems to be a widely held belief that the default behaviour of providing copy constructors and copy assignment is correct. I reject this. Consider my favourite 'playing card' type. How many Spade Aces should there be in a pack of cards? One, and if you were playing Poker and two Spade Aces turned up you would know someone was cheating. Each card in a back is a unique item in context. It might be possible to duplicate that item but such duplication should be a careful and considered action, not some by-product of a desire to have a second object that was identical to the first. This is even more the case when it comes to assignment. It should be completely meaningless to assign one object to another. I think that object types should never have public copy constructors and copy assignments. Sometimes it may be desirable to provide such functionality privately, or even to other class designers via the protected interface. The existence of a public copy constructor is what distinguishes a value type from and object type. Values may be freely copied, objects should only be cloned. If you do not understand this distinction you do not understand object based/oriented programming. Unfortunately we get very casual about our use of terminology. We often talk about throwing an exception object. We should never do this. We should throw an exception value (remember that exception 'objects' are always copied to the point where they are caught). This looseness does not matter as long as we understand what we mean, sadly many of those listening do not and so get confused. So let me consider my Customer type. Should this be a value or an object type? I think we must be careful about what we mean. There is nothing to prevent us from having multiple but identical objects. Indeed my junk mail shows that many companies are quite happy with having multiple instances of me in their databases. What I am asking is should we allow a 'Customer' to be copied without explicitly choosing to do so? My feeling is that the answer should be 'no'. There is a problem with strictly adhering to the concept of an object and removing publicly available copy constructors: all the STL containers are value based. In other words the STL containers require access to copy constructors. We would expect to be able to produce a customer list, yet to do so we must provide access to a copy constructor. Before we consider possible solutions we must ask ourselves about our concept of a customer and how we expect it to be used. Is 'customer' intended to be a base class? In other words, do we expect to derive from customer? If so we cannot have a simple container of customers because the STL containers do not work well with polymorphic types (unless they all have the same size, which is unlikely). If we want to manage collections of polymorphic objects we must provide a surrogate or handle type, a smart pointer or use a raw pointer. A suitably designed smart pointer (not, PLEASE, auto_ptr, because that was not designed for such use) would be best because it would handle extensions to customer easily (the cost is in designing the smart pointer, anyone offer a smart pointer for container use?) might be best but a well designed surrogate would be good as well. I would not be keen on using raw pointers as they would be responsible for large scale resource leakage. Our collections would have to manage our objects via (smart-)pointers or surrogates which might have public copy constructors. Actually, I am slightly uneasy with the concept of a surrogate with a public copy constructor. On the other hand if you have an essentially non-polymorphic object type (playing cards would be a good example) then we can fix the problem in a different way. Let me give you an example: class PlayingCard { friend vector<PlayingCard>; PlayingCard(PlayingCard const&); void operator =(PlayingCard const &); // rest of class interfaces }; By making vector<PlayingCard> a friend of PlayingCard I have provided it access to the private copy constructor. Of course the only containers you can have will be vectors, perhaps you might want to add: friend list<PlayingCard>; as well. I think that this is a legitimate use for friend. What do you think? I wish that there was a way to provide special access to the protected interface so that I could grant special access rights to third parties without having to go the whole way and give them access to everything. I am never very happy with this term and suspect that it is often misused. I understand that it originated from the idea of basic ice creams to which a selection of extras could be added. In programming terms it seems to refer to a basic class to which various extras can be added by multiple inheritance (Java, I guess, would use interfaces for this purpose). The idea is that these extras are free standing abstract base classes that represent some specific abstraction. In the context of our hotel as a commercial enterprise we have a couple of candidates for 'mixins'. The concept of being hireable is one that applies to much more than rooms and presentation equipment. Complementary with the concept of being hireable is the concept of being billable. Hireable might be provided by something along the lines of: class Hireable { ChargeInfo * rates; public: Hireable(ChargeInfo *lookup = 0) : rates(lookup){} // despite the pointer, // shallow copies work Currency getRate(TimePeriod) throw(Invalid) const; void setRate(ChargeInfo *) throw (); virtual ~Hireable() throw() = 0; }; This class raises a number of issues. The first is that several other ADTs naturally arise and will have to be designed and implemented. Anything that is hireable will have to have some form of rate-table. We will also need some form of time information (hourly, daily, weekly etc.) and something to represent the currency used. I am not providing details of these but have added them to highlight the kind of thing that starts to happen as you try to work in an OO fashion. It would seem that ChargeInfo should be some kind of external data structure that can be accessed with TimePeriod data. I have used a pointer rather than a reference because it seems likely that you might want to replace the rate-table, you will also need to handle the creation of hireable objects even if you do not know what rate-table to use. The nature of ChargeInfo is left for consideration by the designer of that class with the proviso that it should work with the TimePeriod class to generate Currency information. There is another interesting aspect of this class in that it is a user of ChargeInfo but is not responsible for its creation. That means that the raw pointer can be copied by both copy-constructor and copy assignment. It is not always the case that you must provide the copying functions if one or more data element is a pointer. On the other hand this is a risky technique because we are using a pointer to data that is outside the control of the object. Such pointers are always vulnerable to becoming hanging pointers if the object they are pointing to is removed or relocated. The reason for taking this risk is that many objects may need to share a look-up table of rates. Such a table would be subject to amendment and so needs to be unique. There is another option. We can allow each object to hold its own local copy and register this information with the master copy. The functions that change the master copy would then be responsible for notifying the copy-holders. The destructor for the master would then be responsible for notifying all current holders of local copies to reset their pointers either to null or to some substitute. In the long term a technique such as this is preferable and professional class designers should be familiar with the idea and the principles for implementing it. Experience suggests that few are. The reason that an empty destructor has been declared is to provide a hook for making Hireable an abstract base class. Hireable is an abstraction and we do not want free standing instances. What we want to be able to produce is something like: class RentableRoom : public Room, public Hireable { // what ever }; As we think deeper and deeper into this problem we become aware of many other classes that we should work on. For example we will need to consider the payment method (cash, credit card, cheque etc.) This seems a good target for a class hierarchy with an abstract base class PaymentMethod and shallow hierarchy to provide the various options. I think it is because of this requirement to add layers of classes that so many programmers retreat to simple non-reusable solutions. This article is already late and getting rather long. I think it is about time that I looked at some more of Paul's code. This time I am going to look at some of his implementation. #include <iostream.h> #include <string.h> const int maxName = 30; // reserve storage for the static int Customer::customerCount; Customer::Customer( { char temp[maxName]; int size; cout << "Enter customer name: "; cin >> temp; size = strlen(temp); name = new char[size + 1]; strcpy(name, temp); cout << "Enter payee name"; cin >> temp; size = strlen(temp); payee = new char[size + 1]; strcpy(payee, temp); customerCount++; } When we look at the above code we will realise that several poor decisions relate back to his original design. The pollution of the global namespace by maxName (an unfortunate choice of identifier as it is certain to be popular in other code written at the same level of expertise - a good reason for hiding such in a named namespace) can be avoided by recognising that the only code that depends upon this value is the temporary array of char used to capture the data. In such a case the manifest constant should be declared close to its point of use (like immediately before its first use). Of course once we feel comfortable with using string instead of char[] the problem goes away, though might still want to apply some form of validation by restricting the number of characters used. I always feel unhappy with the use of int for the sizes of things. Surely this should either be size_t or unsigned int? The next problem is that no attempt has been made to ensure that the input does not over-write the provided storage, nor has code been provided to handle names that include embedded whitespace. I offer the following re-write (I am focusing on implementation here because writing good implementation code is also important). // select standard library identifiers using std::cin; using std::cout; using std::istream::get; // reserve storage for the static int Customer::customerCount = 0; Customer::Customer() { const int maxNameLength = 30; char temp[maxNameLength]; size_t size; cout << "Enter customer name: "; cin.get(temp, maxNameLength); size = strlen(temp); // clear input buffer while(cin.get()!= '\n'); name = new char[size + 1]; strcpy(name, temp); cout << "Enter payee name"; cin.get(temp, maxNameLength); size = strlen(temp); // clear input buffer while(cin.get()!= '\n'); name = new char[size + 1]; strcpy(payee, temp); customerCount++; } As I wrote this I became very conscious that a large chunk of that code is almost duplicated. That provides a maintenance problem as well as making the function larger than necessary (pragmatically the error rate goes up as function size increases). Consider the following alternative: void initName(char const * prompt, char * & dest) { const int maxNameLength = 30; char temp[maxNameLength]; size_t size; cout << prompt; cin.get(temp, maxNameLength); size = strlen(temp); // clear input buffer while(cin.get()!= '\n'); dest = new char[size + 1]; strcpy(dest, temp); } Customer::Customer() { initName("Customer name: ", name); initName("Payee name)", payee); customerCount++; } Note the type of the second parameter of initName(). This handles a situation that many programmers get wrong. I want to pass a pointer for modification. By passing a reference to a pointer I make it more likely that I will write what I intend. By the way should initName be a private member function? Perhaps it should be a utility function in namespace Harpist, or perhaps there should be a third parameter passing the maximum acceptable length. As I would use string instead of char[] I am not going to worry too much this time around, but this kind of small utility function is a prime candidate for very low-level reuse. Customer::~Customer() { customerCount--; delete name; delete payee; } int Customer::getCustomerCount() { return customerCount; } char* Customer::getName() { return name; } char* Customer::getPayee() { return payee; } Of course these last two functions are badly flawed because they provide write access to private data and hence allows fraudulent changes to the data. We know that the original design was faulty because it failed to qualify these functions as const (read only) and without that qualification we can get the return type wrong. With the qualification the compiler knows that we have just provided illegal write access to instance data. The various uses of const are designed to reinforce each other. However I am just improving the implementation of the original so these two functions should at least become: char const * Customer::getName() { return name; } char const * Customer::getPayee() { return payee; } Well I think that is all I have time for this time. Keep the comments flowing so that we all become better C++ programmers.
https://accu.org/index.php/journals/596
CC-MAIN-2019-22
refinedweb
4,175
60.24
Read nrrd files efficiently from parallel file systems (and reasonably well elsewhere). More... #include <vtkPNrrdReader.h> Read nrrd files efficiently from parallel file systems (and reasonably well elsewhere). vtkPNrrdReader is a subclass of vtkNrrdReader that will read Nrrd format header information of the image before reading the data. This means that the reader will automatically set information like file dimensions. Definition at line 50 of file vtkPNrrdReader.h. Definition at line 53 of file vtkPNrrdReader.h. Return 1 if this class is the same type of (or a subclass of) the named class. Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h. Reimplemented from vtkNrrdReader. Methods invoked by print to print information about the object including superclasses. Typically not called by the user (use Print() instead) but used in the hierarchical print process to combine the output of several classes. Reimplemented from vtkNrrdReader. Get/set the multi process controller to use for coordinated reads. By default, set to the global controller. Returns the size, in bytes of the scalar data type (GetDataScalarType). Break up the controller based on the files each process reads. Each group comprises the processes that read the same files in the same order. this->GroupedController is set to the group for the current process. Get the header size of the given open file. This should be used in liu of the GetHeaderSize methods of the superclass. Set up a "view" on the open file that will allow you to read the 2D or 3D subarray from the file in one read. Once you call this method, the file will look as if it contains only the data the local process needs to read in. Given a slice of the data, open the appropriate file, read the data into given buffer, and close the file. For three dimensional data, always use "slice" 0. Make sure the GroupedController is properly created before calling this using the PartitionController method. Transform the data from the order read from a file to the order to place in the output data (as defined by the transform). A group of processes that are reading the same file (as determined by PartitionController. This is a convenience method that is implemented in many subclasses instead of RequestData. It is called by RequestData. Reimplemented from vtkImageReader. Definition at line 119 of file vtkPNrrdReader.h. Definition at line 124 of file vtkPNrrdReader.h.
https://vtk.org/doc/nightly/html/classvtkPNrrdReader.html
CC-MAIN-2020-50
refinedweb
401
59.4
I.”?. I'm wondering your take on views in MVC? To me, this is where I spend 95% of my frustration. I am able to write domain code I am happy with, but the view seems to fight with doing domain properly (domain is behavior/event focused, view is property focused, etc). I am considering the idea of splitting them, but I don't know if I'm smart enough :p ASP.NET MVC is the only framework I have used at work (not even WebForms!) so maybe my confusion is from my limited exposure not seeing what Rails or Django are like... @eyston: that is a somewhat wide open question. My take would be that the view will often be written by someone who is not necessarily a developer. That consideration alone guided much of the design we put into the theming engine that Kona is using. I'll talk a lot more about this in future posts and when the new code is available but let's just say that we tried to lower the concept count to a minimum in view code. We also have some ideas around the separation of layout from actual content rendering. Stay tuned. Bertrand, Sad news about Rob leaving MS, but glad that they made a smart choice on having you pick up Kona. A colleague and I have been tinkering with a similar concept to your revised Kona plan for a while now, and just yesterday posted a call for ideas on the forums (forums.asp.net/.../1464120.aspx). We have both been working with the framework since the first preview, and have tried out a number of the concepts relating to pluggability and extensibility of ASP.Net MVC and the above post was intended to be the first step to consolidating them all into the sort of application-level framework you describe, to compete w/ the likes of Joomla or Drupal, but ideally with better scalability & provider (e.g. db) agnosticism. Our intent at this point (like you) is to use NHibernate as the persistence provider, and we were considering the use of Billy McAfferty's S#harp Architecture, though we aren't set on that yet. Bottom line, I'm excited about your vision for Kona and would like to collaborate! Paul yah... I don't know what I'm looking for. I guess just seeing more ways of doing things so I look forward to your examples. I know Rob had a screencast awhile ago where he had "this.Customer.Name" or something similar. I'm not sure if that means you create a strongly typed ViewPage where the model is part of the ViewPage properties? (honestly I was looking forward to more Kona screencasts and it seemed to disappear... is there even code out there?) The idea of having the view appreciate that a designer could be the one crafting is appealing, even if I'm that designer :). .." Paul Vencill and I have planning and spiking such a system for over a year. For the most part, we feel that we've reached the point where we are mostly satisfied with the design and are capable of putting our numerous sketches and spikes to the test. With the recent launch of MVC 2 CP1, we've decided to start the project completely fresh and placed an invitation for developers on the asp.net mvc forums. The post can be found here: forums.asp.net/.../1464120.aspx It sounds very exciting to me, even though there a lot of OSS offerings in .NET, I don't think it's anywhere near as comprehensive as the LAMP offerings. however, you have got to be careful not to try to be all things to all people (CommunityServer?). for me, simplicity counts a lot in what framework I end up using. @Paul: that sounds great and very much in line with lots of our thoughts and technical choices. Feel free to contact me at bleroy at microsoft. @Eyston: the this.Customer was an experiment that Rob tried. It was very nice in many ways, but it also came with a number of hidden strings attached and a few things that were less than clean (such as hacking the global namespace). We decided to use regular strongly-typed views instead, which actually works well enough and is much cleaner. @Dave: absolutely. From a learning standpoint I was interested in Rob's implementation of Workflows. Even though it may be overkill in some situations I would like to use it. Do intend to add it to the Kona project? @axsbrad: I'm not sure. The plugin logic is certainly staying.
http://weblogs.asp.net/bleroy/archive/2009/08/27/walking-the-tight-rope.aspx
CC-MAIN-2014-15
refinedweb
777
71.75
Hello everyone, I am a complete and utter newbie when it comes to programming. This sounds kind of silly coming from the mouth of a third year software engineering student but fact of the matter is, I know absolutly nothing. In the midst of all the theoritical stuff on how to optimize my algorithm and how to make sure my software is of good quality they forgot to make us practice the theory (granted I could of practiced on my own...). Anyways, I currently bought a book on how to program games using C and the Allegro library. Being excited and extremely motivated I made it to page 55 of 500 only to get stuck in the installation! I followed every step (I think... I tried like five times...) only to fail.! So... if any of you guys know a good site (for a dummy) that explains how to install both these things together and explains why things are done without skipping any steps could you please refer me to them? Thanks a lot in advance Seb [edit] PS: If there are no good webpages on the subject but someone is generous enough to help me install it, that is acceptable too I've tried on and off again to install different libraries to program games only to get stuck at the library's installation... However this time I really do want to succeed but I also want to understand why I did something! I might be wrong but I believe there is some documents in the src folders of allegrounder docs/doc. I currently bought a book on how to program games using C and the Allegro library. Let me guess: Game Programming All in One, second edition?! I assume you have no problems with installing Dev-C++, as I figure it comes with a standard Windows installer. I wouldn't be able to help anyway.To install Allegro, I believe you have several options. I think Dev-C++ has this thingy called `DevPacks' that you can use to install Allegro with, which should be easy enough to get to work.Alternatively, I would suggest you grab a pre-compiled version from. If you do want to install it, there should be a step-by-step guide in the documentantion that comes with Allegro (see the documentation for MinGW, since that's the compiler Dev-C++ uses). Download this: click to install it. Start a new project in DevC++, an Allegro template should be somewhere in "new project" window. _____________________________________________________"The world doesn't care about what storms you sailed through, it is interested in whether you brought the ship to the dock or not!" Hey guys, Thanks for the speedy reply. You are correct, it is in fact that book. Was it a bad choice on my part to purchase it? Also, the book came with a cd which already had the devpaks. I did install them but when I coded the script to check whether allegro was configured right it didn't want to compile. Something about not finding some file (alle40.dll or something similar to it). Someone mentioned in a thread that you had to write a path or something somewhere and the book also mentions this in the annexe but they never say which file to modify and what does what. That's where I got stuck. [edit] Well I DLed all the most recent versions and tried installing them following the intructions in the readme file of the precompiled version of allegro. After copy pasting the files in the right folders I got this compilation error. [Linker error] undefined reference to '__gxx_personality_v0'Id returned 1 exit status[Build Error] [GetInfo.exe] Error 1 okays... umm in the readme it says this: The contents of the "bin" folder (three DLLs) should be placedsomewhere in your system's PATH. Normally they are put in theC:\WINDOWS\SYSTEM32 folder. Now how do I put it in the system's "PATH"? Do I have to edit a file? Which one? You move the dlls from C:\Dev-C++\bin\alleg*.dll to C:\Windows\System32 However, that won't prevent this compiler error. It seems it is an error from the Dev-C++ installation. You could try installing a newer version of Dev-C++. --RB光子「あたしただ…奪う側に回ろうと思っただけよ」Mitsuko's last words, Battle Royale [Linker error] undefined reference to '__gxx_personality_v0' That linker error means that you have compiled the code as C++ code but are trying to link it as C code. In that case, you won't be linking the C++ library, whence the error.I don't know what settings you have to fiddle with to get that right, but try making sure that your filename's extension is .c, NOT .C. Regarding the code you posted, here's a correct version (yes, I know you copy&pasted that from the book): #include <stdlib.h> #include "allegro.h" int main() { allegro_init(); allegro_message("Allegro version = %s\n", allegro_id); return 0; } END_OF_MAIN() Evert: don't you mean #include <stdlib.h> #include <allegro.h> int main() { allegro_init(); allegro_message("Allegro version = %s\n", allegro_id); return 0; } END_OF_MAIN() ? -- Move to the Democratic People's Republic of Vivendi Universal (formerly known as Sweden) - officially democracy- and privacy-free since 2008-06-18! Awesome! Well I'm not too sure what the conio.h file does... regardless the program compiled and ran! I had set up the project as a c++ (unintentionally) but was writing my code in C. So I made a new project and pasted my code in there. It compiled and I got my console app. On a side note, I noticed that in your code you didn't include a semi colon at the end of END_OF_MAIN() was that intentional, if so, how does it work? Thanks a lot guys, like A LOT. Seb On a side note, I noticed that in your code you didn't include a semi colon at the end of END_OF_MAIN() was that intentional, if so, how does it work? It's intentional. END_OF_MAIN() is a macro expanding to a function, like this: int foo() { } So any semicolon will just be tacked on after the brace, which is superfluous. Evert: don't you mean Yes. I also meant to include void as the argument to main, though that is even more of a stylistic question. Well I'm not too sure what the conio.h file does... Nothing useful. It declares the getch() function which is not a standard C function that you have no reason to use anyway.
https://www.allegro.cc/forums/thread/559706
CC-MAIN-2018-30
refinedweb
1,095
73.07
NAME mmap, munmap - map or unmap files or devices into memory SYNOPSIS #include <sys/mman.h> void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *addr, size_t length); DESCRIPTION (since Linux 2.4.20, 2.6) Put the mapping into the first 2 Gigabytes of the process address space. This flag is only supported. Since Linux 2.6.23, this flag causes MAP_POPULATE to do nothing. One day the combination of MAP_POPULATE and MAP_NONBLOCK may be.21 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/karmic/man2/mmap.2.html
CC-MAIN-2015-27
refinedweb
105
69.38
Important: Please read the Qt Code of Conduct - Subclassing Graphics view and loading it from ui file. - metalshreds last edited by Hello, I am subclassing QGrahicsView so that I can control mouse input events for drawing multiple rectangles and selecting areas on the image. I am having a couple problems. I generate the view through qt designer, get a hold of the object as below. This is when things start to break. I originally scaled the QGraphicsView with **self.graphicsView_area.scale(2, 2)**but it doesn't work on my sub-class despite not overwriting the function. self.graphicsView_area = ImageGraphicsView(self.image_viewer.graphicsView_area) I also try overwritting the paintEvent function but even these lines tell me that the QWidget::paintEngine: Should no longer be called def paintEvent(self, event): qp = QPainter(self) Thanks in advance for any tips Okay first - a mini fully functional program of some sort (does not have to be the actual thing just something that shows what you are doing and has the issue you describe) is extremely helpful as it allows anyone considering to help you an easy means (aka copy/paste) of seeing your issue and trying to render you some aid. Also what version of Python are you using and what version/flavor of qt are you using and what OS. That being said what you provided is extremely inadequate for rendering you the help you desire -- please augment. Next I would personally say -- stop using the designer -- yeah I know in some ways it makes things easier but at a price. I find that with just a little extra effort understanding how the layout system works will put you miles ahead of those that use the designer because not only will understand how it should be done you will not have to work with that extremely ugly code the designer creates nor will you be constrained by the designer anymore. I suggest looking at what the designer makes to give you an idea of how it might be done but then I would take that base and do some clean up rewriting it to be easier to use and understand. - metalshreds last edited by Thanks for the reply and constructive feedback. I'm fairly new to qt so still getting the hang of how everything is tied together and how I can use it. Making a lot of beginner mistakes and learning about best practices. As you suggest I'll re-create what I have so far through code instead of the designer and make a better post if I run into issues. I'm building an image viewer with the ability to custom select areas of an image for pixel manipulation, hence trying to figure out how to capture mouse event and draw rectangles over the image. Thanks again! For capturing events you may want to look into something called addEventFilter (or something very similar to that) however I have found that there are sometimes various signals you can easily intercept if you make the object in question a class however these signals are not always that easy to ascertain since they may be buried a few classes deep so pay attention to the object inheritance being fairly new myself to qt I am starting to get a better handle on how the documentation is laid out -- for instance QTreeView may not have the property you are looking for but its parent has it so I have learned to (if I cannot find something in the object that I think ought to be there) open its parent and peruse it and then its parent's parent if I did not find it within its parent. I typically have not had to go back any further than the grandparent for property or method but you never now.
https://forum.qt.io/topic/104069/subclassing-graphics-view-and-loading-it-from-ui-file/4
CC-MAIN-2020-34
refinedweb
635
57.13
AU 2012 Handout: Moving code to the cloud – it’s easier than you think – Part 1 After posting the handout for my Wednesday class, now it’s time to start the one for Tuesday's - CP1914 - Moving Code to the Cloud: It's Easier Than You Think (I have a lot else going on on Tuesday, but this is the only class on that day for which I needed to prepare material). Attendance for both classes is looking fairly good: there are currently 138 attendees registered for the Cloud session and 62 registered for the one on WinRT. Why all this talk of the cloud? The software industry is steadily adopting a model commonly referred to as “cloud computing”. For many software developers, this will not appear to be anything very new: many have worked with centralized computing resources in the past – in the mainframe era – but that’s not to say that this shift isn’t valid. So let’s step back and look briefly at how the industry has evolved over recent decades. The mainframe era gave way to personal computing: Autodesk was one of many software companies that identified this trend and rode the wave to become a successfully business. The initial releases of AutoCAD were far from being really useable, in many ways, but it was clear that Moore’s Law – which indicated that the number of transistors on chips would double every 18-24 months – would hold long enough for the various pieces of the puzzle to provide the necessary performance from a personal computer before very long. Nothing lasts forever, especially if it’s an exponential law. Moore’s Law as we know it has hit a bit of a barrier in recent years: we’re no longer seeing CPU clock speed doubling, for instance, as we’re hitting certain physical laws that prevent this from happening. This article from Herb Sutter does a great job of explaining this in detail. That said, technology continues to evolve: rather than chips doubling in speed, we’re seeing the number of cores doubling, and the overall computing power that’s available to us via the cloud continuing to grow, too. For more information on this shift, see Herb’s sequel to the above article. Ultimately, for software developers to continue to see performance gains (and cost efficiencies) software is having to be architected to work in a more distributed manner, with much of its processing performed on the cloud. This work distribution is being made possible via improvements in infrastructure – it’s very common for people to have redundant methods of accessing the Internet, for instance, whether wired or wirelessly – and the cost of centralized resources are continuing to drop as performance between major hosting providers turns computing resources into a commodity (and some would say utility). At the same time as we’re seeing some kind of plateauing in performance of local, sequential software execution (although note the emphasis on sequential: parallelizing code can still bring performance gains from multi-core systems), we’re seeing a rise in the availability of lower-powered, mobile devices. As we enter the post-PC era, it’s increasingly the desire to be able to access centralized computing resources from devices that are little more than “dumb” terminals (although the modern smartphone contains more computing power than existed on the planet on the day many of their users was born). And the world is becoming truly heterogeneous in terms of computing devices: over time software developers will decreasingly target specific operating systems, having core algorithms executing centrally. There may still be some amount of native code targeting various supported devices, but even that is likely to reduced as true cross-platform execution improves (whether via toolkits or HTML5). Moving code to the cloud can make sense [You may want to skip this section if you remember reading this post.] So why would you move product functionality to the cloud? Here are some reasons: - Performance - If you have a problem you can easily chunk up and parallelize – rendering is a great example of this, as we’ve seen with Project Neon(which it seems is now known as Autodesk 360 Rendering) – then the cloud can provide significant value. Renting 1 CPU for 10,000 seconds is (more or less) the same cost as buying 10,000 CPUs for 1 second. - Scalability - With cloud services you pay for what you use, which should scale linearly with your company’s income (or benefits) from hosting functionality in that way. Dynamic provisioning allows companies to spin up servers to manage usage spikes, too, which allows infrastructure to be made available “just in time” rather than “just in case”. - Reliability - You often hear about measurements such as “five nines” uptime, which means 99.999% availability (or about 5 minutes of downtime per year). Some providers are no doubt proving better than others at meeting their availability SLAs, but the fact remains: having a local system or server die generally creates more significant downtime than those suffered by the outages suffered by cloud providers. And that should only get better, over time. - Low cost - As cloud services get increasingly commoditized – and Microsoft, Google and Amazon are competing fiercely in the cloud space, driving costs down further – using the cloud is becoming increasingly cost-effective. That’s a bit about the “why”, here’s the “when”… - Computation intensive - If you have serious number crunching going on locally in your desktop apps – which either ties up resources that could be used differently or stops your apps running on lower-spec hardware – then the cloud is likely to look attractive. I mentioned we use make the cloud available for rendering, but we’re doing the same with simulation and analysis, too. - Collaboration - Imagine implementing the collaboration features of AutoCAD WS without the cloud… - Frequent change - If you have applications that go through rapid release cycles, then update deployment/patching is likely to be a challenge for you. Hosting capabilities on the cloud – appropriately versioned when you make breaking interface changes, of course – can certainly help address this. - Large data sets - The ideal scenario is clearly that data is co-located with the processing capability that needs to access it. Much of this data is currently stored on local systems – which makes harnessing the cloud a challenge – but as data shifts to be hosted there (for lots of very good reasons), this starts to become more compelling. - Another example: let’s say you have an application that relies on a local database of pricing information. Making sure this database is up-to-date can be a royal pain: it’s little surprise, then, that a number of the early adopters of cloud technology in the design space relate to pricing applications. These were the main benefits that have been presented to ADN members during DevDays. There are few additional benefits that I’d like to add… - Customer intimacy - Delivering software as a service can increase the intimacy you have with customers – and with partners, if you’re providing a platform. You have very good knowledge of how your technology is being used – and this has a “Big Brother” flip-side that people often struggle with, as you clearly have to trust your technology provider – which can allow you to provide better service and even anticipate customer needs. - Technology abstraction - You may have some atypical code that you’d like the user to not have to worry about: let’s say you have some legacy product functionality implemented using Fortran or COBOL that you’d rather not have to provide a local runtime to support. Hiding it behind a web service reduces the complexity in deploying the application and can provide a much cleaner installation/deployment/usage capability. - Device support - This is probably obvious (as many of the preceding points will have been to some of you, I expect), but web services are accessible from all modern programming languages on any internet-enabled device. Web services are a great way to more quickly support a variety of usages of your application’s capabilities on a variety of devices. Today’s Example We’re going to take an example that hits on a few of these topics: we have a core algorithm – implemented in F#, which some might questionably classify as arcane ;-) – that we want to move behind a cloud-hosted web-service and use from a number of different devices. The algorithm generates Apollonian Gaskets – a 2D fractal, which places as many circles as it can within the “whitespace” inside a circle – and Apollonian Packings – the 3D equivalent which obvious deals with spheres. We’re going to have fun using this service to generate some interesting 3D visualizations on a variety of platforms. Choosing a cloud hosting provider Autodesk is a very heavy user of Amazon Web Services, which might indicate it would be a good, long-term choice for users and developers to adopt (as co-location with data is of benefit, as we’ve seen). That said, there are lots of factors that contribute to this kind of decision. The early popularity of AWS was due in large part to its focus on providing Infrastructure-as-a-Service (IaaS): they made it really easy for companies with their own servers to move them across to be hosted centrally. Many companies shifted from on-premise servers (or perhaps their own data-centers) to centrally hosted and managed servers. Microsoft’s approach has been to deliver highly integrated Platform-as-a-Service (PaaS) offerings: they abstract away the physical machine, focusing on the “roles” that you deploy to the cloud. Microsoft is now starting to deliver via an IaaS model, just as Amazon is providing more by way of PaaS from their side. In our particular example, we’re going to make use of Windows Azure. That’s not to say it’s better for everyone – it’s just what I’ve chosen to use for this project as the integration with Visual Studio is first-class and I have free hosting provided via my MSDN subscription. If you’re interested in AWS, I recommend looking at some of the guides on ADN’s Cloud & Mobile DevBlog. Another option is Google App Engine, which provides an even higher level of abstraction that Azure. It seems to be an excellent system for highly granular, scalable tasks (without even having the underlying concept of physical machines in the picture). If interested in learning more about Google App Engine, I recommend attending tomorrow’s 8am class by my colleague (and manager), Ravi Krishnaswamy: CP2568 – PaaSt the Desktop: Implementing Cloud-Based Productivity Solutions with the AutoCAD® ObjectARX® API Architecting for the cloud There are lots of decisions to be made when considering moving application functionality to the cloud. Not least of which is “what is your core business logic?” meaning the algorithms that are application- and device-independent. The algorithms that moving away from your core implementation increases your flexibility and platform independence. You also need to consider the data that needs to be transferred between the client and the cloud: both in terms of the arguments that need to be sent to your cloud-based “function” and the results that need to be brought back down to earth afterwards. Ideally you’d be working with data that’s already hosted in the cloud – and this is likely to happen more and more, over time – but that’s not necessarily where we are today. You should also think about whether there are optimizations to be made around repeated data: should you be making use of cloud-hosted database storage (which is very cheap when compared with compute resources) or some kind of caching service? In our case we’re going to re-calculate the data, each time, but we could very easily implement a cache of the “unit” results and then multiply those for specifically requested radii. Another important question is whether offline working needs to be supported: does a local version of the algorithm – or a cache of local data – need to be maintained in order to enable this? An increasingly easy decision, amongst others that are quite tricky, is how to expose your web-services. These days the commonly accepted approach is to expose RESTful services, which means the transport protocol for data is standard HTTP and (most commonly) any results will be encoded in JSON – JavaScript Object Notation. JSON isn’t actually a required part of REST – it’s also possible for RESTful services to return XML, for instance – but it has become the de-facto approach that is most favored by API consumers. The previous “standard” was SOAP – Simple Object Access Protocol. SOAP has gradually ceded ground to REST, as it required more effort to create XML envelopes containing the data to transmit to the web-service, and is generally more verbose and requires more bandwidth. A common requirement is around authentication: you probably want to be able to monitor and control access to your web-services. This is not going to be covered in this class, but you may want to look at OAuth-compatible toolkits such as DotNetOpenAuth, which comes pre-integrated with AS.NET 4.5. How you end up exposing your RESTful web-services will depend on your choice of technology stack (although these days it should be simple to do so from which choice you make). The Microsoft stack – which would often involve ASP.NET at some level, irrespective of whether you host on AWS or Azure – certainly abstracts away a lot of the messiness with exposing web-services, but comes with a certain execution overhead. If you really want to get “close to the metal” then you might also want to consider a Linux environment: not only do you end up with lower execution overhead but the cost associated with Linux instances can be very interesting. And as we know, the actual implementation of the web-service should be largely irrelevant to the consumer. For today’s example we’re going to go with Microsoft and choose its ASP.NET MVC 4 Web API. This is a great way to expose web-sites with associated web-services, and seems to be the product of choice for people using the Microsoft stack to expose web-services, these days. WCF, the Windows Communication Framework, provides some very interesting capabilities – especially when needing to marshal more complex data-types to and from web-services – but our requirement is relatively simple and the Web API seems the best fit. The ADN DevBlog mentioned earlier provides some good information on using WCF. Considering cloud costs One of the key benefits of the cloud is its ability to scale as you provision more resources to deliver your web-services. The counterpoint is that if you over-estimate the resources required to do this, your costs will be proportionally higher than they need to be. Companies making heavy use of the cloud tend to invest in tools they can use to scale up and down automatically based on usage. This is not a topic that we’ll cover today, but it’s worth pointing out that getting this right is important for any significant cloud-based deployment. There are some general things you can do to keep costs in check: consider looking for ways to reduce your instance sizes – dropping from a small to an extra-small instance size can bring significant costs benefits (adding some caching or online database storage might be a way to enable this, helping reduce the processing load). Online calculators are available to help you determine up-front costs associated with provisioning resources, here are the calculators for Azure and AWS. Be sure to monitor actual costs (and optimize provisioning based on real usage, ideally), to make sure they are in line with projections. The Problem Now let’s go back to today’s “problem”. We want to move our business logic – the core F# algorithm used to generate 2D and 3D Apollonian fractals – behind a cloud-based web-service. The original implementation for the 3D packing algorithm was provided in C++ by a Professor of Mathematics at the prestigious ETH in Zurich, but I chosen to migrate the code to F# to see how it looked (and having the code in a language that isn’t necessarily easy to get working on OS X, iOS and Android demonstrates the “technology abstraction” point from an earlier slide nicely. As mentioned earlier, we’re not going to worry about authenticating users of our web-service: it’s a topic that would probably deserve a class of its own. We’re going to expose a simple, unsecured web-service (at least in terms of the need for authentication to make use of it). Once it’s up, you’ll be able to query the geometry defining 2D Apollonian Gaskets using the “circles” API: - (returns circle definitions via JSON) And 3D Apollonian Packings using the “spheres” API: - (returns sphere definitions via JSON) Building a simple web-service We’re going to use the ASP.NET MVC 4 Web API to expose our web-service. MVC – standing for the common “Model View Controller” architectural pattern, which is used to separate model data from UI and interactions – is Microsoft’s technology of choice for defining and hosting web-sites and -services on top of ASP.NET. We don’t care a great deal about the web-site – we’re much more interested in the web-services – but we’ll go ahead and create one, anyway. While Windows Azure apparently now supports .NET 4.5, we’re going to stick with .NET 4.0 (at the time of writing this new capability had only just been announced). We’re going to install an F#-aware project template into VS2012 and make use of that to create our Web API project. Once published to Azure, the code will be hosted and executed on Windows Server 2008 (although this is really a detail – this is not something we should have to worry about at all). We’ll start by getting our project template installed. We can select it via the “Extensions and Updates” manager on the VS 2012 Tools menu, searching for “F# C# MVC 4”. Once installed, we can launch a project of this type and select “WebApi Project”: Visual Studio will go ahead and create our basic project from the template. We can launch the default web-site via the debugger: To test the default implementation of the web-service, try appending the following suffix to the URL: /api/values At this point the browser will ask us whether we want to save or open the results from the web-service. Opening the results in Notepad should show them to be ["value1","value2"]. There are a few changes we’ll make to the project to get it working as we want it. Firstly, we should change the .NET Framework target to 4.0 from 4.5 for both the contained projects. Then some changes to the web-site project (ApollonianPackingWebApi). - We want to copy across some files from the “ToCopy” folder: Site.css into the Content folder - Three images into the Images folder (two of which need adding to the project) - Index.cshtml into the Views -> Home folder - crossdomain.xml into the root folder Now running the project should look very different (although the .CSS change doesn’t always get picked up if running locally – the background of the “Welcome” area should be orange, but often looks blue before it makes it up to Azure). There are still some changes needed to allow our service to support “cross domain scripting” (which for us primarily means being callable from client-side HTML5/JavaScript code). The first step was to add the crossdomain.xml file but we also need to open Web.config and add these elements: Inside <configuration><system.web>: <customErrors mode="Off" /> Inside <configuration><system.webServer>: <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> And then we should expand the serialization limit beyond the default to make sure it’s large enough for our largest JSON string: <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="500000"> </jsonSerialization> </webServices> </scripting> </system.web.extensions> We can then update the web-services project (ApollonianPackingWebAppApi). Copy across the various files into the root project folder: Global.fs will update the existing file. Here are its contents: namespace FsWeb open System open System.Web open System.Web.Mvc open System.Web.Routing open System.Web.Http open System.Data.Entity open System.Web.Optimization open System.Linq open System.Collections.Generic open Newtonsoft.Json open Newtonsoft.Json.Serialization type OrderedContractResolver() = inherit DefaultContractResolver() override x.CreateProperties(tp, ms) = (base.CreateProperties(tp, ms).OrderBy (fun(p) -> p.PropertyName)).ToList() :> IList<JsonProperty> type BundleConfig() = static member RegisterBundles (bundles:BundleCollection) = bundles.Add (ScriptBundle("~/bundles/jquery").Include ("~/Scripts/jquery-1.*")) bundles.Add (ScriptBundle("~/bundles/jqueryui").Include ("~/Scripts/jquery-ui*")) bundles.Add(ScriptBundle("~/bundles/jqueryval").Include ("~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")) bundles.Add(ScriptBundle("~/bundles/modernizr").Include ("~/Scripts/modernizr-*")) bundles.Add(StyleBundle("~/Content/css").Include ("~/Content/*.css")) bundles")) type Route = { controller : string action : string rad : UrlParameter steps : UrlParameter } type ApiRoute = { rad : obj steps : obj } type Global() = inherit System.Web.HttpApplication() static member RegisterGlobalFilters (filters:GlobalFilterCollection) = filters.Add(new HandleErrorAttribute()) static member RegisterRoutes(routes:RouteCollection) = routes.IgnoreRoute("{resource}.axd/{*pathInfo}") routes.MapHttpRoute( "DefaultApi", "api/{controller}/{rad}/{steps}", { rad = RouteParameter.Optional steps = RouteParameter.Optional }) |> ignore routes.MapRoute( "Default", "{controller}/{action}/{rad}/{steps}", { controller = "Home" action = "Index" rad = UrlParameter.Optional steps = UrlParameter.Optional } ) member this.Start() = // Only support JSON, not XML let cfg = GlobalConfiguration.Configuration cfg.Formatters.Remove(cfg.Formatters.XmlFormatter) |> ignore // Order the JSON fields alphabetically let stg = new JsonSerializerSettings() stg.ContractResolver <- new OrderedContractResolver() :> IContractResolver cfg.Formatters.JsonFormatter.SerializerSettings <- stg AreaRegistration.RegisterAllAreas() Global.RegisterRoutes RouteTable.Routes |> ignore Global.RegisterGlobalFilters GlobalFilters.Filters BundleConfig.RegisterBundles BundleTable.Bundles The other four files need to be added to the project. Two of them, CirclePackingFull.fs and SpherePackingInversion.fs, are copied directly from the previous AutoCAD-hosted version of the application. The other two, CirclesController.fs and SpheresController.fs, implement the logic to pass the API requests through to our core algorithm implementations. Here’s CirclesController.cs: namespace FsWeb.Controllers open System open System.Web.Http type Circle (X, Y, C, L) = member this.X = X member this.Y = Y member this.C = C member this.L = L type CirclesController() = inherit ApiController() // GET /api/values/rad/steps member x.Get(rad:double, steps:int) = CirclePackingFullFs.Packer.ApollonianGasket rad steps |> List.map (fun ((a,b,c),d) -> new Circle (Math.Round(a, 4), Math.Round(b, 4), Math.Round(c, 4), d)) |> List.toSeq And here’s SpheresController.cs: namespace FsWeb.Controllers open System open System.Web.Http type Sphere (X, Y, Z, R, L) = member this.X = X member this.Y = Y member this.Z = Z member this.R = R member this.L = L type SpheresController() = inherit ApiController() // GET /api/values/rad/steps member x.Get(rad:double, steps:int) = SpherePackingInversionFs.Packer.ApollonianGasket steps 0.01 false |> List.map (fun ((a,b,c,d),e) -> new Sphere (Math.Round(a * rad, 4), Math.Round(b * rad, 4), Math.Round(c * rad, 4), Math.Round(d * rad, 4), e)) |> List.toSeq You can safely remove ValuesController.fs from the project (deleting it from disk, should you so wish). To test our web-site and -service, we first want to launch it in a browser (most easily via the debugger): With the web-site loaded, we can then add these URL suffices into the browser to test the two APIs: - /api/circles/2/2 - /api/spheres/2/2 The first number in each of these URLs specifies the desired radius of the outer circle/sphere to be packed while the second tells the recursion level: how “deep” the fractal should go. Here are the results of the first of these calls. It should be easy enough to see how the JSON file contains a list of circle definitions, each with X, Y, Curvature and Level values: [{"C":1.0774,"L":2,"X":2,"Y":3.0718},{"C":1.0774,"L":2,"X":2.9282,"Y":1.4641},{"C":1.0774,"L":2,"X":1.0718,"Y":1.4641},{"C":6.9641,"L":1,"X":2,"Y":2},{"C":17.1603,"L":0,"X":2.1748,"Y":2.1009},{"C":17.1603,"L":0,"X":2,"Y":1.7981},{"C":17.1603,"L":0,"X":1.8252,"Y":2.1009},{"C":2.2321,"L":0,"X":3.3441,"Y":2.776},{"C":2.2321,"L":0,"X":2,"Y":0.448},{"C":2.2321,"L":0,"X":0.6559,"Y":2.776}] Assuming both web-service calls return valid JSON files, we are now ready to publish to Azure. Which we will look at in the next post. :-) Recent Comments Archives More...
http://through-the-interface.typepad.com/through_the_interface/2012/11/au-2012-handout-moving-code-to-the-cloud-its-easier-than-you-think-part-1.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+typepad%2Fwalmsleyk%2Fthrough_the_interface+%28Through+the+Interface%29
CC-MAIN-2014-52
refinedweb
4,152
53.41
Jason R. Coombs <jaraco at jaraco.com> added the comment: You're right. The documentation isn't incorrect, if you're splitting hairs. But it's not super friendly either. Questions that the documentation should answer: 1) Does the action always need to be a subclass of an Action, or is that recommended? If it's recommended, replace "easiest" with "recommended". 2) If it does not always need to be a subclass of Action, what is the interface expected of a class for a custom action? 3) If one does use a subclass of Action, are there any hooks that are called at any point? How does one customize an action other than to override __call__? What attributes are available on the object (the example shows .dest only)? 4) What is the action required to do in __call__, if anything? Is there any way to invoke the default behavior (if for example a special case wasn't detected)? All of these questions can be answered by going to the source, but I've twice now gone to the documentation to reference how to provide a custom action and found the documentation insufficient. Now that I review the source again, I think I know the answers to those questions. 1) It does not always need to be a subclass of Action, but it is recommended. 2) The action API expects a callable with the following signature: Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None) which when called returns another callable accepting the four parameters. 3) Argparse does nothing with the custom action except to call it first with the init parameters, then calls the result with four parameters. If subclassing Action, the default __init__ simply stores each of those parameters as attributes on the object. Most subclasses of Action will override the __init__ to validate the options and raise an exception (typically a ValueError) when the parameters aren't valid. 4) The action is not required to do anything. Most actions will perform some logic and then invoke setattr(namespace, self.dest, result) where result is the result of some logic. I can see why no one wanted to write this documentation. It's difficult to describe simply. Here's what I propose: First, remove the phrase "Action API" which suggests that there's an API outside of subclassing the Action that's recommended. Second, change "easiest" to "recommended" to using the class. Third, explain what attributes are available on an object initialized from a subclass of Action. Provide a link to code or other section that describes advanced usage (overriding __init__). Fourth, explain what is expected when calling an Action instance (i.e. setattr). Fifth, consider extending the Action class so that __call__ calls an actual named method so that those writing custom actions aren't writing classes with only a __call__ method. Perhaps "invoke". I feel less strongly about this point, but it seems strange that the recommended usage is to write a class with only a __call__ method. ---------- _______________________________________ Python tracker <report at bugs.python.org> <> _______________________________________
https://mail.python.org/pipermail/docs/2011-December/006719.html
CC-MAIN-2016-44
refinedweb
520
64.3
Introduction When it comes to true unit tests, having a mocking framework such as Spock for Java is essential. Using a mocking framework ensures that your unit tests are fast, self-contained and deterministic. A mocking framework can help you fake external systems, pre-program your classes with expected responses, and test hard-to-replicate error conditions. There are several mocking frameworks in the Java world, but the most popular one is Mockito. Our previous mocking tutorial is a great introduction to Mockito if you would like a detailed tutorial on using it. In this tutorial, we will cover the Spock testing framework, an emerging framework that can be used to test both Java and Groovy code. Unlike Mockito, Spock is a complete testing framework that can function on its own (Mockito works in addition to JUnit). For the code examples, we will use the same situations that were presented in the Mockito tutorial. This will allow for an easy comparison between the two frameworks. If you ever wanted to see how Spock competes against the Junit/Mockito combo, you will find this tutorial particularly interesting. We will cover: - Downloading and setting up Spock — the “batteries included” testing framework for both Java and Groovy - Some very brief theory on the goals of Spock, - Stubbing return data from methods, - Verifying interactions, - Capturing arguments, and - Returning custom mocked responses. Notice that the tutorial will focus exclusively on testing Java code. Even though Spock can also work with Groovy code, in this tutorial we will focus on Java unit tests. Spock can test both Java and Groovy, but in the case of Groovy it has some additional capabilities that we will not cover here.. The Java project may or may not have existing JUnit tests. Spock tests can be added to the project without any negative impact on the existing JUnit tests. Both kinds of tests will run when the Maven test goal is executed. Groovy knowledge is NOT required, as the Spock tests will be written in a Groovy style that is very close to Java. However, for some advanced examples it would be beneficial to know Java 8 lambda expressions as they will be similar to the Groovy closures in this tutorial. It is also assumed that we already know our way around basic Maven builds. If not, feel free to consult its official documentation first. Mockito knowledge is not strictly required. We will cover some differences between Mockito and Spock that will be useful if you are already a Mockito veteran. Setting Up Spock Spock is already distributed via Maven central, so using it in a Java forward is a painless process. We just need to modify the pom.xml and add the following dependencies: <dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>1.1-groovy-2.4</version> <scope>test</scope> </dependency> <dependency> <!-- enables mocking of classes (in addition to interfaces) --> <groupId>net.bytebuddy</groupId> <artifactId>byte-buddy</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency> <dependency> <!-- enables mocking of classes without default constructor (together with CGLIB) --> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> <version>2.5.1</version> <scope>test</scope> </dependency> The reason why we need three dependencies instead of just one is that the extra libraries are needed to “replicate” some of the needed built-in Groovy functionality, e.g. if we wanted to write unit tests for a Groovy application. In order to integrate Spock into the Maven lifecycle, we also need the following additions in the same pom file: org.codehaus.gmavenplus gmavenplus-plugin 1.5 compile testCompile maven-surefire-plugin 2.18.1 false **/*Spec.java **/*Test.java The Surefire plugin configuration ensures that both JUnit and Spock unit tests are honored by Maven. This concludes the setup. Now, whenever we run mvn test, both kinds of tests will run and be presented in reports (even including code coverage if you have it enabled in your pom file). Spock unit tests will need to be placed in the src/test/groovy/ folder, while JUnit tests (if any) are still in src/test/java/ as per Maven guidelines. Spock and the Java Ecosystem If you are already a veteran of JUnit and assorted testing tools, you might wonder why Spock was created in the first place. Aren’t the existing testing frameworks capable of dealing with all of our testing needs? The answer is that Spock was created to cover the full testing lifecycle of a Java Enterprise application. The existing tools have a long history and come with several legacy features that cannot always keep up with newer testing practices. The most evident example of this is the fact that JUnit covers only plain unit testing and nothing else. If you need to mock some services or wish to employ Behavior-driven development, JUnit is simply not enough. You are forced to add more testing frameworks into the mix, each one with its own idiosyncrasies and issues. Spock takes a step back and offers you all the testing facilities you might need during the full testing lifecycle. It comes with built-in mocking and stubbing and several extra testing annotations created exclusively for integration tests. At the same time, because Spock is a newer testing framework, it had the time to observe common pitfalls of the existing frameworks and either fix them or offer a more elegant workaround. Explaining all the advantages of Spock over existing solutions is out of the scope of this article. A more detailed comparison between Spock and the JUnit/Mockito combo can be found in the Spock vs JUnit article. In the context of mocking, Spock offers four major advantages: - Spock doesn’t need special constructs for capturing arguments and creating mocked answers. It uses Groovy closures, which are similar to Java 8 lambda expressions. - Mockito has a limitation with argument matchers. If you use matchers in a method, then all arguments need to have matchers. Spock does not suffer from this limitation, and you can mix and match real arguments with argument matcher. - Spock makes a distinction between stubs and mocks, making unit tests slightly more readable. - Spock presents much more detailed error messages when expected mock invocations are not found. A Word on Mocking and Stubbing The theory behind mocking and stubbing was already explained in the previous article under the section “The Need for Mocks and Stubs”. We are not going to repeat it here. In summary, we use mocks to isolate the class under test and examine it in a completely controlled environment. Common targets for mocking are: - Database connections, - Web services, - Classes that are slow, - Classes with side effects, and - Classes with non-deterministic behavior. We will cover two kinds of mock objects. Stubs are fake classes that come with preprogrammed return values. Mocks are fake classes that we can examine after a test has finished and see which methods were run or not. Spock makes a clear distinction between the two as mocks and stubs, as we will see in the sections to follow. Semaphore also provides tutorials for mocking in other languages if your interests go beyond Java: Basic Stubbing with Spock. We will test it by stubbing the EntityManager so that we can decide what gets returned without having a real database. Here is the Spock unit test: public class CustomerReaderSpec extends spock.lang.Specification{ entityManager = Stub(EntityManager.class) entityManager.find(Customer.class,1L) >> sampleCustomer and: "a customer reader which is the class under test" CustomerReader customerReader = new CustomerReader() customerReader.setEntityManager(entityManager) when: "we ask for the full name of the customer" String fullName = customerReader.findFullName(1L) then: "we get both the first and the last name" fullName == "Susan Ivanova" } } This file is called CustomerReaderSpec.groovy, and it should be placed in the folder src/test/groovy under the same Java package as the class under test. We have instructed Spock to run unit tests that end in *Spec in the Maven pom file, as described in the previous section. Even if you have never seen Groovy/Spock before, the syntax of the unit test should be familiar, as the code is deliberately written to be Java-like. First of all, we have named our unit test using a full sentence that explains its purpose (customer full name is first name plus last name). With Spock, you are free to use proper English explanations for your unit tests. These sentences also appear in unit test reports, so they are very valuable for other people in your organization (e.g. Project Managers), as they can understand what a unit test does with zero Java/Groovy knowledge. More importantly, the test content itself is marked with given, and, when, then labels that showcase the BDD sprit of Spock. These labels are called blocks in Spock parlance, and they logically divide the unit test to create a well-defined structure. The strings next to each label serve as a human-readable explanation of the associated code block. The idea is that somebody can focus only on these labels and understand what the unit tests does without actually looking at the code. In this particular example, the following blocks are contained: - given: “a customer with example name values” - and: “an entity manager that always returns this customer” - and: “a customer reader which is the class under test” - when: “we ask for the full name of the customer” - then: “we get both the first and the last name” Reading the block descriptions creates an English sentence that serves as a mini-specification of what the test does. The labels can be normal strings, so you should strive to name them according to your business domain and abstraction depth that suits you. Ideally, you should use full sentences to explain what each block does in a high-level manner. The given: block contains just some Java code that creates a sample customer. The first and: block is where we actually create a fake object. In this particular case, we create a stub using the static method Stub() that Spock offers. We essentially tell Spock that it will need to create a fake object for the EntityManager class. The most important line of the whole test is the next one. The line entityManager.find(Customer.class,1L) >> sampleCustomer instructs Spock what to do when the find() method of the stub is called. The carret character means “return” in Spock parlance. The whole statement says: “when the entityManager find() method is called with arguments Customer class and 1, return our sample customer”. If you know how Mockito works, the equivalent line would be: when(entityManager.find(Customer.class,1L)).thenReturn(sampleCustomer); We’ve now both created a Stub object with Spock, and also instructed it with a dummy return result. Next, we create our CustomerReader reader object and pass as a dependency the fake object. From now on, the CustomerReader class will function without understanding that the EntityManager is not a real one. In the when: block, we call our test method in the usual Java manner. The final block is the then: block. This is the block that decides if the test will fail or not. Unlike Junit, Spock does not use assert statements. Instead, it expects normal boolean statements. Statements in the then: block will be evaluated by Spock as boolean, and if all of them are true, the test will pass. If any of them fail, the test will fail as well. Notice also that no statement has a semicolon at the end of the line. Unlike Java, Groovy does not require semicolons. With the test code in place, we can run this Spock unit test either from the command line (using the mvn test command), or via our favorite IDE. Here is an example with Eclipse. As far as Eclipse is concerned, the Spock test is handled in exactly the same way as a JUnit test would be. The test result shows the title correctly as a full English sentence. Grouping Multiple Unit Tests for the Same Class Under Test In the previous section, we had a single unit test in a single file. In a real project, we will probably have multiple unit tests for the same class under test in order to evaluate multiple scenarios and conditions. In those cases, it makes sense to move the stub creation process to a reusable method, removing code duplication. Similar to the @Before annotation in JUnit, Spock also allows the extraction of common setup code into a method that will run before each unit test. You might have already noticed that our CustomerReader class is not correct, as it does not handle the null case, i.e. the given database ID does not exist as an object in the DB. Let’s create a unit test that covers this scenario as well. public class CustomerReader2Spec extends spock.lang.Specification{ //Class to be tested private CustomerReader customerReader; //Dependencies private EntityManager entityManager; /** * Runs before each test method, like the JUnit Before * annotation */ public void setup(){ customerReader = new CustomerReader(); entityManager = Stub(EntityManager.class); customerReader.setEntityManager(entityManager); }.find(Customer.class,1L) >> sampleCustomer when: "we ask for the full name of the customer" String fullName = customerReader.findFullName(1L) then: "we get both first and last name" fullName == "Susan Ivanova" } public void "customer is not in the database"(){ given: "the database has no record for the customer" entityManager.find(Customer.class,1L) >> null when: "we ask for the full name of the customer" String fullName = customerReader.findFullName(1L) then: "the empty string should be returned" fullName == "" } } The method named setup() will be executed by Spock before each individual name. This functionality is detected by the name of the method itself (there is no Spock annotation for this). Apart from extracting the common code for creating our test class and its mocked dependencies, we have also added a second scenario for the case when the customer is not in the database. For this scenario, the stubbing line is changed to entityManager.find(Customer.class,1L) >> null. This line means: “when the find() method is called with these arguments, then return null”. In true TDD fashion, we have created the unit tests before the actual implementation. If you run our unit test, the second test method will fail. Eclipse should still show the names of the tests as full sentences. As an exercise, feel free to correct the CustomerReader implementation and also add extra unit tests when the first and/or last name are null themselves. To gain full advantage of the individual Spock blocks, you can also use the external project of Spock reports. Here is a sample report: You can find information on how to use the reports in the README file. Basic Mocking with Spock In all the examples so far, we have only seen Spock stubs (i.e. classes that hardcoded return values). For a mocking example, let’s assume that we have the following class in our, a class that sends emails and an invoice database. It checks for late customer invoices, and sends customers an email if an invoice is late. We want to test the method notifyIfLate() and ensure that emails are sent to a customer only if they have outstanding invoices. Since the method does not have a return value, the only way to verify if it runs or not is to use a mock. We will mock both InvoiceStorage and EmailSender, run the unit test and examine what interactions took place after the test has finished. We need to test two scenarios. In the first one, the customer has an outstanding invoice (and thus an email should be sent). In the second one, the customer has no pending invoices. Here is the Spock code: public class LateInvoiceNotifierSpec extends spock.lang.Specification{ //Class to be tested private LateInvoiceNotifier lateInvoiceNotifier //Dependencies (will be mocked) private EmailSender emailSender private InvoiceStorage invoiceStorage //Test data private Customer sampleCustomer /** * Runs before each test method, like the JUnit Before * annotation */ public void setup(){ invoiceStorage = Stub") } public void "a late invoice should trigger an email"() {) } public void "no late invoices"() { given: "a customer with good standing" invoiceStorage.hasOutstandingInvoice(sampleCustomer) >> false when: "we check if an email should be sent" lateInvoiceNotifier.notifyIfLate(sampleCustomer) then: "an email is never sent out" 0 * emailSender.sendEmail(sampleCustomer) } } The first dependency, InvoiceStorage, is used as a stub. This is why we use the caret syntax as shown in the previous section. For the first test, we assume the customer has an outstanding invoice (line invoiceStorage.hasOutstandingInvoice(sampleCustomer) >> true). For the second test, no late invoice is present (line invoiceStorage.hasOutstandingInvoice(sampleCustomer) >> false.) The second dependency – EmailSender is a bit different. At the end of the test, we need to know if an email was sent or not. The only way to do this is to check how many times the method sendEmail() was called using a mock. Spock supports the creation of mocks using the static Mock() method. Here is the respective line: When running a unit test, Spock keeps track of all the invocations that happen with mocked objects. At the end of the test, we can query these invocations with the following Spock syntax: N * mockedObject.method(arguments) This line means: “after this test is finished, this method of mockedObject should have been called N times with these arguments“. If this has happened, the test will pass. Otherwise, Spock will fail the test. The verification lines are placed inside the then: block of each test, right at the end of the test method. In our case, the line 1 * emailSender.sendEmail(sampleCustomer) means: “once this test has finished, the sendEmail() method should have been called 1 time with the sampleCustomer class as an argument. This is the scenario when an email should be sent. In the second scenario, the number of times is zero because no email should be sent. If you already know Mockito, these two Spock lines map to verify(emailSender, times(1)).sendEmail(sampleCustomer); and verify(emailSender, times(0)).sendEmail(sampleCustomer); respectively. Spock is smart enough to monitor the expected invocations, and give a clear error message when things go wrong. For example, let’s assume that we have a bug in the code that does not send reminders to customers when they have outstanding invoices. The test will fail, and Spock will present the following error message: Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.015 sec <<< FAILURE! - in com.codepipes.mocking.LateInvoiceNotifierSpec a late invoice should trigger an email(com.codepipes.mocking.LateInvoiceNotifierSpec) Time elapsed: 0 sec <<< FAILURE! org.spockframework.mock.TooFewInvocationsError: Too few invocations for: 1 * emailSender.sendEmail(sampleCustomer) (0 invocations) In the error message, Spock explains how we requested 1 call for the method sendEmail(), but that method was never called – 0 invocations. Verifying Mocked Object Arguments we want to write a unit test that verifies that the event recorded: - is of type REMINDER_SENT, - has the correct customer name, and - contains a timestamp. Spock supports examining method arguments using Groovy closures. Groovy closures are very similar to Java 8 lambda expressions, so you don’t need any special knowledge to understand them if you have already worked with Java 8. They both use the -> to mark a closure, so Java and Groovy code are mostly very close to each other. Here is the Spock test that not only verifies that the email event was recorded, but also checks its values: public class EventCheckSpec extends spock.lang.Specification{ /; /** * Runs before each test method, like the JUnit Before * annotation */ public void setup(){ invoiceStorage = Stub") } public void "email about late invoice should contain customer details"() {) and: "the event is recorded with the respective details" 1 * eventRecorder.recordEvent({ event -> event.getTimestamp() != null && event.getType() == Event.Type.REMINDER_SENT && event.getCustomerName() == "Susan Ivanova" }) } } Our class under test LateInvoiceNotifier now has 3 dependencies: InvoiceStorageis just used as a helper, so we stub it EmailSenderwill be used to verify that an email was sent. We create a Mock for it, and EventRecorderwill also be used to verify the event that was emitted. We also create a mock for it. The creation of these 3 mocks happens in the setup() method. Our class under test now has 3 fake dependencies, and we have full control of all input and output that happens during the unit test. The unit test itself has a slightly different structure from the ones we have seen before. This time, we have the following blocks: given, when, then, and. The second and: block after the then: block is used because the unit test actually tests two related actions. First of all, it verifies that the email was indeed sent as in the previous section. This is the line 1 * emailSender.sendEmail(sampleCustomer);. This line is the same as with the previous section. We also need to verify that an event has been created (along with the contents of the event). We employ an and: block at the end of the test to do this. The -> character denotes a Groovy closure. The last line of the test means: - “Verify that the recordEvent()method of the eventRecorderclass was called 1 time, - and use a closure to capture the argument that was used, - and name the argument event, - and verify that the argument had a non null timestampproperty, - and a TYPE.REMINDER_SENTtype property, - and a customerName property equal to “Susan Ivanova”. If all the above are true, the test will succeed. If any of these statements is false, the whole test will fail. Spock is so smart that it can detect the difference between an invocation that has arguments that are similar, but not exactly the same. Let’s assume that we have a bug in our application, and that the timestamp property is not correctly set. Spock will present the following test error: email about late invoice should contain customer details(com.codepipes.mocking.EventCheckSpec) Time elapsed: 0.126 sec <<< FAILURE! org.spockframework.mock.TooFewInvocationsError: Too few invocations for: 1 * eventRecorder.recordEvent({ event -> event.getTimestamp() != null && event.getType() == Event.Type.REMINDER_SENT && event.getCustomerName() == "Susan Ivanova" }) (0 invocations) Unmatched invocations (ordered by similarity): 1 * eventRecorder.recordEvent(com.codepipes.mocking.Event@31198ceb) Here, Spock tells us that, while our method was indeed called once, it was not called with the arguments we requested. Forming Dynamic Responses for Mocks The previous examples of Spock unit tests will cover most of your testing needs. We will now cover some advanced Spock examples that deal with dynamic manipulations of arguments and responses from mocks. Again, Spock is based on Groovy closures for both of these features. If you know your way around Java 8 lambda expressions, then it should be very easy to follow. However, keep in mind that dynamic manipulation of arguments and responses with Spock Let’s see an example where we just want to modify the argument itself. We’ll fact that once the customer is saved using the persist method, its database ID is sent to the logger presents a problem. For this contrived example, the code will work just fine in the real system, as the database will indeed assign an ID to the object as soon as it is saved. How can we replicate this processing in our unit test? The persist method does not return an argument, so we cannot mock it using Spock’s >> syntax. Spock can still create a unit test for this scenario with the following test: public class CustomerDaoSpec extends spock.lang.Specification{ // Class to be tested private CustomerDao customerDao; // Dependencies (will be mocked) private EntityManager entityManager private Logger logger //Test data private Customer sampleCustomer /** * Runs before each test method, like the JUnit Before * annotation */ public void setup(){ customerDao = new CustomerDao(); entityManager = Stub(EntityManager.class) customerDao.setEntityManager(entityManager) logger = Mock(Logger.class) customerDao.setLogger(logger) } public void "customer IDs are logged whenever they are saved in the DB"() { given: "a customer dao that assigns an ID to customer" entityManager.persist( _ as Customer) >> { Customer customer -> customer.setId(123L)} when: "that customer is saved in the DB" customerDao.saveCustomer("Suzan", "Ivanova") then: "the ID is correctly logged" 1 * logger.info("Saved customer with id {}", 123L) } } As with the previous unit tests, we create two fake objects in the setup() method: - The EntityManagerclass is stubbed, and - The Loggerclass is mocked because we need to verify its info()method. The most important line of the whole unit test is the following: entityManager.persist( _ as Customer) >> { Customer customer -> customer.setId(123L)} Let’s break this line into two parts, the one before the >> operator, and the one after. The first part uses the underscore character as an argument. The underscore character is a special character in Spock, and it means “any”. It is used as an argument matcher that can match any value of the argument. The syntax as Customer is another special Spock construct that makes the test a bit more strict by ensuring that the argument is indeed a Customer class. Therefore, the first part of the statement matches the call of the persist() method with any kind of argument that is a Customer. The equivalent matcher in Mockito would be when(entityManager).persist(any(Customer.class). In all the Spock examples we have seen so far, the >> operator means “then return”. In this particular example, the persist() method doesn’t return anything. Therefore, we can think the >> character as “then do”. The second part of the statement is a Groovy closure (denoted by the -> character), and it means “take the customer argument, and execute its setId() method with an argument of 123L”. This is all that is needed to create dynamic responsesin Spock. Mockito would need a special Answer construct here. The last part of the test (the then: block) is the same as we have seen in previous examples. It just verifies that the info() method was executed once with the correct arguments and more specifically with the ID equal to 123 which was stubbed in the when: block. Dynamic Responses Based on Arguments with Spock As a grand finale, we will see an extreme unit test long list of customers. The code here is very simple, and stub that method with the >> operator 20 times to instruct it exactly what output it should send. A more concise way is the following: public class MassUserRegistrationSpec extends spock.lang.Specification{ //Class under test private MassUserRegistration massUserRegistration; //Dependencies (will be mocked) private UserRepository userRepository; private EventRecorder eventRecorder; //Test data private List sampleCustomers; /** * Runs before each test method, like the JUnit Before * annotation */ public void setup(){ sampleCustomers = new ArrayList<>() eventRecorder = Mock(EventRecorder.class) userRepository = Stub(UserRepository.class) } massUserRegistration = new MassUserRegistration(eventRecorder,userRepository); } public void "mass registration of users"() { given: "a list of sample Customers" sampleCustomers.add(new Customer("Susan", "Ivanova")); sampleCustomers.add(new Customer("Lyta", "Alexander")); sampleCustomers.add(new Customer("Vir", "Cotto")); sampleCustomers.add(new Customer("Stephen", "Frankling")); //[...20 customers redacted for brevity...] when: "we register all customers at once" massUserRegistration.massRegister(sampleCustomers); then: "each registration event contains the correct customer details" sampleCustomers.each { sampleCustomer -> 1 * eventRecorder.recordEvent({ event -> event.getTimestamp() != null && event.getType() == Event.Type.REGISTRATION && event.getCustomerName() == sampleCustomer.getFirstName() + " "+ sampleCustomer.getLastName() }) } } } This Spock unit test essentially gathers all the techniques we have seen so far in one masterpiece. It combines simple stubbing, simple mocking, dynamic arguments and argument verification in the same file! Let’s analyze everything in turn. Our class under test is MassUserRegistration and has two dependencies: - Class UserRepository. We will create a stub for it as we use it as a helper class - Class EventRecorder. We will mock it because we want to verify the emission of events for each user registration. In our setup() method we stub UserRepository using dynamic arguments: } The first part before the >> operator matches the saveCustomer() method when any two arguments are passed by employing the underscore character. To make the test a bit more strict we make sure that the arguments are Strings (the as String) syntax. If non-string arguments are passed, the unit test will fail. The second part after the >> operator instructs the stub to create a dynamic response for the two matched arguments. It uses a closure with two argument where the first one is named firstName, and the second one is named lastName. These values are used for the creation of a new Customer object. The combination of these two parts translates to: - Whenever the saveCustomerof the userRepositoryobject is called with any Strings as arguments, - name those arguments firstNameand - create a new Customerobject on the fly using those two strings in the constructor, - concatenate these two strings with a space and assign the result to the fullNameproperty of the customer, - set the sinceproperty to the current date, and - return the Customercreated to the method caller. All these actions will be performed by Spock during the course of the unit test. Regardless of the size of our testing data, the UserRepository mock will always return the correct response to the class under test. In the then: block we peform verification of the events for each customer. First of all, we use the Groovy each iteration that allows us to use a closure for each Customer. This is equivalent to the Java 8 forEach statement. Then, we employ the same argument verification we have seen in the previous section inside the closure. For each customer passed in the recordEvent method, we verify that the event emitted is of type Type.REGISTRATION, that the timestamp property is not null, and that the correct first name and last name were stored.. Continuous Integration for Spock on Semaphore Now that we have our tests, we can start doing continuous integration (CI). The first step is to integrate our project’s repository with Semaphore, a hosted CI service. Semaphore will wait for any pushes to our repository, and will then run our tests for us. Semaphore comes with an included stack of Java tools, including Maven and Gradle, allowing us to set up our project with minimal effort. All that we need to do is add our repository, let Semaphore figure out our build configuration, and we’ll be good to go with little or no tweaking. Summary In this tutorial, we’ve written several unit tests using Spock for both stubbing and mocking. We’ve covered: - How to download and set up Spock via Maven, - The advantages Spock brings when it comes to testing Java code - Basic stubbing with the >>operator, - Basic verification with the N * mockedObject.method(arguments)syntax, - Advanced verification of arguments using Groovy closure and the underscore character, - Advanced dynamic manipulation of arguments, and - Advanced dynamic responses based on arguments. Where to Go from Here We’ve seen Spock’s most important mocking features, but there are several more to explore: - There are more ways to restrict argument matchers, - The number of verifications can also be described using Groovy ranges, - Stubs can be instructed to throw exceptions (for negative testing scenarios), - You can also verify the event order as they happen in a unit test using multiple then:blocks, - You can stub multiple calls to the same method to return different results for each subsequent time, and - Spock also supports Spies, which is another advanced type of fake objects. If you have any questions and comments, feel free to leave them in the section below. Also, feel free to share this tutorial with anyone you think might benefit from it.
https://semaphoreci.com/community/tutorials/stubbing-and-mocking-in-java-with-the-spock-testing-framework
CC-MAIN-2019-47
refinedweb
5,231
54.52
4. App Integration¶ It is pretty easy to integrate your own Django applications with django CMS. You have 7 ways of integrating your app: Statically extend the menu entries Attach your menu to a page. Attach whole apps with optional menu to a page. Modify the whole menu tree Display your models / content in cms pages Add Entries to the toolbar to add/edit your models Templatetags and other CMS-provided utilities 4.3. App-Hooks¶ Whenever you add or remove an apphook, change the slug of a page containing an apphook or the slug if a page which has a descendant with an apphook, you have to restart your server to re-load the URL caches. import * urlpatterns = patterns('sampleapp.views', url(r'^$', 'main_view', name='app_main'), url(r'^sublevel/$', 'sample_view', name='app_sublevel'), ) The main_view should now be available at /hello/world/ and the sample_view has the url /hello/world/sublevel/. Note CMS pages below the page to which the apphook is attached to, can be visible, provided that the apphook urlconf regexps are not too greedy. From a URL resolution perspective, attaching an apphook works in same way than inserting the apphook urlconf in the root urlconf at the same path as the page is attached to. Note All views that are attached like this must return a RequestContext instance instead of the default Context instance. 4.3.2. Attaching an Application multiple times¶ If you want to attach an application multiple times to different pages you have 2 possibilities. - Give every application its own namespace in the advanced settings of a page. - Define an app_name attribute on the CMSApp class. The problem is that if you only define a namespace you need to have multiple templates per attached app. For example: {% url 'my_view' %} Will not work anymore when you namespace an app. You will need to do something like: {% url 'my_namespace:my_view' %} The problem is now if you attach apps to multiple pages your namespace will change. The solution for this problem are application namespaces.) Note If you do provide an app_label, then you will need to also give the app a unique namespace in the advanced settings of the page. If you do not, and no other instance of the app exists using it, then the ‘default instance namespace’ will be automatically set for you. You can then either reverse for the namespace(to target different apps) or the app_name (to target links inside the same app). If you use app namespace you will need to give all your view context a current_app: def my_view(request): current_app = resolve(request.path).namespace context = RequestContext(request, current_app=current_app) return render_to_response("my_templace.html", context_instance=context) Note You need to set the current_app explicitly in all your view contexts as django does not allow an other way of doing this. You can reverse namespaced apps similarly and it “knows” in which app instance it is: {% url myapp_namespace:app_main %} If you want to access the same url but in a different language use the language template tag: {% load i18n %} {% language "de" %} {% url myapp_namespace:app_main %} {% endlanguage %}): current_app = resolve(request.path).namespace reversed_url = reverse('myapp_namespace:app_main', current_app=current_app) ... Or, if you are rendering a plugin, of the context instance: class MyPlugin(CMSPluginBase): def render(self, context, instance, placeholder): # ... current_app = resolve(request.path).namespace reversed_url = reverse('myapp_namespace:app_main', current_app=current_app) # ... 4.3.3. Automatically restart server on apphook changes¶ As mentioned above, whenever you add or remove an apphook, change the slug of a page containing an apphook or the slug if a page which has a descendant with an apphook, you have to restart your server to re-load the URL caches. To allow you to automate this process, the django CMS provides a signal cms.signals.urls_need_reloading which you can listen on to detect when your server needs restarting. When you run manage.py runserver a restart should not be needed. Warning This signal does not actually do anything. To get API you need a request for the signal to fire. 4.5. Custom Plugins¶. 4.6. Toolbar¶ Your app might also want to integrate in the Extending the Toolbar to provide a more streamlined user experience for your admins. 4.7. Working with templates¶ Application can reuse cms templates by mixing cms templatetags and normal django templating language. 4.7.1. static_placeholder¶ Plain placeholder cannot be used in templates used by external applications, use static_placeholder instead. 4.7.2. CMS_TEMPLATE¶ New in version 3.0. CMS_TEMPLATE is a context variable available in the context; it contains the template path for CMS pages and application using apphooks, and the default template (i.e.: the first template in CMS_TEMPLATES) for non-CMS managed urls. This is mostly useful to use it in the extends templatetag in the application templates to get the current page template. Example: cms template {% load cms_tags %} <html> <body> {% cms_toolbar %} {% block main %} {% placeholder "main" %} {% endblock main %} </body> </html> Example: application template {% extends CMS_TEMPLATE %} {% load cms_tags %} {% block main %} {% for item in object_list %} {{ item }} {% endfor %} {% static_placeholder "sidebar" %} {% endblock main %} CMS_TEMPLATE memorizes the path of the cms template so the application template can dynamically import it. 4.7.3. render_model¶ New in version 3.0. render_model allows to edit the django models from the frontend by reusing the django CMS frontend editor.
http://docs.django-cms.org/en/develop/extending_cms/app_integration.html
CC-MAIN-2014-15
refinedweb
878
52.7
In this series, we'll build a web application from scratch with Laravel—a simple and elegant PHP web framework. First up, we'll learn more about Laravel and why it's such a great choice for your next PHP-based web application. web application framework that describes itself. - Elegant—most of Laravel's functions work seamlessly with very little configuration, relying on industry-standard conventions to lessen code bloat. - Well-documented—Laravel's documentation is complete and always up-to-date. The framework's creator makes a point of updating the documentation before releasing a new version, ensuring that people who are learning the framework always have the latest documentation. What Makes Laravel Different? As with any PHP framework, Laravel boasts a multitude of functions that differentiate it from the rest of the pack. Here are some, which I feel are the most important (based on the Laravel documentation). Packages Packages are to Laravel as PEAR is to PHP; they are add-on code that you can download and plug into your Laravel installation. Laravel comes with a command-line tool called Artisan, which makes it incredibly easy to install bundles. We all know the importance of web security in this modern digital era. One of my favorite Laravel Packages, called Spatie, adds a useful tool to Laravel that lets you define roles and permissions in your application. In essence, it lets you specify which users have access to what resources. Other very useful Laravel packages include Laravel Mix (a webpack front-end build tool), Eloquent-Sluggable (for making slugs), and Laravel Debugbar (for debugging). Eloquent ORM The Eloquent ORM is the most advanced PHP ActiveRecordimplementation members' that creates a users table in a database, taken from the Laravel documentation: Schema::table('users', function($table) { $table->create(); $table->increments('id'); $table->string('username'); $table->string('email'); $table->string('phone')->nullable(); $table->text('about'); $table->timestamps(); }); Migrations are defined inside a migration PHP file. These files go inside the app/database/migration folder in a Laravel project. Typically, a migration file follows the naming convention: 2022_05_23_000000_create_users_table.php, where 2022_05_23 is the date and create_users_table is the type of migration. Running the migration above will create a users table consisting of the specified columns inside your chosen database. Each column is assigned a type using the type methods (see a complete list in the official docs). To create a database migration, use the artisan utility as follows: php artisan migrate You can also perform more granular tasks on your table like adding or removing a column, reordering the columns, seeding data, and so on. Here's an example that adds the location column to the existing users table: Schema::table('users', function (Blueprint $table) { // Add location after the id column in the table $table->string('location')->after('id'); }); The file for this migration would follow almost the same naming convention discussed earlier. The only difference would be in the migration name, which would go like: add_location_column_to_users_table. Seeding When developing an application, it's important that you test the functionality to see if the app is working as intended. Seeding allows you to populate your tables with fake data en masse, for testing purposes. All seeders inside a project go in the app/database/seeders directory. To generate a seeder, use the artisan utility as follows: php artisan make:seeder UserSeeder Here's a basic example that populates the users table with some autogenerated data, from the docs: DB::table('users')->insert([ 'name' => Str::random(10), 'email' => Str::random(10).'@gmail.com', 'password' => Hash::make('password'), ]); You can use model factories to generate large amounts of database records at a time. This basic example creates 50 posts for a user inside this database: Post::factory() ->count(50) ->belongsToUser(1) ->create(); Unit-Testing TestCase class, like so: class MyUnitTest extends TestCase { public function somethingShouldBeTrue() { $this->assertTrue(true); } } To run your Laravel application's tests, let's, again, use the artisan command-line utility: php artisan test That command will run all the tests that are found within the app/tests/unit directory of your Laravel application. Let's Build a To-Do Application With Laravel Now that we know more about Laravel, it's time to get hands-on by building a web application with it from scratch. We'll build a to-do application that allows us to post items to the database. I'll also include the functionality to mark them once completed. When done, it will look like this: In the process, we'll learn about the different concepts and features of Laravel like routing and controllers, as well as MySQL and, of course, the Blade templating language. With that in mind, let's dive in! Installing Laravel composer create-project laravel/laravel my-app After the application has been created, cd into my-app and start your development server: cd my-app php artisan serve Now we're done setting up the environment. After some time, you should be able to access your Laravel development server at. Setting Up the Application At this point, Laravel has scaffolded a working framework for you. You'll find a host of folders and files inside your root project folder. We won't go over all of these folders—instead, we'll focus on the most important ones. First, you have the app folder. This folder contains the Models and Controllers, amongst others. Next you have the database folder, which contains the migrations, factories, and seeders. resources is where all the front-end code will go, and specifically in here we find the view folder, where we'll create the view of our application using Blade templates. Finally, routes will contain all of our application routes. Inside routes/web.php, we'll define the web routes of our application. Now that we have a basic understanding of the framework, let's create and serve our first page. By default, Laravel sets up a starter template at resources/views/welcome.blade.php, which is what we see at. This is a Blade template, not HTML. Whenever we modify that file, the changes are reflected in the browser. You can modify yours and see the changes in effect. First, we'll bring Bootstrap CSS into our project by embedding its CDN link in the <head> tag of our welcome.blade.php file: <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Bootstrap CDN --> "> </head> Then we'll create a basic Bootstrap CSS form for our to-do layout: <form method="post"> Hooking Up the Database (MySQL) MySQL is a popular relational database, similar to Microsoft SQL Server and Oracle. It's used by many web applications to create relational datastores where the records relate to one another. You can get MySQL via popular distributions like WAMPServer and XAMPP. Create a new database in your local MySQL installation and name it todo. In the following section, we'll create and migrate a table comprising some columns to this database. Once you have your MySQL server set up, simply open the .env file in your project root folder and pass your database name to DB_DATABASE, like so: DB_DATABASE=todo Creating a Table and Adding Columns (Models and Migrations) Earlier we learnt that migrations are simply a way to execute changes to our database tables. They allow us to create tables and add or remove columns right from our application. But in relation to databases, there is another important concept we must learn about, and that is Models. Models allow you to retrieve, insert, and update information in your data table. Typically, each of the tables in a database should have a corresponding “Model” that allows us to interact with that table. Now we'll create our first model, which is ListItem. To do so, we run the following artisan command: php artisan make:model ListItem -m The -m flag creates a migration file along with the model, and this migration file will go inside the app/database/migrations folder. Next, we'll modify the migration file and add the columns we want in our list_items table: <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateListItemsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('list_items', function (Blueprint $table) { $table->id(); $table->string('name'); $table->integer('is_complete'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('list_items'); } } Here we are adding the fields id, name, and is_complete. table->timestamps() will automatically generate two fields in our database: created_at and updated_at. Run the following to migrate the table and its columns to your database: php artisan migrate Setting Up Routes In Laravel, all requests to the application are mapped to specific functions or controllers by Routes. They are responsible for instructing the application where URLs go. For example, if we wanted to render the home view file, we could create the following route within web.php, found inside the routes folder: Route::get('/home', function() { return view('home'); }) Alternatively, if we instead needed to route to a Controller, say, the HomeController.php controller, we might do something like this: Route::controller('HomeController'); This would route to the HomeController.php controller file. Any action method there will be made available as well. To take things further, you can specify a particular method to handle that route: Route.get([HomeController::class, 'index']) Your HomeController.php file will basically look like this: <?php namespace App\Http\Controllers; class HomeController extends Controller { public function index() { } } Don't worry, we'll learn more about controllers soon. Basically, what we did is specify the index method inside the HomeController class to be called when a user navigates to localhost:8000/home. In addition, a route name, home.index, is assigned to the route. This is especially useful if you're using a templating language like Blade (as we'll see soon). Sometimes, two routes may share the same path (e.g. /thread), but one is GET and the other is POST. In such cases, you can distinguish both by using different route names, preventing mix-ups. An important thing to note here is that by default, Laravel does not route to the controllers as other PHP frameworks do. This is by design. By doing so, we can actually create simple pages without the need to create a controller for it. For example, if we wanted to create a static Contact Us page that just lists contact information, we can simply do something like this: Route::any('contact-us', function() { return view('contact-us'); }) This will route and render the resources/views/contact-us.blade) - Middleware—this lets us run some functionality before or after a route is executed, depending on the route that was called. For example, we can create auth middleware that will be called before all routes, except the home and about routes. For the purposes of this web application, though, we only need two routes: the first route just shows the welcome page along with the to-do list, and the second route will be called when we submit a new to-do item using the form. Open up the web.php file and add the following routes: Route::get('/', [TodoListController::class, 'index']); Route::post('/saveItem', [TodoListController::class, 'saveItem'])->name('saveItem'); For the second, we set the method to post to indicate that we are handling a POST request. When this route is triggered, we want to call the saveItem method inside the TodoListController (we'll create it soon). A route name is also set. We'll use this name when making a POST request from the form. Next, we import the controller on top of the file: use App\Http\Controllers\TodoListController; Time to learn about controllers and create our very own TodoListController. Creating Controllers Typically, you define all of the logic for handling a route inside a controller. Controllers in Laravel are found inside the app/Http/Controllers folder. To create a controller, we use the artisan utility. Remember that TodoListController whose method I said was going to handle to POST request to our saveItem route? It's time to create it. Run the following command on your terminal: php artisan make:controller TodoListController This will create a TodoListController.php file inside the app/Http/Controllers folder. By convention, we'll want to name the file something descriptive that will also be the name of the controller class, which is why I went with that name. In this controller class, we'll define two methods: index and saveItem. <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\ListItem class TodoListController extends Controller { public function index() { return view('welcome', ['listItems' => ListItem::all()]); } public function saveItem(Request $request) { $item = new ListItem; $item->name = request->name; $item->is_complete = 0; $item->save(); return view('welcome'); } } First, we import two Models: Request and ListItem. Request gives us all the information about the HTTP request. ListItem is the model we created earlier for saving a to-do list item in our database. The index method returns the welcome view and passes all the list items from the database. That way, we can display them on the page if there is any. The saveItem method is for saving a to-do item to our database. Here we create a new ListItem instance. We then set its name to the name from the request payload, and set is_complete to 0 (represents false or "no"). Finally, we return the welcome page. For this to work, all we have to do now is modify our welcome.blade.php file, which is where we'll be making a request from and showing the to-do list. For now, let's learn more about controllers. More Controller Fun Middleware There's a lot more that we can do with controllers, rather than them just being gateways to the view files. For example, remember the Middleware feature that I mentioned earlier in the routes section? Aside from being attached to specific Routes, we can also attach them to specific controllers! Simply create a __constructor method for the controller, and set up the middleware there. For example, if we need to ensure that a user is authenticated for all the methods in a controller, we can make use of our example auth middleware: public function __construct() { $this->middleware('auth'); } This will call the auth middleware on all actions in this controller. If we want to target some specific actions, we can refer to the only method, like so: public function __construct() { $this->middleware('auth')->only('index'); // Or for only index and store actions $this->middleware('auth')->only(array('index, 'store')); } We can alternatively use the except method to implement the middleware on all actions, except a few: public function __construct() { $this->middleware('auth')->except('store'); } Notice how expressive this code is? We can even target a specific HTTP verb: public function __construct() { $this->middleware('auth')->except('store')->on('post'); } The Base Controller Most, if not all, controllers extend the Controller. This gives us a way to define methods that will be the same for all our controllers. For example, if we need to create a logging method to log any controller request: class Controller extends BaseController {. If you want to learn more, this section of Laravel's documentation provides detailed information about controllers. Now let's hook up our view to our already-implemented route and controller. Creating the need to have a .blade.phpextension. This tells Laravel to use the engine on the view file. Now, back in our welcome.blade.php file, we do two things: - We use forelse to loop through our to-do list and show them. If there is no item (i.e. we haven't saved any item yet), we instead show No Items Saved Yet. - We set the route to POST to. We'll make our form work by adding a CSRF token to it. This is a security measure you take whenever you're posting data with forms. Replace the contents of div.container with the following markup: @forelse ($listItems as $listItem) <div class="alert alert-primary" role="alert"> <span>Item: {{ $listItem->name }}</span> <form method="post" action="{{ route('markAsComplete', $listItem->id) }}"> {{ csrf_field() }} <button type="submit" class="btn {{ $listItem->is_complete ? 'btn-success' : 'btn-danger' }}" > {{ $listItem->is_complete ? 'Completed' : 'Mark as Complete' }} </button> </form> </div> @empty <div class="alert alert-danger" role="alert"> No Items Saved Yet </div> @endforelse <form method="post" action="{{ route('saveItem') }}"> {{ csrf> Notice how we used the is_complete value of each list item to decide the color of the button and text content. We'll come to how we change it very soon. Also, we used the route() helper function provided by Blade to define a form submit action; we simply route to saveItem (that we created earlier) when this form is submitted. To test this out, navigate your browser to localhost:3000 to see the welcome page. Now type a to-do item in the text input and submit. The new item will be shown on the page. Also, go to your MySQL database and check the list_items table to confirm. While you're there, you'll notice that all the items have their is_complete column set to 0. One last thing we'll do is add the functionality for marking a to-do list as Completed. If you recall, we already added the button for marking a to-do item as completed in the view. Now we need to define the route. Go to your web.php and add the following: Route::post('/markAsComplete/{id}', [TodoListController::class, 'markItem'])->name('markAsComplete'); Because we need to know which list item is being marked, we pass its id to the markItem method in the controller since all items had an id column and we passed the id to route() inside the view. Next, we define the method in the controller: public function markItem($id) { $item = ListItem::find($id); $item->is_complete = 1; $item->save(); return redirect('/'); } Now refresh your page at and mark any item. The button colour and text content will change. Now that we have our main layout, let's see how to include other sections inside it. @section and @yield Sections let us inject content into the main layout from within a view. To define which part of our main layout is a section, we surround it with @section and @yield_section Blade tags. Supposing we want to create a navigation section and inject it into our main layout, welcome.blade.php. We create a new blade file and name it nav.blade.php in. In this file, we create a section called Navigation and define the markup for this section: @section('navigation') <li><a href="about">About</a></li> <li><a href="policy">Policy</a></li> <li><a href="app">Mobile App</a></li> @endsection At this point, the navigation simply exists. To actually inject it inside the main layout, we use @yield. @yield The @yield function is used to bring a section into a layout file. To yield a section, we need to pass the correct path to that file inside the @yield function. To define the path, the starting point is the views folder. For example, assuming that we created nav.blade.php inside the views folder, this is how we bring it into welcome.blade.php: <div class="container"> <div class="navigation"> @yield('nav') </div> <!-- Other Markups --> </div> Importing Assets With @section and @yield With @section and @yield, you can also load CSS and JS files to a page. This makes it possible to organize your application's layout in the best possible manner. To demonstrate, I'll create a third blade file and name it styles.blade.php. Inside this file, I'll bring in the stylesheet used in my app: @section('navigation') "> <style> form { display: flex; align-items: center; justify-content: center; } .container { margin-top: 8rem; } .alert { text-align: center; display: flex; align-items: center; justify-content: space-between; } </style> @endsection Instead of writing the styles directly in welcome.blade.php, I can simply do this instead: <head> <!-- Styles --> @yield('styles') </head> There is so much more to learn about Blade. If you're interested in exploring further, be sure to check out the documentation. Conclusion After reading this tutorial, you've learned: - What Laravel is and how it's different from other PHP frameworks. - Where to download Laravel and how to set it up. - How Laravel's Routing system works. - How to create your first Laravel Controller. - How to create your first Laravel View. - How to use Laravel's Blade Templating Engine. Laravel is truly an amazing framework. It's fast, simple, elegant, and so easy to use. It absolutely merits being considered as the framework to use for your next project. The Laravel category on Envato Market is growing fast, too. There's a wide selection of useful scripts to help you with your projects, whether you want to build an image-sharing community, add avatar functionality, or much more.
https://code.tutsplus.com/tutorials/building-web-applications-from-scratch-with-laravel--net-25517?ec_unit=translation-info-language
CC-MAIN-2022-40
refinedweb
3,511
55.03
The Binary Search It is possible to take greater advantage of the ordered list if we are clever with our comparisons. In the sequential search, when we compare against the first item, there are at most more items to look through if the first item is not what we are looking for.. If the item we are searching for is greater than the middle item, we know that the entire lower half of the list as well as the middle item can be eliminated from further consideration. The item, if it is in the list, must be in the upper half. We can then repeat the process with the upper half. Start at the middle item and compare it against what we are looking for. Again, we either find it or split the list in half, therefore eliminating another large part of our possible search space. The diagram below shows how this algorithm can quickly find the value 54. This algorithm is a great example of a divide and conquer strategy. Divide and conquer means that we divide the problem into smaller pieces, solve the smaller pieces in some way, and then reassemble the whole problem to get the result. When we perform a binary search of a list, we first check the middle item. If the item we are searching for is less than the middle item, we can simply perform a binary search of the left half of the original list. Likewise, if the item is greater, we can perform a binary search of the right half. Either way, this is a recursive call to the binary search function passing a smaller list. An implementation of recursive binary search in Python may look like this: def binary_search(alist, item): if not alist: # list is empty -- our base case return False midpoint = len(alist) // 2 if alist[midpoint] == item: # found it! return True if item < alist[midpoint]: # item is in the first half, if at all return binary_search(alist[:midpoint], item) # otherwise item is in the second half, if at all return binary_search(alist[midpoint + 1:], item) testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42] binary_search(testlist, 3) # => False binary_search(testlist, 13) # => True Analysis of Binary Search To analyze the binary search algorithm, we need to recall that each comparison eliminates around half of the remaining items from consideration. What is the maximum number of comparisons this algorithm will require to check the entire list? If we start with n items, approximately items will be left after the first comparison. After the second comparison, there will be approximately . Then , , and so on. How many times can we split the list? This table helps us to see the answer: When we split the list enough times, we end up with a list that has just one item. Either that is the item we are looking for or it is not. Either way, we are done. The number of comparisons necessary to get to this point is i where . Solving for i gives us . The maximum number of comparisons is logarithmic with respect to the number of items in the list. Therefore, the binary search is . One additional analysis issue needs to be addressed. In the solution shown above, the recursive call, binary_search(alist[:midpoint], item) uses the slice operator to create the left half of the list that is then passed to the next invocation (similarly for the right half as well). The analysis that we did above assumed that the slice operator takes constant time. However, we know that the slice operator in Python is actually . This means that the binary search using slice will not perform in strict logarithmic time. Luckily this can be remedied by passing the list along with the starting and ending indices. We leave this implementation as an exercise. Even though a binary search is generally better than a sequential search, it is important to note that for small values of n, the additional cost of sorting is probably not worth it. In fact, we should always consider whether it is cost effective to take on the extra work of sorting to gain searching benefits. If we can sort once and then search many times, the cost of the sort is not so significant. However, for large lists, sorting even once can be so expensive that simply performing a sequential search from the start may be the best choice.
https://bradfieldcs.com/algos/searching/the-binary-search/
CC-MAIN-2018-26
refinedweb
737
69.52
Doing the OAuth dance with style using Flask, requests, and oauthlib. Currently, only OAuth consumers are supported, but this project could easily support OAuth providers in the future, as well. The full documentation for this project is hosted on ReadTheDocs, including the full list of supported OAuth providers, but this README will give you a taste of the features. InstallationInstallation Just the basics: $ pip install Flask-Dance Or if you're planning on using the SQLAlchemy storage: $ pip install Flask-Dance[sqla] QuickstartQuickstart If you want your users to be able to log in to your app from any of the supported OAuth providers, you've got it easy. Here's an example using GitHub: from flask import Flask, redirect, url_for from flask_dance.contrib.github import make_github_blueprint, github app = Flask(__name__) app.secret_key = "supersekrit" blueprint = make_github_blueprint( client_id="my-key-here", client_secret="my-secret-here", ) app.register_blueprint(blueprint, url_prefix="/login") @app.route("/") def index(): if not github.authorized: return redirect(url_for("github.login")) resp = github.get("/user") assert resp.ok return "You are @{login} on GitHub".format(login=resp.json()["login"]) If you're itching to try it out, check out the flask-dance-github example repository, with detailed instructions for how to run this code. The github object is a context local, just like flask.request. That means that you can import it in any Python file you want, and use it in the context of an incoming HTTP request. If you've split your Flask app up into multiple different files, feel free to import this object in any of your files, and use it just like you would use the requests module. You can also use Flask-Dance with any OAuth provider you'd like, not just the pre-set configurations. See the documentation for how to use other OAuth providers. StoragesStorages By default, OAuth access tokens are stored in Flask's session object. This means that if the user ever clears their browser cookies, they will have to go through the OAuth dance again, which is not good. You're better off storing access tokens in a database or some other persistent store, and Flask-Dance has support for swapping out the token storage. For example, if you're using SQLAlchemy, set it up like this: from flask_sqlalchemy import SQLAlchemy from flask_dance.consumer.storage.sqla import OAuthConsumerMixin, SQLAlchemyStorage db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) # ... other columns as needed class OAuth(OAuthConsumerMixin, db.Model): user_id = db.Column(db.Integer, db.ForeignKey(User.id)) user = db.relationship(User) # get_current_user() is a function that returns the current logged in user blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=get_current_user) The SQLAlchemy storage seamlessly integrates with Flask-SQLAlchemy, as well as Flask-Login for user management, and Flask-Caching for caching. Full DocumentationFull Documentation This README provides just a taste of what Flask-Dance is capable of. To see more, read the documentation on ReadTheDocs.
https://libraries.io/pypi/Flask-Dance
CC-MAIN-2019-47
refinedweb
490
58.58
Five Minute Cloud Lambda Function Building a serverless function is easy. AWS calls their serverless functions Lambdas. Let’s build on a serverless function with Python on AWS. Join the DZone community and get the full member experience.Join For Free Serverless computing is pretty cool. You need something done in the cloud. It might be storing a GPS location. Or pulling some from a DB based on a few query parameters. But building a complete server instance would be overkill. You just need an API endpoint to accept a query and spit back a result. You need a serverless function. Building a serverless function is easy. Let’s build on a serverless function with Python on AWS. AWS calls their serverless functions Lambdas, so I’ll be using those terms interchangeably throughout this tutorial. AWS Account First, you need an AWS account. If you don’t have one, don’t start your timer yet. Creating the account may be harder than creating a Lambda. Log in to the AWS Console If you’re up and running with an AWS account, you can go right to the console. On my console, Lambda appears near the top because I recently used it. However, you can click on View all services to find it if you need to. It’ll be right near the top, under Compute. Click on Lambda, and let’s create a service. New Lambda This will take you to your list of Lambdas. Here’s what mine looks like: I’ve got an old function from an Alexa skill hanging around. If you’ve never created a Lambda before, you’ll see an empty list. Click the Create function button. Now, it’s finally time to define a function. Here are your choices: - Select Author from scratch. - Give your function a name. - Pick Python 3.9 from the Runtime drop-down. This will give us a single Python function. AWS will call it when a web client calls our Lambda. However, we need to set up one more thing to make the function callable from standard web clients. Click Advanced settings. Check the box for Enable function URL. This gives you function a web address. Next, select NONE for Auth type. As the warning says, this is not a secure configuration, and you shouldn’t use it with functions that access secure data or can be used as a vector for attacking other services. Since this will only be a demo app, it’s fine for now. Click Create function and we’ll look at our creation and take it out for a test drive. Here’s what your function info page should look like: Test Drive On the right-hand side, you can see your function’s public URL. Click it. This sends a GET request to your function from the browser: Technically, we could stop the clock here. You’ve created a serverless function. But let’s take it one step further and make it process a more complicated request. Postman I’m going to use Postman for this next part. If you don’t have an account yet, go ahead and create it. Everything we’ll do here works with a free login. Let’s point Postman at the new function. Create a new request. Paste your function URL in the URL section and click Send. Postman displays the result at the bottom. So, we’ve used Postman to make the same request as the browser. Now let’s have some fun. Posting JSON Data to a Lambda Function If we want to make our function do something interesting, we need to send it some data. Switch your request type to POST and give your request a body. Now, if we send this, nothing will change. We need to make some code changes. Here’s the code: import json def lambda_handler(event, context): request = event['body'] request_obj = json.loads(request) return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json' }, 'body': "{}, {} {}!".format(request_obj['Greeting'], request_obj['Title'], request_obj['Name']) } When you call a Lambda from a function URL, the request data is included in the event object as the body field. Since it’s a raw string, we need to pull it out of the event and convert it to an object with json.loads. Then we can access the fields and use them to build a new string. Paste this code in and Deploy it. Now, send the new request. It works! You built a Lambda. So, you can see that serverless functions in AWS in five minutes are easy to build. In the next tutorial, we see what else they can do. Published at DZone with permission of Eric Goebelbecker, DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/five-minute-cloud-lambda-function
CC-MAIN-2022-40
refinedweb
799
86.1
It will be eaiser if you just make the animation in another program example in a frame and then you just take a screenshoot of the frame and upload it to .pdf file. Type: Posts; User: magnus110498 It will be eaiser if you just make the animation in another program example in a frame and then you just take a screenshoot of the frame and upload it to .pdf file. Okay i will do thank you for you time :D[COLOR="Silver"] --- Update --- I still have the problem but after i look in the code i get this.... But i dont understand it i think. ... Ohh sorry forgot to say; "maybe it could be a fail with the ServerGUI.class, because the example i gave before is in the same program". Okay, i just don't understand when i have used this method before, and it works how it cant work now :( Here is a picture there watch the library file: 3125 Here is a example there working: ... But i have use the method before. My library? You mean Netbeans? Hey guys, i try to get my program to open a new GUI window with click on the button. private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { ... You can also use booth off them. But swing is best to painting and graphics things. Hey you say there is nothing with java in minecraft? Minecraft is made in java... The error you get for you server when it not work is a java error :D Can you write the error to me? Have you other plugins on you server? Give me some more info and i sure i can find the problem :D I also have a server :) --- Update --- Somethings in you... Can you plzz write the error :D You know how you connect to a server? --- Update --- And who database you will used? --- Update --- I think when you see this code you have a ide how you can do the :-) Maybe you should also learn little about HTML :-) Or you can buy or find a book about java. And then learn more. My book have learn me all about java, but the book is on danish. Try to find a book on... Class.forName("oracle.jdbc.driver.OracleDriver"); More info about mysql database. You need to create a swing or awt to you project. Example code: import java.awt.*; import javax.swing.*; public class SwingVindue extends JFrame { public void paint(Graphics g) { ... I know some books, but they on danish :( Check this website if you will learn much more about programming and computers and much more. The wiew presentations from the university. --- Update --- omg here is the link: ...
http://www.javaprogrammingforums.com/search.php?s=75582d91a6cbde40ab4c4d8ae6ba32e8&searchid=1665640
CC-MAIN-2015-32
refinedweb
448
82.75