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
This is a discussion on Re: Disposal of a misleading M_TRYWAIT - FreeBSD ; On Sat, 22 Mar 2008, Sam Leffler wrote: >> They have been the same allocator for some time now. It makes more sense >> for them to use the same flags. > > We made a decision a while back ... On Sat, 22 Mar 2008, Sam Leffler wrote: >> They have been the same allocator for some time now. It makes more sense >> for them to use the same flags. > > We made a decision a while back to not use malloc flags for mbuf routine > arguments. There are even assertions to verify it. Changing the flag names > however would be a painful change for little gain. However, this isn't just a search and replace patch on flag names. M_TRYWAIT in fact does a Yoda suggests -- it doesn't "try", it just "does", and as a result none of the intermittently applied NULL-checking for M_TRYWAIT return paths can ever be executed. Hence the are never tested, and new code is turning up that makes the assumption that these paths will never see failure. A significant part of Ruslan's patch is improving consistency in error handling by making all code consider the wait case unable to fail, and there's nothing quite like removing unused exceptional case handling to make network code easier to read. I would also be fine with a proposal that replaces the existing M_DONTWAIT / M_TRYWAIT with mbuf allocator specific flags that read FOO_WAIT and FOO_NOWAIT (be it the same as in Dragonfly, MB_WAIT and MB_NOWAIT or otherwise). It's certainl true that in other cases, we've tried hard to have allocator wrappers with enhanced functionality use their own flag namespace -- SF_WAIT, etc, but since the mbuf allocator really is UMA these days, I am also alright with using the UMA/malloc flags. Robert N M Watson Computer Laboratory University of Cambridge _______________________________________________ freebsd-arch@freebsd.org mailing list To unsubscribe, send any mail to "freebsd-arch-unsubscribe@freebsd.org"
http://fixunix.com/freebsd/367169-re-disposal-misleading-m_trywait.html
CC-MAIN-2014-41
refinedweb
332
59.84
I just need to make sure that the snippet of code is correct. I don't have all the code as I'm still writing it. If it's possible I need help on the assignment. Maybe clues as to how to do it and maybe point to where I can find the answer. I'll add code as I finish it. 1st snippet. 1. A constructor which accepts a suit and a value and, if these are acceptable, initializes the instance variables accordingly. If the supplied values are not acceptable, default values are used instead. 2. A toString method which returns the card value followed by a space, followed by the suit abbreviation in parentheses. For example, the ace of spades would be A (S). If the value to be used is not “10”, add an extra trailing space. This will allow a printout of the whole deck to line up nicely in rows and columns since the 10-cards toString result will have an extra character. 3. Methods called isRed and isBlack that return true if the suit of the card is a red one (hearts, diamonds) or a black one (spades, clubs), respectively. 4. A method called isFaceCard that returns true if the card is a 10, jack, queen, king or ace. 5. A method called isPair that takes in a Card object as a parameter and returns true if the calling Card object (this) has the same value as the parameter. 6. A method called equals that returns true if the calling Card and the Card parameter have the same suit and the same value. 7. A method called compareTo that returns the distance between the suits of the calling Card and the Card parameter, but if they are the same suits then it should return the distance between the card values. An easy way to do this is to use the indexOf method (below) for suits or values and subtract the results. 8. Private methods called validSuit and validValue that takes in a String parameter and return true if the given String is in the constant array of card suits or values, respectively. 9. A private method called indexOf that takes in a String parameter and an array of Strings and returns the index in the array where the String parameter is found. If it is not found it should return -1. public class Card { public static final String[] SUITS = { "S", "H", "C", "D"}; public static final String[] VALUES = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",}; public static final String DEFAULT_SUIT= SUIT[0]; public static final String DEFAULT_VALUE= VALUES[0]; private String suit; private String value; public String Card ( String x, String y) { suit = s; value = v; if(v != VALUES) v = DEFAULT_VALUE; if(s != SUIT) s = DEFAULT_SUIT; } public String toString() { String str = v + " " + s; return str; } public boolean isRed() { for(int i = 0; i<SUIT.length;i+=2) return true; } public boolean isBlack() { for(int i = 0; i<VALUE.length;i+=1) return true; } public boolean isFaceCard() { } public boolean equals(Card) { } public int compareTo(Card) { } public boolean isPair(Card) { } private boolean validSuit(Card) { } private boolean validValue ( String z) { } private int indexOf(String a, String[]) { } }
https://www.daniweb.com/programming/software-development/threads/324247/i-need-help-in-hw
CC-MAIN-2017-17
refinedweb
535
67.69
On 10/31/2012 20:01, Jonathan Wakely wrote: > On 31 October 2012 11:23, JonY wrote: >> On 10/31/2012 19:12, Jonathan Wakely wrote: >>> >>> It looks like the workaround is in mingw not in GCC, so is it a >>> problem that it won't be possible to use GCC 4.8 with existing mingw >>> versions, or are users required to use a brand new mingw to use a new >>> GCC? Should that be documented in >>> ? >>> >> >> They are required to use the latest mingw-w64, the problem was that the >> vfswprintf that libstdc++ expects isn't the same as the one MS provides, >> so I've wrote a redirector to use the vsnwprintf, more precisely, the >> mingw C99 compliant __mingw_vsnwprintf. >> >> std::to_wstring and std::to_string work according to some simple tests. > > Excellent, the testsuite should automatically start running the > relevant tests and we should be able to close > > Yes, the correct way would be to check if the prototype given matches the ISO version. MS version has 1 less argument. The workaround is only active when C++11 is used though to maintain compatibility to older code. The actual guard in the mingw-w64: #if defined(__cplusplus) && (__cplusplus >= 201103L) && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF) ...Redirect to ISO C99 compliant adapter with 4 args... #else ...Use MS Version with 3 args... #endif So the tests and checks would just need to use -std=c++11 or gnu++11. >> I guess the current comment about require mingw-w64 trunk at least r5437 >> is OK for the changes page. It should probably note that this change is >> mingw-w64 specific, with w64 as the vendor key. > > i.e. *-w64-mingw* ? Or is *-w64-mingw32 more accurate? (I don't > really know how the mingw target triplets work, sorry!) > In practice, *-w64-mingw32 is used more commonly when specifying triplet, though for flexibility, checking should use *-w64-mingw*. > I'll put something in the changes page later. > > Thanks for fixing this. > Thanks to Paolo for pushing it in too. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: OpenPGP digital signature URL: <>
https://gcc.gnu.org/pipermail/libstdc++/2012-October/038411.html
CC-MAIN-2022-40
refinedweb
356
73.58
WHAT'S IN THIS CHAPTER? Adding products to a basket via AJAX Using the client's cookie to store a summary of the basket contents Utilizing AJAX for the basket detail page when modifying the basket or shipping options In Chapter 11, you enabled a customer to browse for products; this chapter addresses the needs of a customer to store the items they would like to order in a basket. The basket implementation should use AJAX in all of its functionality, in keeping with the rich web 2.0 theme of the product browsing pages. Therefore, you will use AJAX to add, amend, and remove items from a basket, as well as select the dispatch options. A summary of the basket will appear on all product browsing pages, which will be stored in the client's cookie to enable faster page generation Figure 12-1 shows the domain model of the entities involved with the basket functionality. Figure 12-1. FIGURE 12-1 Create a new folder within the Model project named Shipping, and add to it a new class named Courier that inherits from the EntityBase class that you created in the Infrastructure project. using System.Collections.Generic; using Agathas.Storefront.Infrastructure.Domain; namespace Agathas.Storefront.Model.Shipping { public class Courier : EntityBase<int> { private readonly string _name; private readonly IEnumerable<ShippingService> ... No credit card required
https://www.oreilly.com/library/view/professional-aspnet-design/9780470292785/ch12.html
CC-MAIN-2018-47
refinedweb
226
52.19
----------------------------------------------------------- This is an automatically generated e-mail. To reply, visit: ----------------------------------------------------------- Advertising What is the high-level reasoning for making these namespace specific flags, as opposed to clone flags? 3rdparty/libprocess/include/process/subprocess.hpp (lines 338 - 355) <> Can you add a `TODO` here to consider making this `clone_flags` as opposed to `namespaces`? - Joris Van Remoortere On March 31, 2016, 10:22 a.m., Joerg Schad wrote: > > ----------------------------------------------------------- > This is an automatically generated e-mail. To reply, visit: > > ----------------------------------------------------------- > > (Updated March 31, 2016, 10:22 a.m.) > > > Review request for mesos and Joris Van Remoortere. > > > Bugs: MESOS-5071 > > > > Repository: mesos > > > Description > ------- > > Allows namespaces flags to be passed to subprocess. > > > Diffs > ----- > > > > Diff: > > > Testing > ------- > > Tested entire chain see. > > > Thanks, > > Joerg Schad > >
https://www.mail-archive.com/reviews@mesos.apache.org/msg29819.html
CC-MAIN-2017-30
refinedweb
116
52.56
I will post all th changes that I've made in my codes but Plz test it and check my problem .. Cuz I worked with a grad student and we tried but he said everything seems good that must work .. So if u... I will post all th changes that I've made in my codes but Plz test it and check my problem .. Cuz I worked with a grad student and we tried but he said everything seems good that must work .. So if u... I am sorry from asking this but did you test my code and fix the code ? because I tried everything in the layout maneger also i changed everything in setBounds ... I also finish that wile ago... the height and width of the size of the picture. the logo and picture are same sizes width and height ... 140, 166 honestly I couldn't think anymore .. I fix it every single problem im my program except this point .. please hint or so .. I am sorry I could not get it .. even my teacher said i have never used it ... so please if you could give hint or explanation I really appreciate that .. hmmm ... You mean removing the layout and working with X and Y on setBounds ?? I tried it but it seems I'm making something wrong too... .?? Really good point !! Never though about it ?? Please why? The tshirt will not show on the window I just looked at it ... and tried to delete my layout manager to match it with the example .. but my luck today is too bad .. I am sorry my english is lill bad so i have to read once and twice ....... Some examples uses others no.. I tried all of them nothing change except the place of them .. Up or down left or right .. That's all I sat both of their X, Y same numbers ... is not that right ? I don't know any other code that will do the same as i found in google.. your last question i did not quit understand it .. you mean... you mean the 15, 100 ? I tried using the other way which is // Manually set layout the components, and add it. jlayerPane.add(picture, new Integer (1)); jlayerPane.add(logo, new... yes I tried to get from that page what I need ... that page has been opened in my browser since last Thu .. I honestly could not fine the mistake .. maybe because I have been working too much and i... ( X 15, Y 100 ) And the pictures and logos JLabel has been created .. These two Labels has been added to the JLayerPane .. The LayerPane has been created and we sat the the layout of it... If i am not mistaken this line of code ... picture.setBounds(15, 100, picture.getWidth(), picture.getHeight()); logo.setBounds(15, 100, logo.getWidth(), logo.getHeight()); in this line... I followed up again my code line by line and I changed the numbers many times ... I don't think that the problem is the numbers maybe i miss some codes or so ..?? I changed x to 100 and less and... Yes I did .. and I just did it again .. I used JLayerPane as it suppose to be used, however, it keeps giving me the two pictures beside each other... Honestly this error drove me crazy .... I... Sure .. you can delete whatever you want if you want to test the program ... these names are in the drop list box .. I tried to test it in different ways .. you mean that I have used... import java.awt.*; import java.awt.event.*; import java.util.HashMap; import javax.swing.*; public class SmallProgram extends JFrame { // These variables for the main window. Hi .. I am trying to place a picture on top of another one in java .. I have a Tshirt picture which I am going to place it in the center of my GUI Also I have a logo I want to put it on top... Thanks man .. i have been thinking too much and I missed this code of line add(pnlRadioButtons, BorderLayout.NORTH); Any recommendation for my program .. I am designing a small program... package FunGUI; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import... > I was trying to show the button to start handling them .. but nothing show on GUI when its run ?? I added the panel but is there anything that I could do to fix the problem .. Also, I use to... try this first you have to create an int int x = -1; if(!isCharacterPresent(input.charAt(i), noRepeatCharacters, x)) noRepeatCharacters[x] = input.charAt(i); Thanks for replying .. Ok now if I want to get the deposit from the user and update the balance method .. this is what i am stack in .. how can I connect two methods together ??
http://www.javaprogrammingforums.com/search.php?s=37fa3fe3701851471770182cd3969556&searchid=477218
CC-MAIN-2013-20
refinedweb
815
87.01
Next: Blackfin Options, Previous: ARM Options, Up: Submodel Optionsno-interrupts -mcall-prologues -mtiny-stack -mint8 EINDand Devices with more than 128k Bytes of Flash Pointers in the implementation are 16 bits wide. The address of a function or label is represented as word address so that indirect jumps and calls can address any code address in the range of 64k words. In order to faciliate indirect jump on devices with more than 128k bytes of program memory space, there is a special function register called EIND that serves as most significant part of the target address when EICALL or EIJMP instructions are used. Indirect jumps and calls on these devices are handled as follows and are subject to some limitations: EIND. EIND. Notice that startup code is a blend of code from libgcc and avr-libc. For the impact of avr-libc on EIND, see the avr-libc user manual. EINDimplicitely in EICALL/ EIJMPinstructions or might read EINDdirectly. EINDnever changes during the startup code or run of the application. In particular, EINDis not saved/restored in function or interrupt service routine prologue/epilogue. EINDearly, for example by means of initialization code located in section .init3, and thus prior to general startup code that initializes RAM and calls constructors. gsmodifier (short for generate stubs) like so: LDI r24, lo8(gs(func)) LDI r25, hi8(gs(func)) gsmodifiers for code labels in the following situations: gs()modifier explained above. EIND = 0. If code is supposed to work for a setup with EIND != 0, a custom linker script has to be used in order to place the sections whose name start with .trampolinesinto the segment where EINDpoints to. int main (void) { /* Call function at word address 0x2 */ return ((int(*)(void)) 0x2)(); } Instead, a stub has to be set up: int main (void) { extern int func_4 (void); /* Call function at byte address 0x4 */ return func_4(); } and the application be linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script.
http://gcc.gnu.org/onlinedocs/gcc-4.6.3/gcc/AVR-Options.html
CC-MAIN-2014-15
refinedweb
330
61.26
I've been trying past 12h display text in python 3 with tkinter, seemed easy but this is what I've come up with. (Just recently started with python) But there has to be an easier way to display a window and some text inside of it? from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("GUI") self.pack(fill=BOTH, expand=1, command=self.showTxt()) def showTxt(self): text = Label(self, text='Hello world...') text.pack() root = Tk() root.geometry("400x300") app = Window(root) root.mainloop() Try this : from Tkinter import * root = Tk() T = Text(root, height=2, width=30) T.pack() T.insert(END, "Just a text Widget\nin two lines\n") mainloop()
https://codedump.io/share/58uJbpZzrW9H/1/easier-way-to-display-text-in-python3
CC-MAIN-2017-17
refinedweb
132
63.15
This module is similar to pulldom in that it takes a stream of SAX objects and breaks it down into chunks of DOM. The differences are that it works with any DOM implementation meeting the Python DOM conventions, and that it uses simple pattern expressions to declaratively set how the DOM chunks are partitioned, rather than requiring the user to write procedural code for this purpose. This is an updated/fixed version of code that appeared in an column. Discussion This code is just a fix and update to listing 2 in my article "Decomposition, Process, Recomposition" ( ), so read that article for fuller description and usage examples. The code in that article required the user to set up namespace prefix reporting in SAX, but this only works if PyXML is installed. This code has that limitation removed. If you're trying this code with the listings (3 and 4) in the article and you do not have PyXML installed, just delete the line: parser.setFeature(sax.handler.feature_namespace_prefixes, 1) In the set-up code. Updated version of code in Amara XML Toolkit. This class, with some improvements and fixes, is now part of Amara's saxtools: --Uche
http://code.activestate.com/recipes/298343/
crawl-002
refinedweb
197
60.75
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you may not be able to execute some actions. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). I have been in the process of adding a custom menu with actions to the menubar in Sim4Life 4.2.1.3581. The problem now is, that the custom Menu does not seem to properly add the action. Not only does the action not appear in the menu, but the "Menu" property of the action is none-type. Strangely enough, the "Actions"-property of the menu itself does list the test-action. My code is this: import XCoreUI import XCore import testblock App = XCore.GetApp() ChildList = App.Frame.Children for i in range(len(ChildList)): test = ChildList.__getitem__(i) if test.Name == 'menu': break Menubar = ChildList.__getitem__(i) Menu = XCoreUI.Menu('test') subMenu = XCoreUI.Menu('subMenu') Menu.AddMenu(subMenu) Menubar.AddMenu(Menu) TestAktion = XCoreUI.Action('Test') TestAktion.Label = "Test" TestAktion.Name = "Name" TestAktion.Enabled = True Verbindung = TestAktion.OnTriggered.Connect(testblock.main) Menu.AddAction(TestAktion) If anyone has any ideas, i would be gratefull.
https://forum.zmt.swiss/topic/205/creating-a-custom-menu-with-actions
CC-MAIN-2021-17
refinedweb
197
62.95
SDL is the foundation on which a game can be built without much ado. However, SDL is not complete in itself. It just provides certain services that allow the interaction between various components of a game/simulation, as well as the games interaction with the OS, to become seamless. If there are no components to utilize these services, then these services become just proof of concept. In a gaming engine, most of the time, these services are required by the rendering and AI components. From this part onwards I will be concentrating on the rendering component and its interaction with SDL. I will be covering the AI component in the future. Though SDL supports other graphics libraries, its usage with OpenGL is more common. The reason for this is that SDL and OpenGL fit like parts of a puzzle. So most of the time, the rendering component, or the rendering sub-system (I will be using this term from now onwards) of a gaming engine is built upon OpenGL. Hence understanding OpenGL is a must to build a good rendering sub-system. This part and the articles coming in the near future will detail the different aspects of OpenGL along with how SDL helps in creating a good framework for future purposes. The next section will detail the steps necessary in creating a basic application, while the third section will cover the development of a framework using SDL that can be used in the future. In the last section, I will use simple OpenGL routines to test the framework. That is the agenda for this discussion. {mospagebreak title=OpenGL: Basic Steps} Now that I’ve discussed the theory behind OpenGL, let’s see how to put it to use. To draw any shape onto the screen, there are three main steps. They are: - Clearing the screen - Resetting the view - Drawing the scene Of these the third step consists of multiple sub-steps. I’ll cover the details next.: - GL_COLOR_BUFFER_BIT, which indicates the buffers currently enabled for color writing have to be cleared. - GL_DEPTH_BUFFER_BIT, which is used to clear the depth buffer. - GL_ACCUM_BUFFER_BIT, which is used if the accumulation buffer has to be cleared. - GL_STENCIL_BUFFER_BIT, which); Resetting the View The background and the required buffers have been cleared. But the actual model of the image is based on the view. The view can be considered the matrix representation of the image. In order to draw this matrix, it has to be configured as an identity. This is done using glLoadIdentity(). The statement would be: glLoadIdentity(); Drawing the Scene To draw the scene we tell OpenGL to do two things: start and stop the drawing, and issue the drawing commands. Commands to start and stop the drawing are issued through the calls to glBegin() and glEnd(). The glBegin() command takes one parameter, namely the type of shape to be drawn. To draw using three points use GL_TRIANGLES. Use GL_QUADS for points and GL_POLYGON for multiple points. The glEnd() command tells OpenGL to stop the drawing. For example, to draw a triangle the statements would be: glBegin(GL_TRIANGLES); : : glEnd(); The drawing commands come between these commands. Within the drawing commands, vertex data is specified. These commands are of the type glVertex*f() where * corresponds to the number of parameters, either two or three. Each call creates a point and then connects it with the point created with we need to cover about drawing objects with OpenGL. In the next section, these commands will be used to put the SDL-based framework to the test. {mospagebreak title=SDL-Based Framework: Creating and Testing} Up to now I have discussed SDL’s various APIs. Now it’s time to put them together so that working with OpenGL and SDL becomes easy. So here we go. The framework is based upon NeHe’s excellent framework for SDL.net — the .Net port of SDL. First the includes: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <GL/gl.h> // The OpenGL #include <GL/glu.h> // and OpenGL utility #include <SDL.h> // and SDL headers Here are the global variables which save the state of the surface and the program: bool isProgramLooping;//This one is being used to know if the program //needs to be continued or exited SDL_Surface *Screen; Now the common functionalities: initialization, termination and full-screen toggling. bool Initialize(void)// Any Application & User Initialization Code would be here { AppStatus.Visible= true; // When program begins, the // application window: %sn", SDL_GetError() ); return false; } return true; // return true if initialization is successful } void Deinitialize(void) // Any User Deinitialization such as releasing file handles etc has to be performed here { return; } void TerminateApplication(void)// terminate the application { static SDL_Event Q;// This function sends aSDL_QUIT event Q.type = SDL_QUIT;// to the sdl event queue if(SDL_PushEvent(&Q) == -1) // Sending the event { printf("SDL_QUIT event can’t be pushed: %sn", SDL_GetError() ); exit(1); // And Exit } } void ToggleFullscreen(void)// Toggle Fullscreen/Windowed //(Works On Linux/BeOS Only) { SDL_Surface *S; // a surface to point the screen S = SDL_GetVideoSurface(); // gets the video surface if(!S || (SDL_WM_ToggleFullScreen(S)!=1)) // If SDL_GetVideoSurface Fails, Or if cant toggle to fullscreen { printf("Unable to toggle fullscreen: %sn", SDL_GetError() ); // only reporting the error, not exiting } } {mospagebreak title=Adding OpenGL} Next come the OpenGL parts — creating an OpenGL window. In other words, this section deals with initializing OpenGL. But the initialization; }) } I will be discussing the APIs used in the resize function in the next article. Next is the draw function. It also contains the test code: void Draw3D(SDL_Surface *S) // OpenGL drawing code here { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear screen and depth buffer. Screen color has been cleared at init glLoadIdentity(); // reset the modelview matrix glBegin(GL_TRIANGLES); glVertex3f( 0.0f, 1.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 0.0f); glVertex3f( 1.0f,-1.0f, 0.0f); glEnd(); glFlush(); // flush the gl rendering pipelines return; } Now we move on to the main(). It contains the keyboard handling code. It checks for each key press and processes it accordingly. int main(int argc, char **argv) { SDL_Event E; // and event used in the polling process Uint8 *Keys; // a pointer to an array that will // contain the keyboard snapshot Uint32 Vflags; //)// initializing the sdl // library, the video subsystem { printf("Unable to open SDL: %sn", SDL_GetError() );// if sdl can’t //be initialized exit(1); } atexit(SDL_Quit);// sdl’s been inited, now making // sure that sdl_quit will be // called in case of exit() if(!CreateWindowGL(SCREEN_W, SCREEN_H, SCREEN_BPP, Vflags)) // video flags are set, creating the window { printf("Unable to open screen surface: %sn", SDL_GetError() ); exit(1); } if(!InitGL(Screen))// calling the OpenGL init function { printf("Can’t init GL: %sn", SDL_GetError() ); exit(1); } if(!Initialize()) { printf("App init failed: %sn", SDL_GetError() ); exit(1); } isProgramLooping = true; while(isProgramLooping)// and while it’s looping { if(SDL_PollEvent(&E)) { switch(E.type)// and processing it { case SDL_QUIT://check whether it’s a quit event? { isProgramLooping = false; break; } case SDL_VIDEORESIZE:// or it’s a resize event? { ReshapeGL(E.resize.w, E.resize.h); break; } case SDL_KEYDOWN:// check which key has been pressed { Keys = SDL_GetKeyState(NULL); break; } } } Draw3D(Screen); SDL_GL_SwapBuffers(); // and swap the buffers (since double buffering is being used) } Deinitialize(); exit(0); // And finally exit() so calling call sdl_quit return 0; } That brings us to the end of this discussion. This time it was a bit lengthy. But the framework that has been developed will work as the foundation for developing functionalities like lighting, texture mapping, animation and so on. The next topic will be using timers in animating the triangle just drawn. Till next time.
http://www.devshed.com/c/a/Multimedia/Game-Programming-with-SDL-Getting-Started-with-OpenGL/
CC-MAIN-2015-48
refinedweb
1,258
64
BFS and Bi-directional BFS Originally published at on August 18, 2020. Apart from vanilla BFS introduced in Intro to Graph Algorithms — BFS & DFS, there’s another variant of BFS called bi-directional BFS. Instead of searching from source to target, bi-directional BFS starts with the source and the target at the same time, and search the graph simultaneously. The improvement of time complexities is shown as below, as referring to @ Huahua. Let’s take Leetcode 127. Word Ladder as an example. It asks for the shortest transformation from beginWord to endWord, so BFS is the algorithm that we will apply. Before that, we need to construct the graph, i.e., define nodes and edges. The vanilla BFS is as follows: class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: l = len(beginWord) edges = collections.defaultdict(list) for word in wordList: for i in range(l): edges[word[:i]+'*'+word[i+1:]].append(word) q = collections.deque([beginWord]) visited = set([beginWord]) ret = 0 while q: ret += 1 q_len = len(q) for _ in range(q_len): word = q.popleft() if word == endWord: return ret for i in range(l): for e in edges[word[:i]+'*'+word[i+1:]]: if e not in visited: q.append(e) visited.add(e) return 0 For bi-directional BFS, we would initiate two queues/sets containing the beginWord and the endWord accordingly. One small trick is we would expand the smaller queue/set each time. The code is as follows: class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 edges = collections.defaultdict(list) l = len(beginWord) for word in wordList: for i in range(l): edges[word[:i]+'*'+word[i+1:]].append(word) q1 = set([beginWord]) q2 = set([endWord]) visited = set([beginWord,endWord]) steps = 0 while q1 and q2: steps += 1 if len(q1) > len(q2): # expand the smaller queue first q1,q2 = q2,q1 tmp_len = len(q1) q = set([]) for word in q1: for i in range(l): for e in edges[word[:i]+'*'+word[i+1:]]: if e in q2: return steps + 1 if e not in visited: q.add(e) visited.add(e) q,q1 = q1,q return 0
https://shawnlyu-official.medium.com/bfs-and-bi-directional-bfs-98cd4e6ad080?source=post_internal_links---------1-------------------------------
CC-MAIN-2022-05
refinedweb
373
64.61
Problem with Flex mobile app on iOSmiguel.martin Oct 15, 2011 2:37 AM Hello there, I got an application, which reproduces video using osmf, working quite well with debug and run versions on iOS and Android platforms. It also works without any further problem when I export a release build for Android. The problem is that the very same application does not work when I export it for iOS. I'm using Flash Builder 4.5.1 and I package it using a distribution cert and a distribution provisioning file, selecting ad hoc packaging for testing it before I could submit it to the App Store. The distribution cert and distribution provisioning files seem to be ok: I've checked the profiles installed on my ipad2 and it's been installed without problems and it's valid for a year. The application freezes and become unresponsive when I try to log in into it (just a few HttpService invocations), and then, after some minutes it closes itself, like some kind of memory issue (remember that it works with run/debug versions). Is there anything I can check or be aware of when exporting an app for the iOS platform? I'm not receiving any kind of errors and I'm trying to disable parts to see what it's causing this problem, but as you can imagine, it's a very tedious process since packaging for iOS takes several minutes. Any ideas that could accelerate this process and know what it's happening? Thanks in advance. 1. Re: Problem with Flex mobile app on iOSShongrunden Oct 15, 2011 3:01 PM (in response to miguel.martin) Does it work if you use fast mode to package for iOS? 2. Re: Problem with Flex mobile app on iOSmiguel.martin Oct 15, 2011 4:19 PM (in response to Shongrunden) It works for run/debug using fast and standard packaging. However it does not work when exporting it as a release build for iOS (for Android it does work). Thanks for your reply. 3. Re: Problem with Flex mobile app on iOSShongrunden Oct 15, 2011 4:35 PM (in response to miguel.martin) My first thought is that maybe you're trying to load an external SWF, but that shouldn't work in standard packaging mode. 4. Re: Problem with Flex mobile app on iOSmiguel.martin Oct 16, 2011 1:25 AM (in response to Shongrunden) I'm not loading any external SWF, the only think about this application is that it needs other projects (it is not a single project, it's a project consisting on different ones: model, skins, libraries, etc) and sometimes It has to make multiple server requests (N httpservices at the same time). 5. Re: Problem with Flex mobile app on iOSShongrunden Oct 16, 2011 2:00 PM (in response to miguel.martin) Multiple projects, but they all get compiled into one IPA right? 6. Re: Problem with Flex mobile app on iOSmiguel.martin Oct 16, 2011 2:28 PM (in response to Shongrunden) Right. It's something like there's some logic or process that works on run/debug versions but don't on release ones. I've tried commenting out code and I was able to enter the application normally. The problem is that the application is doing simple tasks on load. I can't understand why the release version is not working, it's only a couple of ChangeWatchers to register a couple of handlers on properties change. These Change Watchers are responsible of processing of various XMLs which contains just a few nodes. 7. Re: Problem with Flex mobile app on iOSShongrunden Oct 16, 2011 2:31 PM (in response to miguel.martin) Are you able to file a bug with your project? 8. Re: Problem with Flex mobile app on iOSjd.perez-diaz Nov 1, 2011 8:13 AM (in response to miguel.martin) Miguel: Did you ever find out what was wrong. I am having a similar issue. My app works well in debug, but then I repackage using ad hoc and it breaks after a certain point. 9. Re: Problem with Flex mobile app on iOSmiguel.martin Nov 1, 2011 10:15 AM (in response to jd.perez-diaz) @jd.perez-diaz: I did find the issue that kept my app from working. It was related with some static functions (generic collections treatment) that I've got coded in a utility class. Removing the code where I was calling these static functions and coding my desire functionality inside the proper .as and mxmls, I was able to solve the problem. However I've not found the time to extract the concrete problem and file a bug for it. Hope it gives you some clue. It's so annoying to find what's going on considering that each release takes aprox 10 minutes. 10. Re: Problem with Flex mobile app on iOSalinator11 Nov 2, 2011 10:02 PM (in response to miguel.martin) I have this same problem. I can deploy with developer cert to registered devices if I use the lowest level (fastest) compile but when I got a distribution cert and tried to package for dist, all I ever got was failures. In any scenario other than the fastest compile for device testing with a developer cert, the ipa gets built, deployed and looks like it will install. Then it fails with no message. 11. Re: Problem with Flex mobile app on iOSShongrunden Nov 3, 2011 9:13 AM (in response to alinator11) Fast packaging is extremely different than standard packaging. If you are able to debug with fast mode can you try debugging with standard mode and see if that works? 12. Re: Problem with Flex mobile app on iOSalinator11 Nov 3, 2011 5:24 PM (in response to Shongrunden) I just ran standard and the result was that the app packaged, downloaded and installed correctly. The giant but is that while I had sound, I had no screen and thus no useful program. When I package in fast mode, the app performs well and I have a visible screen. 13. Re: Problem with Flex mobile app on iOSShongrunden Nov 7, 2011 9:18 AM (in response to alinator11) It's possible that you are using a feature that isn't supported on iOS. Can you provide a small sample application that demonstrates this? 14. Re: Problem with Flex mobile app on iOSalinator11 Nov 7, 2011 11:26 AM (in response to Shongrunden) I would be happy to provide you a running version of the app, one for Android and one for iOS so you can compare the differences and actually run the Android version to see what the iOS version should do. Please let me know if you'd like me to do this as that's the best sample program I can give you. Also, I don't see how an iOS packing can result in a properly running application in fast packing mode but a failure in the other and it be due to some unsuported feature on iOS. The app is running on iOS with fast packaging but failing with the other packaging. It would seem the iOS version should not work at all if it's some unsupported iOS feature causing the problem... 15. Re: Problem with Flex mobile app on iOSShongrunden Nov 7, 2011 1:45 PM (in response to alinator11) I'm looking for a small, complete, compilable sample application that I can build locally to try and reproduce the issue. For example this thread has a great example of a small, complete, compilable sample application: Fast packaging doesn't cross-compile the runtime and application down into native ARM code. Instead it just bundles the AIR runtime and interprets the application at runtime (just like AIR typically operates on other devices). But loading and interpreting code at runtime is strictly forbidden by Apple's iOS terms of service. So while it's fast mode is nice to do quick debugging with locally, it isn't something that would be accepted if you were to submit it to the App store. Standard packaging cross-compiles the runtime and application together into native ARM code so there is no runtime loading and interpreting of code. This packaging process can take a while so that is why there is an option for fast package if you just want to quickly iterate on something like laying out elements of your application. This video might be useful: It's possible that your case should work in both modes, but there is a bug in the standard packaging, but we need to see some code to investigate further. 16. Re: Problem with Flex mobile app on iOSalinator11 Nov 7, 2011 2:05 PM (in response to Shongrunden) My problem is that my app is all swf loaded into flex using SWFLoader and embedded in the app. I have no idea how to determine what SWF is causing the problem (if it is an SWF causing the problem). However, if it helps, I can send you the SWF I'm embedding as well as the intro view of my app. Here is the view of my app: <?xml version="1.0" encoding="utf-8"?> <s:View xmlns:fx="" xmlns: <fx:Script> <![CDATA[ import mx.core.IVisualElement; import mx.events.FlexEvent; import spark.managers.PersistenceManager; private var versionNumber:String = "1.4.14666"; private var pm:PersistenceManager private function initLoader():void { var t:Timer = new Timer(30000); t.start(); t.addEventListener(TimerEvent.TIMER, timesUp); pm = new PersistenceManager(); pm.load(); //if the version number does not match the version number hard coded in the //code above, the system will clear the data. This is useful for testing where //you want to force the app to clear user data so user has to go back through the if(pm.getProperty("versionnum") == null) { pm.clear(); pm.setProperty("versionnum", versionNumber); pm.save(); } else { if(pm.getProperty("versionnum") != versionNumber) { pm.clear(); pm.setProperty("versionnum", versionNumber); pm.save(); } } pm.setProperty("enemyinit", "true"); pm.save(); splashVidLoader.removeEventListener(FlexEvent.CREATION_COMPLETE, initLoader); splashVidLoader.content.addEventListener(Event.ADDED, onLoadSWF); } private function timesUp(timerEvent:TimerEvent):void { mainMovie.stop(); } private var mainMovie:MovieClip; private function onLoadSWF(event:Event):void { event.target.removeEventListener(Event.ADDED, onLoadSWF); if(event.target.name == "introScreenMain") { mainMovie = MovieClip(event.target); } if(event.target.name == "playButton") { event.target.addEventListener(MouseEvent.CLICK, buttonPressed); } else if(event.target.name == "instructionButton") { event.target.addEventListener(MouseEvent.CLICK, buttonPressed); } } private function buttonPressed(event:Event):void { if(event.target.name == "playButton") { if(pm.getProperty("facelearned") != null && pm.getProperty("facelearned") == "true") { //play the game mainMovie.stop(); mainMovie = null; creditsLoader.unloadAndStop(); splashVidLoader.content.removeEventListener(Event.ADDED, onLoadSWF); splashVidLoader.unloadAndStop(true); navigator.replaceView(EnemyViewer); } else { //user needs setup mainMovie.stop(); splashVidLoader.removeEventListener(Event.ADDED_TO_STAGE, onLoadSWF); splashVidLoader.endEffectsStarted(); splashVidLoader.unloadAndStop(true); navigator.replaceView(NewCappa); } } if(event.target.name == "instructionButton") { creditsLoader.load(); creditsLoader.addEventListener(MouseEvent.CLICK, creditsClosed); creditsLoader.visible = true; } } private function creditsClosed(event:Event):void { creditsLoader.visible = false; } ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <s:SWFLoader <s:SWFLoader </s:Group>--> </s:View> I will send you both SWF's referenced here as a private message. When I used fast packaging, the Intro SWF loads up, I see the screen, hear the sounds and the buttons in the SWF work. When I use standard packaging, the SWF loads and I hear sound, but don't get a screen. 17. Re: Problem with Flex mobile app on iOSDushyandh Nov 8, 2011 2:40 AM (in response to miguel.martin) So is there any issue in dynamic code loading / compiling ! I'm findind possibilities to taylor my business requirement of having a mobile portal. Earlier I had been using Sencha with Cue - me for this. Is there a work around for this using flex ?? 18. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 10:10 AM (in response to Dushyandh) I did read that Flex cannot dynamically compile on iOS. iOS does not allow just in time compilation. In keeping with this, I embedded all SWF's in my app (as assets and use the SWFLoader) so I have no need for just in time compilation and Flex can precompile everything. I am a bit confused over a few issues though. For whatever reason, my app works in fast packaging but not in standard. I hear yesterday from Shongrunden that there are some iOS features that are not supported. I'm using the camera and my SWF's have some animation and I'm calling Blaze and getting Strings and other objects passed back and forth. While I understand that these features (compiling to iOS and Android) are new to Flex, if you're going to provide the convenience of fast packaging, also please make the app fail or throw warnings if it will not later also compile to standard packaging. By NOT doing this, it could waste developer's time as we spend a great deal of time writing software, specifically in Flex so as to avoid having to write for iOS and Android, to later find out that all our work is futile and we have to go develop in Objective C anyway. I am at the end of my app development. I have a perfectly working Android app and a semi-working iOS app and absolutely no answers as to why and want to go live. Is there anyone that can help me find out what is wrong and finally publish to iOS? FYI, fast packaging says only that the app may run slower than it will run if you use standard packaging. It does not say that your app may work in fast packaging but won't work when you get to actually deploying it. Can someone also please tell me what iOS features are not supported via Flex? I can't imagine that I've tried to do something that iOS does not support but I can't say as I have no idea what iOS does not support that Android does via Flex. If iOS does not support something, can Adobe make Flex work like every other programming language I've ever worked with and have the compiler complain/fail if a developer tries to do something that iOS does not support. The worst thing you can do is not complain and in fact give me a working IPA file that installs but won't run - with each one of them taking 10 minutes or more to build and deploy! Make it fail during compile (and give some clue why) if it's not going to work please. 19. Re: Problem with Flex mobile app on iOSShongrunden Nov 8, 2011 11:10 AM (in response to alinator11) Re: Unsupported features: When I mentioned that some features are not supported I was mainly talking about the restriction about dynamically loading and interpreting code. It appears that this means loading SWFs (via SWFLoader or otherwise) regardless if they are embedded or not. It appears that when you embed a SWF it isn't cross compiled to ARM code, but rather just treated like any other embedded object like a JPG or PNG. For example, this really simple sample application: <s:Application xmlns:fx="" xmlns: <s:SWFLoader </s:Application> (See attached SWF.swf) There is a red circle that animates across the screen. This animation is accomplished by writing a little ActionScript to move the circle on a timer interval. In fast packaging mode the red circle animates across the screen, but in standard packaging mode the red circle doesn't move suggesting that no ActionScript is being executed. I'll check to see if this is expected or if this is a bug. Re: "if you're going to provide the convenience of fast packaging, also please make the app fail or throw warnings if it will not later also compile to standard packaging" Great point. I'll check to see if there are runtime bugs filed for this. Re: "FYI, fast packaging says only that the app may run slower than it will run if you use standard packaging. It does not say that your app may work in fast packaging but won't work when you get to actually deploying it." Another great point. I'll check with the Builder team to see if we can make that message more useful. - - SWF.fla.zip 5.6 K 20. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 11:27 AM (in response to Shongrunden) Thanks so much! So if the SWF's won't compile even as embedded SWF's, how can I rebuild my app so it will run? I would be happy to take all the SWF's and compile to ARM but then I have no idea how to tie these many SWF's to my Flex code as the only way I see to do it now is to use SWFLoader? I have the fla's given to me by my designer. How can I make those FLA's part of my larger Flex code and get them to compile so I can wrap this project up? FYI, fast packaging is also not consistent among devices. On an iPod 4, I got the app to run in fast packing mode. On an iPhone 4 the app starts but buttons that should not be visible are visible and the app does not behave as it should. Perhaps it won't matter much longer as if I can get the SWF's to be part of my app it sounds like all problems go away. 21. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 4:26 PM (in response to alinator11) I think I [may] have figured it out (sort of) but I still can't get it to run fully - although I have now successfully gotten the SWF's to deploy individually to iOS and run with standard packaging on... Can someone tell me what to change to make this work? Here are the steps I took.. 5. Deployed to iPod and, for the first time, the SWF worked with standard packaging for deployment. Now I just need to understand how to practically instantiate the SWF's in my Flex code and I'm hopefully good to go. Here is how I tried to do that: Then I added to existing project 1. Took above SWF file and put it in my main project bin-debug folder 2. Took above .AS file and put it in my main project default folder 3. Took above app-xml and put it in my main project src folder (now I have multiple app-xml files, one for my main app and one for this new "Intro" app that I just created). 4. Now that this first (test) SWF has been added to my project, I modify a Flex object that was previously loading this SWF to now call the AS directly. Instead of SWFLoader.load(), now my view instantiates the AS associated with the SWF that is in the bin debug. In this case, I've called the SWF, XML and ActionScript class by the name "Intro" so I have Intro.SWF, Intro-xml and Intro.AS and all are in the same project as main.xml, main.swf and main.mxml. In step 4, I am trying to instantiate, from my view, the Intro SWF that is in my bin-debug file as follows (note that my SWF is a MovieClip so I cannot use addElement and have to use addChild()) private function initLoader():void { var intro:Intro = new Intro(); vidcomp.addChild(intro); } While I was able to get the SWF to load on the device when I made it a stand alone project, I am not now able to get the SWF I have added to the bin-debug folder to instantiate and run when I try to call it as part of my larger app. Since I have now made the SWF part of my app directly, I'm sure I just need to understand the practicalities of how to instantiate it. Can someone please help me understand how to get the SWF that is in my bin-debug folder to have a reference that I can control. 22. Re: Problem with Flex mobile app on iOSFlex harUI Nov 8, 2011 5:29 PM (in response to alinator11) Actionscript in a loaded SWF cannot be executed. 23. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 6:01 PM (in response to Flex harUI) Is there any way to solve my problem or am I sol? 24. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 6:22 PM (in response to Flex harUI) Btw, I don't care about executing AS on the loaded swf so much as I care about getting a reference to the movieclip that the swf contains. If I can get to that, I'm good. Is there a way to do that? 25. Re: Problem with Flex mobile app on iOSdrkstr_1 Nov 8, 2011 7:32 PM (in response to alinator11) Turn your SWFs into libraries and import the assets that way. The packager must be able to pick up the class linkages in your SWF. This means they need to be embeded as "code" and not assets. That means .swc libraries. If you give more info on the nature of these SWFs, I may be able to suggest a specific strategy for the conversion process. Mainly, is this dynamic content or "application assets"? 26. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 7:38 PM (in response to drkstr_1) I will be back at my computer soon and will try to convert. This is my first flash project. My swfs were all designed by my designer (he is absolutely not a programmer). They are animations, buttons, forms... stuff like that. I will do a google search to find out the means to turn to a library and try that. 27. Re: Problem with Flex mobile app on iOSalinator11 Nov 8, 2011 9:35 PM (in response to alinator11) drkstr_1, thanks so much for the offer to help. While I will search through the web to find an answer as well, if you can give me one walk through of turning an SWF into a library object that I can then call and manipulate, that would be most helpful and appreciated. I put up one SWF from my app here: That will load it in your web browser. From that SWF, I need to get a reference to the buttons so I can listen to them, enable/disable them as well as turn them visible/not visible as needed and I need to get the name and email text information and populate some other image fields with jpg's I send from Blaze. The way I get reference in Flex to the fields in NewCappaNoGend.SWF now is as follows: 1. SWFLoader.load(@Embedded...) 2. SWFLoader.content.addEventListener(Event.ADDED, objectLoaded); 3. Function objectLoaded checks for the event.target.name of the SWF component item as it is added to stage. If it is one of the instance names I know about in the SWF, I cast event.target to the proper object (such as a TextField) and then I can manipulate the SWF fields as needed. Clearly none of the above works in iOS. I will search for how to convert SWF to library and will post if I find a solution before you respond. Thanks so much for your help. Sincerely. EDIT: Just noticed that you said SWC, not SWF. Read SWF... Duh. Found good references for how to do this here: 28. Re: Problem with Flex mobile app on iOSdrkstr_1 Nov 9, 2011 10:05 AM (in response to alinator11) The challenge will be getting the code in the FLA to play nice as a library. It will most likely involve opening up each FLA given to you by the designer and creating a top level "entry point" class that you can import into your project. I attached an example to show you what I mean. I can't figure out how to attach an example to show you what I mean, but... package { import fl.controls.Button; import flash.display.Sprite; public class SWCTest extends Sprite { public var buttonDisplay:Button; } } What I did in the FLA is plop everything sitting on the stage (in my case, a button with an intance name buttonDisplay), then I converted it into a movie clip with the class reference SWCTest. You change change the publish settings to publish as an SWC library instead of a SWF. You can then use this class directly by importing the SWC into your Flex project, and then doing something similar to this: <?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns: <fx:Script> <![CDATA[ import mx.events.FlexEvent; protected function creationCompleteHandler(event:FlexEvent):void { trace("SWCFlexTest.creationCompleteHandler(event)"); this.content = new SWCTest(); this.contentContainer.addChild(this.content); } public var content:SWCTest; ]]> </fx:Script> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <s:SpriteVisualElement </s:WindowedApplication> This will allow the ADT compiler to pick up all the necessary class linkages so they can be cross compiled into native ARM code. 29. Re: Problem with Flex mobile app on iOSalinator11 Nov 9, 2011 1:07 PM (in response to drkstr_1) Very cool. Thanks dr_eunuch_maker. I am able to get to the invidual components in the fla, but I am not able (yet) to get the main movie to play with all components automatically added to stage without instantiating each component individually. Thus, I have sent the FLA to the designer and asked him to put everything under one MovieClip to see if that helps. When I was using SWFLoader, of course, all this loaded up without any fuss. However, I adore the fine grained control I have over the components now and adore even more that I'm pointed in the right direction. Dealing with format and layout issues is a far more welcome problem. Along with the steps you explained above, I also added the swc to the build path of my flex project and copied the swc to my flex project's lib directory. Thanks again drkstr_1. 30. Re: Problem with Flex mobile app on iOSShongrunden Nov 9, 2011 2:07 PM (in response to alinator11) You might find the Flex Component Kit for Flash useful for turning FLA classes into Flex objects: 31. Re: Problem with Flex mobile app on iOSalinator11 Nov 10, 2011 9:00 PM (in response to Shongrunden) Thanks a bunch guys. After a bit of internet searching, I found the latest FlexComponentKit (2.0.0). It's not easy to find so if anyone is looking for it, it's here: I am using CS5.5 and have found 2.0.0 to work great with it. After installing the framework, I had my designer take all the contents of the FLA and put them into one (1) movieclip. Using Flash Pro, I then gave that MovieClip an instance name and I tied it to ActionScript. When I linked it to ActionScript, I changed the default parent class from flash.display.MovieClip to mx.flash.UIMovieClip. As soon as you do that, the library symbol changes from a MovieClip symbol to an actual FX symbol. Then I published to swc. After publishing to SWC, I switched over to Flash Builder, opened my project and ran a test. I was able to instantiate the objects within the FLA, including the parent MovieClip, and get reference to all the children. Perfect! Thanks a ton for the help guys. 32. Re: Problem with Flex mobile app on iOSmadhu_51 Mar 1, 2012 2:57 AM (in response to alinator11) Hi , I am facing issue wile loading swf from past 1 week. I am using adobe flex 4.5.1 for mobile project. I got .swf file from third person i am totaly unaware of file . Initially i was facing compile time error for the same .swf so as you posted i tried to follow your steps, ipad simulator . i was succesfull abble to do this But after two three instances of run in simulator .swf will not load again and default home screen will be displayed. So i do not have real device to test how it will beahave on it. Can you please tell me how i can ensure it will load at each launch. Regards, MAdhu
https://forums.adobe.com/thread/913819
CC-MAIN-2017-51
refinedweb
4,782
71.24
Collection of classes for programming with functors, applicative functors and monads. Project description - int, float, str, list, List, Maybe, First, and Last - Six predefined monad types - Maybe - for when a calculation might fail - Either - Similar to Maybe but with additional error reporting - List - For non-deterministic calculations - Reader - For sequencing calculations which all access the same data. - Writer - For keeping logs of program execution. - State - Simulating mutable state in a purely functional way. Getting Started Installation Using pip: pip install PyMonad Or download the package or clone the git repository from bitbucket. State Monad Unlike most of the other monad types, the state monad doesn’t wrap values it wraps functions. Specifically, it wraps functions which accept a single ‘state’ argument and produce a result and a new ‘state’ as a 2-tuple. The ‘state’ can be anything: simple types like integers, lists, dictionaries, custom objects/data types, whatever. The important thing is that any given chain of stateful computations all use the same type of state. The State constuctor should only be used to create stateful computations. Trying to use State to inject values, or even non-stateful functions, into the monad will cause it to function incorrectly. To inject values, use the unit function. Here’s an example of using State. We’ll create a little system which can perform addition and subtraction. Our total will never be allowed to drop below zero. The state that we’ll be keeping track of is a simple count of the total number of operations performed. Every time we perform an addition or subtraction the count will go up by one: @curry def add(x, y): return State(lambda old_state: (x + y, old_state + 1)) @curry def subtract(y, x): @State def state_computation(old_state): if x - y < 0: return (0, old_state + 1) else: return (x - y, old_state + 1) return state_computation As mentioned, The State constructor takes a function which accepts a ‘state’, in this case simply an integer, and produces a result and a new state as a tuple. Although we could have done subtract as a one-liner, I wanted to show that, if your computation is more complex than can easily be contained in a lambda expression, you can use State as a decorator to define the stateful computation. Using these functions is now simple: x = unit(State, 1) >> add(2) >> add(3) >> subtract(40) >> add(5) x now contains a stateful computation but that computation hasn’t been executed yet. Since State values contain functions, you can call them like functions by supplying an initial state value: y = x(0) # Since we're counting the total number of operations, we start at zero. print(y) # Prints (5, 4), '5' is the result and '4' is the total number of operations performed. Calling a State function in this way will always return the (result, state) tuple. If you’re only interested in the result: y = x.getResult(0) # Here 'y' takes the value 5, the result of the computataion. Or if you only care about the final state: y = x.getState(0) # Here 'y' takes the value 4, the final state of the computation. Changes v1.3, 2014-06-28 – Added Monoid instances for List and Maybe, added First and Last Monoids, add State Monad, updated tests for List and Maybe. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/PyMonad/
CC-MAIN-2018-51
refinedweb
578
52.29
5942/how-to-clone-arraylist-and-also-clone-its-contents Iterate on the items, and clone them one after the other, putting the clones in your result array as you go. public static List<Dog> cloneList(List<Dog> list) { List<Dog> clone = new ArrayList<Dog>(list.size()); for (Dog item : list) clone.add(item.clone()); return clone; } For that to work, obviously, you will have to get your Dog object to implement the Cloneable interface, and the clone() method You can also use Java Standard Library ...READ MORE ArrayList is what you want. LinkedList is almost always a ...READ MORE The best possible way of conversion between byte[] and String is to ...READ MORE Follow these steps: Write: public class User { ...READ MORE We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE In Java 8 or later: String listString = ...READ MORE List<String> al = new ArrayList<>(); // add elements ...READ MORE List<String> results = new ArrayList<String>(); File[] files = ...READ MORE In Java 9 you can use: List<String> list= List.of("Hello", "World", ...READ MORE To convert STring to byte[]: String s = ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/5942/how-to-clone-arraylist-and-also-clone-its-contents
CC-MAIN-2021-21
refinedweb
200
69.38
Get the highlights in your inbox every week. Why I use the D programming language for scripting | Opensource.com Why I use the D programming language for scripting The D programming language is best known as a system programming language, but it's also a great option for scripting. Subscribe now The D programming language is often advertised as a system programming language due to its static typing and metaprogramming capabilities. However, it's also a very productive scripting language. Python is commonly chosen for scripting due to its flexibility for automating tasks and quickly prototyping ideas. This makes Python very appealing to sysadmins, managers, and developers in general for automating recurring tasks that they might otherwise have to do manually. It is reasonable to expect any other script-writing language to have these Python traits and capabilities. Here are two reasons why I believe D is a good option. 1. D is easy to read and write As a C-like language, D should be familiar to most programmers. Anyone who uses JavaScript, Java, PHP, or Python will know their way around D. If you don't already have D installed, install a D compiler so that you can run the D code in this article. You may also use the online D editor. Here is an example of D code that reads words from a file named words.txt and prints them on the command line: open source is cool Write the script in D: #!/usr/bin/env rdmd // file print_words.d // import the D standard library import std; void main(){ // open the file File("./words.txt") //iterate by line .byLine // print each number .each!writeln; } This code is prefixed with a shebang that will run the code using rdmd, a tool that comes with the D compiler to compile and run code. Assuming you are running Unix or Linux, before you can run this script, you must make it executable by using the chmod command: chmod u+x print_words.d Now that the script is executable, you can run it: ./print_words.d This should print the following on your command line: open source is cool Congratulations! You've written your first D script. You can see how D enables you to chain functions in sequence to make reading the code feel natural, similar to how you think about problems in your mind. This feature makes D my favorite programming language. Try writing another script: A nonprofit manager has a text file of donations with each amount on separate lines. The manager wants to sum the first 10 donations and print the amounts: #!/usr/bin/env rdmd // file sum_donations.d import std; void main() { double total = 0; // open the file File("monies.txt") // iterate by line .byLine // pick first 10 lines .take(10) // remove new line characters (\n) .map!(strip) // convert each to double .map!(to!double) // add element to total .tee!((x) { total += x; }) // print each number .each!writeln; // print total writeln("total: ", total); } The ! operator used with each is the syntax of a template argument. 2. D is great for quick prototypingD is flexible for hammering code together really quickly and making it work. Its standard library is rich with utility functions for performing common tasks, such as manipulating data (JSON, CSV, text, etc.). It also comes with a rich set of generic algorithms for iterating, searching, comparing, and mutating data. These cleverly crafted algorithms are oriented towards processing sequences by defining generic range-based interfaces. The script above shows how chaining functions in D provides a gist of sequential processing and manipulating data. Another appeal of D is its growing ecosystem of third-party packages for performing common tasks. An example is how easy it is to build a simple web server using the Vibe.d web framework. Here's an example: #!/usr/bin/env dub /+ dub.sdl: dependency "vibe-d" version="~>0.8.0" +/ void main() { import vibe.d; listenHTTP(":8080", (req, res) { res.writeBody("Hello, World: " ~ req.path); }); runApplication(); } This uses the official D package manager, Dub, to fetch the vibe.d web framework from the D package repository. Dub takes care of downloading the Vibe.d package, then compiling and spinning up a web server on localhost port 8080. Give D a try These are only a couple of reasons why you might want to use D for writing scripts. D is a great language for development. It's easy to install from the D download page, so download the compiler, take a look at the examples, and experience D for yourself.
https://opensource.com/article/21/1/d-scripting
CC-MAIN-2021-21
refinedweb
760
67.65
Merge sort is the first algorithm we are going to study in Divide and Conquer. According to Divide and Conquer, it first divides an array into smaller subarrays and then merges them together to get a sorted array. The dividing part is the same as what we did in the previous chapter. The real thing lies in the combining part. We combine the arrays back together in such a way that we get the sorted array. So, we will make two functions, one to break the arrays into subarrays and another to merge the smaller arrays together to get a sorted array. Let's start by making the first function which is similar to the function we made in the previous chapter. MERGE-SORT(A, start, end) if start < right middle = floor((start+end)/2) MERGE-SORT(A, start, middle) MERGE-SORT(A, middle+1, end) With this code, we will be able to break our array into smaller subarrays, but now we want the subarrays to combine together and make a sorted array. For this purpose, let's focus on writing the merge function. To merge the smaller arrays back together, we will start iterating over the arrays and putting the smaller element first to get a sorted array. This will be clear from the picture given below. From the above picture, you can see that we are iterating over both the arrays simultaneously and comparing the elements and then putting the smaller element in the final array and then continuing the iteration. But one doubt can come in anyone's mind that both the arrays shown in the above picture are themselves sorted and then we are merging them together to get the final sorted array, so how are we going to get the two smaller arrays sorted? The answer is simple, we are breaking our arrays into smaller subarrays until the size of each subarray becomes 1 and any array with just a single element is already sorted in itself. So, we will start merging them together to get bigger sorted arrays. Since we are clear with the entire idea of Merge Sort, so let's write code for the merge function. Code for Merge Sort As shown in the picture above, the merge function is going to merge two arrays which are already sorted. However, these two arrays will not be entirely different arrays but a single array which will be separated by a variable into two arrays because this is how we are breaking our arrays. So, our function to merge the arrays will take an array, starting index, ending index and the middle index from which the array is separated i.e., MERGE(A, start, middle, end). Now, we have to iterate over both the subarrays, compare the elements and put the smaller one into the final array. But we don't have any final array to work with, all we have is a single array and the indices. So, let's copy the subarrays into two temporary arrays and modify the initial array 'A' to make it sorted. So, our first task is to make two temporary arrays. temp1 = A[start, middle] temp2 = A[middle+1, end] Now, we have to iterate over these arrays and compare the elements and then put the smaller elements into the bigger array. i = 1 j = 1 k = start while i <= temp1.length and j <= temp2.length if temp1[i] < temp2[j] A[k] = temp1[i] i=i+1 else A[k] = temp2[j] j=j+1 k=k+1 We are iterating over both the arrays with while i <= temp1.length and j <= temp2.length and then comparing the elements - if temp1[i] < temp2[j]. After that, we are putting the smaller element into the array first - A[k] = temp1[i] (if temp1 has smaller element) or A[k] = temp2[j] (if temp2 has smaller element) and then we are continuing our iteration with i = i+1 or j = j+1, which ever element was put to the array. At last, k = k+1 is making the increase for the iteration on the original array. The illustration for the same is given below. One thing you can note from the above picture is that after this process, it might be possible that we are left with few elements in any of the subarrays. To handle this case, let's just copy the remaining elements to the array. Because these elements are already sorted and only the larger elements are going to be left, so direct copying is going to work for us. while i < temp1.length A[k] = temp[i] i = i+1 while j < temp2.length A[k] = temp[j] j = j+1 The first while loop is iterating over the temp1 array and copying any leftover of the array. The second loop is doing the same thing but with the array temp2. So, now we are ready to write the merge function. MERGE(A, start, middle, end) temp1 = A[start, middle] temp2 = A[middle+1, end] i = 1 j = 1 k = start while i <= temp1.length and j <= temp2.length if temp1[i] < temp2[j] A[k] = temp1[i] i=i+1 else A[k] = temp2[j] j=j+1 k=k+1 while i < temp1.length A[k] = temp[i] i = i+1 while j < temp2.length A[k] = temp[j] j = j+1 Now, we have to use this MERGE function inside the MERGE-SORT function which is basically dividing the array into subarrays. Till now, we have developed the MERGE-SORT function as: MERGE-SORT(A, start, end) if start < right middle = floor((start+end)/2) MERGE-SORT(A, start, middle) MERGE-SORT(A, middle+1, end) We know that after the completion of the MERGE-SORT function, the function will sort any array passed to it and this is the entire point of this function. So, MERGE-SORT(A, start, middle) and MERGE-SORT(A, middle+1, end) are going to sort the arrays A[start, middle] and A[middle+1, end] respectively. And now we have to merge them together to get the bigger sorted array. So, placing MERGE(A, start, middle, end) right after MERGE-SORT(A, middle+1, end) will complete the function for us. MERGE-SORT(A, start, end) if start < right ... MERGE-SORT(A, middle+1, end) MERGE(A, start, middle, end) But wait, we have basically assumed that MERGE-SORT(A, start, middle) will give us a sorted array A[start, middle] when the function was not even complete and our entire completion of the function is dependent on this assumption only. So, if the assumption is correct then the entire function is going to work correctly. In other words, if we show that MERGE-SORT gives us a sorted array in the base case, then we can use the MERGE function afterward to generate bigger sorted arrays. And we have already discussed that in the base case, MERGE-SORT is going to break the array into size of 1 and any array with single element is sorted in itself and thus MERGE-SORT is going to give us a sorted array in base case and after that, the MERGE function is going to combine them into bigger sorted arrays. Thus, the code for MERGE-SORT can be written as: MERGE-SORT(A, start, end) if start < right middle = floor((start+end)/2) MERGE-SORT(A, start, middle) MERGE-SORT(A, middle+1, end) MERGE(A, start, middle, end) - C - Python - Java #include <stdio.h> void merge(int a[], int start, int middle, int end) { int size_of_temp1, size_of_temp2, i, j, k; //temporary arrays to copy the elements of subarray size_of_temp1 = (middle-start)+1; size_of_temp2 = (end-middle); int temp1[size_of_temp1], temp2[size_of_temp1]; for(i=0; i<size_of_temp1; i++) { temp1[i] = a[start+i]; } for(i=0; i<size_of_temp2; i++) { temp2[i] = a[middle+1+i]; } i=0; j=0; k=start; while (i < size_of_temp1 && j < size_of_temp2) { if (temp1[i] < temp2[j]) { // filling the main array with the smaller element a[k] = temp1[i]; i++; } else { // filling the main array with the smaller element a[k] = temp2[j]; j++; } k++; } // copying leftovers while (i<size_of_temp1) { a[k] = temp1[i]; k++; i++; } while (j<size_of_temp2) { a[k] = temp2[j]; k++; j++; } } void merge_sort(int a[], int start, int end) { if (start < end) { int middle = (start+end)/2; merge_sort(a, start, middle); merge_sort(a, middle+1, end); merge(a, start, middle, end); } } int main() { int a[] = {4, 8, 1, 3, 10, 9, 2, 11, 5, 6}; merge_sort(a, 0, 9); //printing array int i; for(i=0; i<10; i++) { printf("%d ",a[i]); } printf("\n"); return 0; } Analysis of Merge Sort Let's have a look at the MERGE function first. It just iterates over the arrays and the arrays can have at most size of n. In the rest of the part, we are just comparing and assigning values and they are constant time processes. Thus, the MERGE function has a running time of $\Theta(n)$. Now, the analysis of the MERGE-SORT function is simple and we have already done this kind of analysis in previous chapters. The MERGE-SORT function is breaking the problem size of n into two subproblems of size $\frac{n}{2}$ each. The comparison ( if start < right) and calculation of middle ( middle = floor((start+end)/2)) are constant time taking processes. Also, we deduced that the MERGE function is $\Theta(n)$. So, we can write the overall running time of MERGE-SORT function as: $$ T(n) = 2T\left(\frac{n}{2}\right)+\Theta(n)+\Theta(1) $$ We have already dealt with the same function in Recurrence, Let's Iterate, Now the Recursion and Master's Theorem chapters and we know that it is going to take $\Theta(n\lg{n})$ time. So, this was a pure implementation of divide and conquer technique into an algorithm. Let's proceed to the further chapters and learn about more algorithms which use this technique.
https://www.codesdope.com/course/algorithms-merge-sort/
CC-MAIN-2021-25
refinedweb
1,671
57.71
User Name: Published: 19 Oct 2009 By: Andrew Siemer In this article we will start to address some of the flaws in our original design. The first step will be to refactor towards logical separation of our code. Then we can analyze the code to see what the remaining issues are. Then we will analyze the pros and cons of this design. In the last article we refactored our simple project from a UI direct to data access style web site into a logically separated tiered application. This took form by creating a separate data access layer area in our code as well as a separate business layer area in our code. We then moved our connection logic into its own class for reuse across the site. Next we created a repository to take care of all the querying for a given type of object. Once the data access was isolated we then created a fairly straight through business layer which can be easily modified in the future. This gave us a point to insert new functionality if the need were to arise. With the reworking of our plumbing code we then cleaned up our front end by plugging into our new business layer. We ended the article with a look at the pros and cons of this approach and found that there were significant improvements gained with just this one refactoring. There is still plenty of room for improvement in this code. In this article we will take the next step in improving this code by further elevating our logical tiers to physical tiers. This simply means that we will create separate assemblies for each of the separate tiers. By the end of this article we will have our web project, a business layer project, domain project, and a data access project. As we will see shortly this will alleviate some of the pains that we observed in our last article. But it should serve to surface a few other dependencies that we have not really had a good view of yet. To get started this time around we will need to create three new class library projects. One project will be called Core and will hold our business logic including service classes. The other project will be called DataAccess and will hold our Connection and Repository classes. And the last one is going to be our Domain project which will hold our domain objects. Right click on our current solution and add a new project. Then choose to add a Class Library project. Name it KnowledgeExchange.Core and place it in our src directory. Then add another Class Library project. This one will be named KnowledgeExchange.DataAccess and also placed in the src directory. And finally add the last class library for our Domain project. src Once you have the projects created you will need to modify the properties for each project. You need to make sure that the assembly name and namespace reflect exactly what you want them to be. I name my projects assembly and namespace the same: Very sorry! I just noticed that I named our web project KnowledgeExchangeWeb without the dot. This bothers me! For that reason we will take a quick moment to "refactor" our solution file, project directories, and project name to fit with all the other stuff we are doing. Before we get started doing operations such as this make sure that you commit all your changes and that your code base is 100% green across the board. Next, make sure that you commit after each and every modification you make as your code repository can quickly get so far out of sync that you will have a heck of a time getting things merged back in. Also, make sure that you perform all modifications through your SVN client tools. I am using Tortoise and will rename my folders first using Tortoise's rename feature. When you hit ok you will see a scary window that says it is deleting all of your files in this folder! Don't worry, it created a new folder with the new name and copied the versioned contents into that folder, and then tagged the other folder for deletion on SVN's side. Make sure that you rename both the KnowledgeExchangeWeb and KnowledgeExchangeWeb.Tests directories. Then we will rename the project file names. Use Tortoise to do this too. When renaming the project file to KnowledgeExchange.Web and KnowledgeExchange.Web.Tests you will see this prompt to rename similar files. Click yes and it will rename your surrounding files with the same name. Now we can rename the guts of the solution file. Do this by opening your solution in your favorite text editor. There are two lines that have modifications. And there is three modifications per line. You need to rename the project name, the project's directory name, and the project file name. Here is what they should now look like: Once you have finished this process you should then be able to reopen your solution file and see the new names reflected. Now that we have all of our projects created and uniform we can move our existing code to their new homes. We will move the connection and repository in our new data access project. And we will move our service into our new core project. If you are using visual studio and ankhsvn then you can quite literally just drag the class files to their appropriate project. If you are only using Tortoise then you are better off creating a new class file in the appropriate project and copy the contents from file A to file B. Then delete file A. Once you have moved those files we will then look to relocate our data context which generates our domain objects. We can move the KE.dbml to the Domain project.. Then you can delete the Models, Core, and DataAccess folder from your web project. Now that everything is relocated we need to modify our namespaces. You will notice that all of our namespaces in the core and data access projects mention Web. The namespace should directly reflect the name of the project and folder structure for each file. For a namespace that looks like this: We will need to change all of the namespaces so that they look like this instead: Now we need to add references from one project to the next. If we have done things correctly then the web project should only need to know about our business layer. Our business layer should know about our data access layer. Then the web project, core, and data access should all be aware of our domain objects. Add references to the web project by right clicking on the project and selecting add reference. Click the projects tab and select the core and domain projects. Then do the same for the core project and add a reference to the domain and data access projects. And for the data access project add a reference to the domain project. Next we need to look through our code and update all the dependencies (and remove references to namespaces that no longer exist). To start we need to see if anything will compile as is. I am starting by working on the Domain project that has our KE.dbml file. We need to make sure that it has access to its settings file. Do this by opening up the design surface for the .dbml file. If it complains about not being able to locate the settings file update the project appropriately (by adding a settings file and adjusting the reference). Then you should be able to build the Domain project which all of the other projects are referencing. Then we can look at the data access project. This project needs to be able to use the ConfigurationManager so we need to add a reference to the project for System.Configuration. Do this by right clicking on the project, add references, then select the .net tab, and then scroll down to find System.Configuration. While in there we will also need to add a reference to System.Data.Linq for our LINQ to SQL data context reference. Lastly we will need to add a using statement to the top of our repository and connection file to be able to access the AndrewSiemer.KnowledgeExchange.Domain namespace where our Post object now lives. Build this project to make sure that everything is working in our data access project. Now we can update our core project. The first thing we need to do is add some using statements to the top of our PostService class. This class needs to know about the PostRepository which lives in AndrewSiemer.KnowledgeExchange.DataAccess and it also needs to know about the Post object which lives in AndrewSiemer.KnowledgeExchange.Domain. Once that is done you should be able to build the core project. All that is left is to update our HomeController so that it knows where the PostService now lives. Do this by adding a reference to AndrewSiemer.KnowledgeExchange.Core. Then we need to open up our Index view to update its usage of the Post object. You should now be able to build your entire solution and then browse out to see if the web page still works. Also, make sure that your local build process still works. Do this by first deleting your KnowledgeExchange database and the login for the KnowledgeExchange_dev user. Then run the build process and initialize the local database. Then run the build process to make sure that everything is still good. Not a lot has changed from a code perspective. The code is technically the same from our last article. But we have reorganized it in a manner that makes it considerably more flexible. Having said that though I wanted to introduce this form of physical tiers as this is the form that most people build their projects thinking that everything is perfect, flexible, and most importantly scalable. This is a farce though as you will see in the dependency graph. In the past iterations we have done a pretty good job removing or at least relaxing dependencies that don't belong in our application. We still have one major dependency in place with regards to our data access layer. Since our domain objects are generated directly by our data access layer, LINQ to SQL in our case, we are pretty well tied to LINQ to SQL. This isn't horrible in the general since of things but it does break some of our rules such as abstraction, an a large chunk of the SOLID principles! Technically speaking a developer working on this application could instantiate an instance of KEDataContext and perform ad-hoc queries at their leisure. With this tight coupling we could never easily swap out our data source. We now have all of our concerns separate out into their own projects which is certainly a step in the right direction. It is now easier to limit the exposure of one tiers functionality to the next. There is now no way to make a call from the presentation layer to the data access layer. Also, having moved our domain into its own project sort of reduces the dependency between our core and data access layers which we had in our previous implementations. This is not perfect yet. While we have limited exposure from one layer to the next, technically the UI still has some access to the data access layer. And while our application is flowing through the appropriate channels to perform its various requests, there is nothing stopping a rouge developer from connecting to the data base and getting at the data that they need for a piece of functionality that they are working on. Also, our ORM preferences are too well known across all of the tiers which has created a very inflexible dependency on a specific technology. And our code is still not very testable! took the next step in improving this code by further elevating our logical tiers to physical tiers. This simply means that we created separate assemblies for each of the separate tiers. By the end of this article we had a web project, a business layer project, a domain project, and a data access project. We saw that this new structure alleviated some of the pains that we observed in our last article by strongly separating what each tier had access to. But it also surfaced our heavy dependency on our ORM choice. In our next article we will focus on less of the structural issues and instead work on removing our dependency on LINQ to SQL. We will achieve this by employing an object to object mapping tool called AutoMapper. We will create plain old CLR object (POCO for short) that we can then map our LINQ to SQL objects too. We will then refactor our application to be dependent upon our internal POCO objects instead of the LINQ to SQL generated objects. This will effectively allow our ORM choice to be independent of our code base which will allow us to swap LINQ to SQL out for Entity Framework 4.0 when it comes out next year!
http://dotnetslackers.com/articles/aspnet/Building-a-StackOverflow-inspired-Knowledge-Exchange-Three-Tiers-to-MVC-Hooray-Physical-Separation.aspx
crawl-003
refinedweb
2,213
72.05
I am having a problem with prototypes. I don't really get why I need phototypes or how to use them (my book doesn't explain it well) One of my problems is I need to use correctMessage() instead of cout << "Great Work!!!" << "\n";and I also need to use random good comments (switch between great, excellent, very good...). That also applys to incorrectMessage() and wrong++; while ( z != multiplication(x,y) ) { cout << "Wrong. Try again. \n"; cin >> z; } and bool needHelp( int, int ) and fail = (wrong/10)*100; if ( fail <= 75) { cout << "\nPlease ask you instructor for extra help.\n"; } Thank you for your help and hopefully I will understand the prototypes more. My full program is below. #include <iostream> using std::cin; using std::cout; using std::endl; #include <cstdlib> using std::rand; using std::srand; #include <ctime> using std::time; void multiplication(); // function prototype for the function you are programming! void correctMessage(); // function prototype void incorrectMessage(); // function prototype bool needHelp( int, int ); // function prototype int main() { srand( time( 0 ) ); // seed random number generator int multiplication( int x = 0, int y = 0 ); // begin multiplication practice int count =1; int x =0; int y =0; int z =0; int wrong =0; double fail =0; while (count <= 10 && z != -1) { count++; x = rand() % 9 + 1; y = rand() % 9 + 1; cout << "How much is " << x << " times " << y << " (-1 to end)? "; cin >> z; if ( z != multiplication(x,y) && z != -1) { wrong++; while ( z != multiplication(x,y) ) { cout << "Wrong. Try again. \n"; cin >> z; } } if ( z == multiplication(x,y)) { cout << "Great Work!!!" << "\n"; } } fail = (wrong/10)*100; if ( fail <= 75) { cout << "\nPlease ask you instructor for extra help.\n"; } return 0; // indicate successful termination } // end main int multiplication(int x, int y) { return x*y; }
http://www.dreamincode.net/forums/topic/98306-problem-understanding-function-prototypes/
CC-MAIN-2016-26
refinedweb
291
64.1
On Friday 15 October 2004 15:29, Carsten Ziegeler wrote: IMHO, generally, compatibility provided through subclassing is 'asking for long-term trouble'. Take a deep look inside the Netbeans project for a scary example. Subclassing of interfaces is slightly better... > > public interface Source extends org.apache.cocoon.source.Source {} ? > > You mean this as a compatibility layer, right? So, new code would use > the o.a.c.s.Source and old code can still use the o.a.e.s.Source? > > Hmm, I actually don't know what's best. What do others think? However, you are requesting that the Excalibur Source is a subclass of the Cocoon Source. I suspect that is a typo, but if not, then you are introducing a cross-dependency with the Excalibur project, or breaking namespace policies by using the excalibur namespace. Either way, having the same name is not a good idea, as it makes code that cares about the difference very messy. Cheers Niclas -- +------//-------------------+ / / / / +------//-------------------+
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200410.mbox/%3C200410151543.54662.niclas@hedhman.org%3E
CC-MAIN-2014-42
refinedweb
161
67.76
Kitchen coding nightmares: JavaScript scope Lately at the Recurse Center I’ve been developing a JavaScript client for my Settlers game. As a Perl developer working with JavaScript, it has been a fun experience. JavaScript feels very perly - both share a flexible syntax, first class functions and objects as hashes. And both languages have a lax interpreter which should have been put in strict mode in the first place (ha-ha!). One way in which JavaScript is very different from Perl is its scoping rules. I was burned by these more than once, and so if you’re new to JavaScript, you might find the following summary and recommendations useful. Functional scoping Variables are declared with the var keyword: var name = "David"; Variables are functionally-scoped, which means that if declared within a function, the variable is private to the function block. Variables declared outside of functions are globally scoped. And there is no other type of block scoping (such as within if-else or for loops). var name = "David"; function log_name (name) // private { console.log(name); } var names = ["Jen", "Jim", "Jem", "Jon"]; for (var i = 0; i < names.length; i++) { var name = names[i]; // overwriting the global } console.log(name); // Jon NOT David Functions as variables Function names are stored as variables under the same scoping rules as ordinary variables. There are two ways to declare functions: function log_name () { } and: var log_name = function () { } Both of these are the same. Which means it’s possible to inadvertently overwrite a function with another variable declaration: function name () { return "David"; } var name = "John"; name(); // error, name is not a function anymore Hoisting JavaScript interpreters have a initial-runtime phase, (similar to Perl’s BEGIN), where all variable declarations are executed before other code. This is known as “hoisting”, but practically what it means is that you can use a variable before you declare it! console.log(name); // yep, this works var name = "David"; Bind JavaScript makes heavy use of anonymous functions and callbacks.To modify the scope of a function, JavaScript1 provides bind. This is easier to understand by example. If I have a point object and I want a method to draw it to the canvas, by loading an image: Point.prototype.draw = function() { var ctx = get_canvas_context(); // declared elsewhere var img = new Image(); img.onload = function () { // anonymous function ctx.drawImage(img, this.x, this.y); }.bind(this); img.src = "/point.png"; } Here I use bind to inject the point object’s scope into the anonymous function. Otherwise I wouldn’t be able to access the x and y properties of the point as this would be referencing something else. For a more thorough explanation of JavaScript scope, I recommend Todd Motto’s article, Everything you wanted to know about JavaScript scope. Coping with scoping OK so that was the bad news; the good news is there are plenty of techniques for handling JavaScript’s scoping rules. Depending on the context you may find some or all of these methods useful. Naming conventions The first thing you can do to avoid clashes is adopt a naming convention. For example, name all functions with verb-noun constructs (like “get_address”) and all value variables with plain nouns (like “addresses”). This is not a complete solution, but at a minimum it will reduce the chances of a function being replaced by a value variable. One var per scope Another technique for managing variable scope is to only allow one var statement per scope. So a typical program might look like this: // declare global scope variables var foo = "/root/assets", bar = 0; function execute (foo) { var i, j, bar; // functional scope for (i = 0; i < foo.length; i++) { for (j = 0; j < foo.length; j++) { // do something } } } Use strict This is a convention all Perl programmers should be comfortable with. Enable strict mode in JavaScript. Just like with Perl, JavaScript’s strict mode can catch several cases of variable-related bugs. Enable it globally with: "use strict"; Generally JavaScript experts recommend using a functionally-scoped version of strict - in this case the declaration is placed inside a function block. This is useful to prevent script concatenation errors (where an imported script does not satisfy the strict rules). (function () { "use strict"; // this function is strict... }()); Objects as namespaces If you were thinking a simple way to solve all of the namespace clashes was with modules, allow me to be the first to tell you that JavaScript has no notion of modules (being a prototyped language). There is no import keyword. In HTML any code that is loaded with a script tag is simply concatenated to the current scope. There are solutions to this limitation though. In JavaScript the Definitive Guide, author David Flanagan proposes using objects as namespaces (sixth edition, section 9.9.1). Each object’s scope can be used to encapsulate the behavior and data specific to that domain. For example: // everything is scoped to point.* var point = {}; point.Point = function (_x, _y) { this.x = _x; this.y = _y } point.Point.prototype.coordinates = function () { return [this.x, this.y]; } // now lets try it out ... var p = new point.Point(1,3); console.log(p.coordinates()); To package code as modules, there is the module pattern. Finally although JavaScript has no native import method, there are several external libraries that can provide that behavior, like RequireJS. Let The next major version of JavaScript, ES6 provides let. This keyword provides block-level scoping of variables, similar to other mainstream languages. ES6 is not supported everywhere yet, but you can use a transpiler like Babel to convert ES6 JavaScript back to ES5. Use a code linter Browsers do not throw enough exceptions when processing JavaScript. Instead they try to soldier on and do what the programmer meant rather than what they typed. This is good2 for users as they get a uninterrupted browsing experience, but for us programmers this is definitely a bad thing™. Browser robustness makes JavaScript difficult to debug, and which is where a code linter steps in - it analyzes code and reports any errors or warnings they find. For JavaScript I like JSHint. 1 Introduced in ES5 JavaScript - which is supported by all modern browsers. For solutions for older JavaScript versions, use call or apply. 2 It’s probably a bad thing for users too - the overhead in processing syntactically wrong code degrades performance and worse, encourages more incorrect code to be written. This article was originally posted on PerlTricks.com.
https://www.perl.com/article/204/2015/12/17/Kitchen-coding-nightmares--JavaScript-scope/
CC-MAIN-2019-09
refinedweb
1,076
64.51
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index] Re: st: Function el() fails: > Dear All, > > after investigating why my program sometimes breaks, I have found a > problem (observed in Stata 9 and Stata 10 for Windows) with the > function el(matrixname, row, col ), which could be reproduces with the > following sequence of commands: > > > // ----- BEGIN ------- > sysuse auto > > matrix p=1 > matrix a=p > > matrix dir > > matrix list a > di a[1,1] > di el(a,1,1) > > matrix list p > di p[1,1] > di el(p,1,1) > // ----- END ------- > > According to the help file for Stata 9: > > el(A,i,j) the i,j element of A (same as A[i,j]) > > Note that the program above works for matrix name "a" and not "p". > This made it difficult to identify the problem. Because the problem is > observed for some datasets and not for others. > > It seems that the namespace of variables and matrix names in Stata is > overlapping. > I've met the messages earlier regarding what namespaces are shared, > but I can't find them at the moment. The manual explicitly defines the > term "namespace" in the [P] matrix, (page 235 in 10th edition). It > also mentions that there is a single namespace for scalars and > matrices, however it does mention variables in a rather confusing > statement: > > "Scalars and matrices share the same namespace; i.e., scalars and > matrices may have the same names as variables in the dataset, etc., > but they cannot have the same names as each other." > > Confusion here is that indeed Stata allows me to have a matrix with > the same name as a variable, but I'd really like the built-in commands > and functions to be able to WORK with that matrix. (Function el() as > all functions in Stata is built-in). > > I wonder if anyone could elaborate on which namespaces are shared in > Stata, in particular: > > variables > locals > globals > scalars > matrices > programs > classes > all sort of mata objects > all sort of graphics related styles, patterns, etc > .... > [not sure how long the list is, but the above list is definitely not complete] > > I am not sure that the problem above is an intended behavior. In any > case it makes the case that el(a,1,1) is NOT equivalent to A[1,1] > against what the help file says. > If this is not an intended behaviour, can this be fixed? > > Thank you, > Sergiy Radyakin > > CC: Stata Technical Support * * For searches and help try: * * *
http://www.stata.com/statalist/archive/2008-08/msg00652.html
CC-MAIN-2016-44
refinedweb
414
64.34
◕ A new product. Popular Google Pages: This article is regarding Use a Constant directly into C++ program, without declaring it? Last updated on: 09th December 2016. ◕ What will happen if we use a Constant directly into the C++ program, without declaring it? - When we use a Variable in C++ program, then the program declarations tell the C++ compiler about that Type of the Variable. But we can use a Constant directly into the C++ program, without declaring it. The example is given bellow: #include <iostream> using namespace std; int main(){ cout << "India: " << 1947 << endl; return 0; } The output is: India: 1974 - In the above example we use a constant directly without declaring it. ◕ How C++ will decide what type of constant it is? - C++ stores integer constants as int Type unless we declare it as Long or Unsigned. Related article: How to display a value in Hexadecimal form in C++? How to display a value in Octal form in C++? How C++ identify the base of a number? Popular Google Pages: Top of the page
http://riyabutu.com/c-plus-plus/use-constant-directly-in-program.php
CC-MAIN-2017-51
refinedweb
175
66.23
Python is not Java, nor is it C++ It’s different! Let’s talk about how. Why? Because as Python experts (you did choose to come to a Python conference so likely you’re either an expert already or in time you’re going to be come one if you keep going to Python conferences) we have a responsibility to help our colleagues and collaborators who don’t know Python as well we do. The part of that responsibility I want to focus on today is when other people have experience with other programming languages but are new to Python. I work at Dropbox, which as Guido said earlier today is a company that uses a fair bit of Python. But a lot of programmers come to Dropbox without having significant Python experience. Do these people take a few months off when they join to really focus on learning and figure out exactly how Python works, having a lot of fun while they do it? That would great (briefly shows slide of Recurse Center logo) but that’s not what usually happens. Instead they learn on the job, they start making progress right away. They’ll read some books (my favorite is Python Essential Reference, but I hear Fluent Python is terrific), watch some Python talks, read some blog posts, ask questions at work, and Google a lot. That last one is the main one, lots of Google and lots of Stack Overflow. Learning primarily by Googling can leave you with certain blind spots. If the way that you’re learning a language is by looking up things that are confusing to you, things that aren’t obviously confusing aren’t going to come up. We ought to be trying to understand our colleagues’ understandings of Python. This is a big thing whenever you’re teaching, whenever you’re trying to communicate with another person: trying to figure out their mental model of a situation and providing just the right conceptual stepping stones to update that model to a more useful state. Python-as-a-secondary-language empathy We should try to understand the understandings of Python of people coming to Python as a new language. I’m going to call this “Python-as-a-second-language empathy.” How do we build this PaaSL empathy thing? The best thing you can do is learn another language first, and then learn Python. Who here has another language that they knew pretty well before learning Python? (most hands go up) Great! Terrific! That’s a superpower you have that I can never have. I can never unlearn Python, become fluent in another language, and then learn Python again. You have this perspective that I can’t have. I encourage you to use that superpower to help others with backgrounds similar to your own. I’d love to see “Django for Salesforce Programmers” as a talk at a Python conference because it’s very efficient when teaching to be able to make connections to a shared existing knowledge base. Another thing you can do to build this PAASL empathy (I’m still deciding on an acronym) is to learn language that are different than the ones you know. Every time you learn a new language you’re learning new dimensions on which someone could have a misconception. Consider the following: a = b + c Depending on the languages you know, you might make different assumptions about the answers to the following questions: - Will a always be equivalent to the sum of b and c from now on, or will that only be true right after we run this code? - Will b + c be evaluated right now, or when a is used later? - Could b and c be function calls with side effects? - Which will be evaluated first? - What does plus mean, and how do we find out? - Is aa new variable, and if so is it global now? - Does the value stored in aknow the name of that variable? These are questions you can have and ways that someone might be confused, but if you’re not familiar with languages that answer these questions in different ways you might not be able to conceive of these misunderstandings. Another you thing you can do to build PSL empathy is listen. Listen to questions and notice patterns in them. If you work with grad students who know R and are learning Python, try to notice what questions repeatedly come up. In a general sense, this is what my favorite PyCon speaker Ned Batchelder does a wonderful job of. Ned is a saint who spends thousands of hours in the #python irc channel repeatedly answering the same questions about Python. He does a bunch of other things like run the Boston Python Users Meetup group, and he coalesces all this interaction into talks which concisely hit all the things that are confusing about whatever that year’s PyCon talk is. The final idea for building Py2ndLang empathy I’ll suggest is learning the language that your collaborator knows better so you can better imagine what their experience might be like. If you colleague is coming from Java, go learn Java! For this talk I did a mediocre job of learning C++ and Java. I did some research so I could try to present to you some of the things that could be tricky if you’re coming to Python from one of these languages. I chose these languages because they’re common language for my colleagues. It’s very reasonable to assume that a programming language will work like a language you already know, because so often they do! But then when there’s a difference it’s surprising. C++ and Java are not my background! While Python was the first language I really got deep into, I had previous exposure to programming that colored my experience learning Python. My first programming language was TI-81 Basic, then some Excel that my mom taught me. In the Starcraft scenario editor you could write programs with a trigger language, so I did some of that. In middle school I got to use Microworlds Logo, which was pretty exciting. I did a little Visual Basic, got to college and did some MATLAB and some Mathematica, and then I took a CS course where they taught us Python. My misconceptions about Python were so different than other students’, some of whom had taken AP Computer Science with Java in high school. The languages I learned were all dynamically typed languages with function scope, so I didn’t have the “where are my types?” reaction of someone coming from Java. Java and C++ are good languages to focus on because they’re often taught in schools, so when interviewing or working with someone right out of undergrad it can be useful to try to understand these languages. Before we get to a list of tricky bits, there are some thinks I won’t talk about because I don’t call then “tricky.” Not that they aren’t hard, but they aren’t pernicious, they’re misunderstandings that will be bashed down pretty quickly instead of dangerously lingering on. New syntax like colons and whitespace, new keywords like yield; Python gives you feedback in the form of SyntaxErrors about the first group, and there’s something to Google for with the second. When you first see a list comprehension in Python, you know there’s something not quite normal about this syntax, so you know to research it or ask a question about it. Tricky Python From Java/C++ Cheatsheet Let’s split things that are tricky about Python for people coming from Java or C++ into three categories: things that look similar to Java or C++ but behave differently, things that behave subtly differently, and “invisible” things that leave no trace. The first category is tricky because you might not think to look up any differences, the second because you might test for differences and at a shallow level observe none when in fact some lurk deeper. The third is tricky because there’s no piece of code in the file you’re editing that might lead you to investigate. These are pretty arbitrary categories. Look similar, behave differently Decorators There’s a think in Java called an annotation that you can stick on a method or a class or some other things. It’s a way of adding some metadata to a thing. And then maybe you could do some metaprogramming-ish stuff where you look at that metadata later and make decisions about what code to run based on them. But annotations are much less powerful than Python decorators. >>> @some_decorator ... def foo(): ... pass ... >>> foo <quiz.FunctionQuestion object at 0x10ab14e48> Here (in Python) a python decorator is above a function, but what comes out is an instance of a custom class “FunctionQuestion” - it’s important to remember that decorators are arbitrary code and they can do anything. Somebody coming from Java might miss this, thinking this is an annotation adding metadata that isn’t transforming the function at definition time. Class body assignments create class variables I’ve seen some interesting cool bugs before because of this. The two assignments below are two very different things: class AddressForm: questions = ['name', 'address'] def __init__(self): self.language = 'en' questions is a class attribute, and language is an instance attribute. These are ideas that exist in Java and C++ with slightly different names ( questions might be called a “static” variable, and language called a “member” variable), but if you see something like the top in one of those languages people might assume you’re initializing attributes on an instance; they might think the first thing is another way of doing the second. Run-time errors, not compile-time Here I’ve slightly misspelled the word “print:” if a == 2: priiiiiiiiiiiiint("not equal") This is valid Python code, and I won’t notice anything unusual about it until a happens to be 2 when this code runs. I think people coming from languages like Java and C++ with more static checks will get bitten by this before too long and get scared of it, but there are a lot of cases for them to think about. try: foo() except ValyooooooooooError: print('whoops)' Here’s I’ve slightly misspelled ValueError, but I won’t find out until foo() raises an exception. try: foo() except ValueError: priiiiiiiiiiiiiiint('whoops)' Here ValueError is fine, but the code below it won’t run until foo() raises an exception. Conditional and Run-Time Imports Particularly scary examples of the above issue feature imports because people may think imports work like they do in Java or C++: something that happens before a program runs. try: foo() except ValueError: import bar bar.whoops() It’s not until foo() raises a ValueError that we’ll find out whether the bar module is syntactically valid because we hadn’t loaded it yet, or whether a file called bar.py exists at all! Block Scope This might blow your mind if you’re mostly familiar with Python: there’s this idea called block scope. Imagine that every time you indented you got a new set of local variables, and each time you dedented those variables went away. People who use Java or C++ are really used to this idea, they really expect that when they go out of a scope (which they use curly brackets to denote, not indentation) that those variables will go away. As Python users, we might know that in the below, def foo(): bunch = [1, 2, 3, 4] for apple in bunch: food = pick(apple) print(apple) print(food) the variables apple and bunch “escape” the for loop, because Python has function scope, not block scope! But this sneaks up on people a lot. Introducing Bindings This above is sort of a special case of something Ned Batchelder has a great talk about, which is that all the statements below introduce a new local variable X: X = ... for X in ... [... for X in ...] (... for X in ...) {... for X in ...} class X(...): def X(...): def fn(X): ... ; fn(12) with ... as X: except ... as X: import X from ... import X import ... as X from ... import ... as X (these examples taken from the talk linked above) import in a function introduces a new local variable only accessible in that function! Importing in Python isn’t just telling the compiler where to find some code, but rather to run some code, stick the result of running that code in a module object, and create a new local variable with a reference to this object. Subtle behavior differences Assignment Python = is like Java, it’s always a reference and never a copy (which it is by default in C++). Closures A closure is a function that has references to outer scopes. (mostly - read more) C++ and Java have things like this. Lambdas in C++ require their binding behavior to be specified very precisely, so each variable might be captured by value or by reference or something else. So a C++ programmer will at least know to ask the question in Python, “how is this variable being captured?” But in Java the default behavior is to make the captured variable final, which is a little scarier because a Java programmer might assume the same about Python closures. GC It’s different! We have both reference counting and garbage collection in Python. This makes it sort of like smart pointers in C++ and sort of like garbage collection in Java. And __del__ finalizer doesn’t do what you think it does in Python 2! Explicit super() In Java and C++ there exist cases where the parent constructor for an object will get called for you, but in Python it’s necessary to call the parent method implementation yourself with super() if a class overrides a parent class method. Super is a very cooperative sort of thing in Python; a class might have a bunch of superclasses in a tree and to run all of them requires a fancy method resolution order. This works only so long every class calls super. I’ll translate this one to the transcript later - for now you’ll have to watch it because the visual is important: explicit super. Invisible differences Properties and other descriptors It can feel odd to folks coming from C++ or Java that we don’t write methods for getters and setters in Python; we don’t have to because ordinary attribute get and set syntax can cause arbitrary code to run. obj.attr obj.attr = value This is in the invisible category because unless you go to the source code of the class it’s easy to assume code like this only reads or writes a variable. Dynamic Attribute Lookup Attribute lookup is super dynamic in Python! Especially when writing tests and mocking out behavior it’s important to know (for instance) that a data descriptor on a parent class will shadow an instance variable with the same name. Monkeypatching Swapping out implementations on a class or an instance is going to be new to people. It could happen completely on the other side of your program (or you test suite) but affect an object in your code. Metaprogramming It takes less characters in Python! get_user_class("employee")("Tom", 1) The code above returns a class object based on the string “employee” and then creates an instance of it. It might be easy to miss this if you expect metaprogramming to take up more lines of code. Python 2 Whitespace Trivia A tab is 8 spaces in Python 2 for the purposes of parsing significant whitespace, but is usually formatted as 4! What do we do with this? Should we try to teach everyone all these things right now? Maybe not! If someone is interested, sure. But I think it’s hard to hit all of these without much context. And be careful not to assume people don’t know these things, maybe they do know 80% of them. I think this cheat sheet presents things that are important to be aware of while teaching whatever other topic is most pedagogically appropriate. I don’t have time to talk much about teaching, so I’ll point to Sasha Laundy’s talk (embedded above) which I love, and quickly quote Rose Ames and say that “knowledge is power; it’s measured in wats.” I think a great way to broach a misunderstanding is to present someone with a short code sample “wat” that demonstrates a misconception exists without necessarily explaining it because often all someone needed was to have the a flaw in their model pointed out to them. Code review is a great impetus for sending someone such a wat. I don’t have time to talk about code review so I’ll point to this terrific post by Sandya Sankarram about it. Another thing we can do with this information is to write it in code comments. I think of comments as the place to explain why code does a thing, not to explain what that code is doing. But if you know what’s happening in your code might surprise someone less familiar with Python, maybe you should say what it’s doing? Or maybe you should write simpler code and not do that interesting Python-specific thing. In the same way Python library authors sometimes write code that straddles Python 2 and 3 by behaving the same in each, imagine writing Python code that, if it were Java or C++, would do the same thing. Perhaps you’d have quite unidiomatic code, but perhaps it’d be quite clear. image from this Stack Overflow blog post Python is becoming more popular. Maybe this means more people will understand it, and we’ll get to use all our favorite Python-specific features all the time! Maybe this will mean Python becomes the lingua franca which ought to be as simple and clear as possible. I imagine it will depend on the codebase. I think as a code base grows tending toward code that is less surprising to people who do not know Python well probably makes more sense. One final use for this cheat sheet is interviewing: interviewing is a high time pressure communication exercise where it really can help to try to anticipate another person’s understanding of a thing. Candidates often interview with Python, but know C++ or Java better. If I can identify a misunderstanding like initializing instance variables in the class statement, I can quickly identify it, clarify with the candidate, and we can move on. Or perhaps I don’t even need to if the context is clear enough. And when I’m interviewing at companies, it’s helpful to remember what parts of my Python code I might need to explain to someone not as familiar with the language.
http://ballingt.com/python-second-language-empathy/
CC-MAIN-2018-34
refinedweb
3,160
67.89
MySQL Python/Connector is an interface for connecting to a MySQL database server from Python. It implements the Python Database API and is built on top of MySQL. For installing MySQL-connector-python first you have to open your terminal and execute the following code pip install mysql-connector-python After installation, you have to import that package into your code and define your database name and other entities using connect(). You can establish a connection using the connect() constructor. This accepts the username, password, host and, name of the database you need to connect with (optional) and, returns an object of the MySQLConnection class. … MySQL is an open-source relational database management system based on SQL — Structured Query Language. The application is used for a wide range of purposes, including data warehousing, e-commerce, and logging applications. The most common use for MySQL however, is for the purpose of a web database. To view all the existing databases you can use the below syntax show databases; In this story, we are gonna see some questions on manipulation of some student's data and the solution will be composed of various python libraries such as pandas, regex, and numpy. Consider, data=pd.DataFrame({‘names’:[‘tom’,’sam’,…],’email’:[‘tom21@gmail.com’,’samdr@yahoo.com’,’jk21456@abc.com’,..],’Firstweekscore’:[],’secondweekscore:[]}) 1.Write a function that will create a new column consisting of an average of two scores 2.List comprehension → create another column which is consisting of scores 93 → 96 3.’gmail.com’ →regular expressions in pandas 4.Select rows which are having gmail address and also secondtestscore greater than 90 5.Create a new column ‘group’ and randomly assign values as 1,2 and 3 6.Create a pivot table having means… Pandas is a software library written for the Python programming language. It is used for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. We can install pandas by entering the following line of code in our command prompt. We have to import it every time we use it like every other predefined module in Python. pip install pandas #Installationimport pandas as pd #Importing Unlike NumPy, pandas has three data structures based on the array’s dimension, They are: Among the above three data structures, panel… NumPy stands for Numerical Python. NumPy is an open-source numerical Python library. NumPy contains a multi-dimensional array and matrix data structures. It can be utilized to perform a number of mathematical operations on arrays such as trigonometric, statistical, and algebraic routines. We can install NumPy by entering the following line of code in our command prompt and we have to import it every time we use it like every other predefined module in python pip install numpyimport numpy as np Unlike python, the only data structure in the numpy is an array, and that array can support only one… Abstraction in Python is the process of hiding the real implementation of an application from the user and emphasizing only how to use the application. An abstract method is also known as an incomplete method where we can only implement it in the children's classes. By default, Python does not provide abstract classes. Python comes with a module that provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works by decorating methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. … A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.RegEx can be used to check if a string contains the specified search pattern. In python, RegEx can be used from a module called re, which must be imported in order to work with the regular expressions. import re There are many keyword patterns used in RegEx in order to form a search pattern, you can have a brief look at them on RegexOne. The match function is used to check whether the given pattern matches with the strings at the beginning of the string. import… Python super() function is used for accessing the methods and properties of the base class or superclass, basically a super function returns a proxy object. For example: class Person: def __init__(self,name,age): self.name = name self.age = age class Student(Person): def __init__(self,name,age,grade): super().__init__(name,age) self.grade = grade def printGrade(self): print('Student name is {} age is{} and Grade is{}'.format(self.name,self.age,self.grade))stud1 = Student('tom',24,'A') stud1.printGrade()Student name is tom age is 24 and Grade is A From the above program, we can see that we have used the instances of the parent class in the child class using the super keyword, like this we can… There are different types of methods are there while defining a class, they are Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute, let us see an example class Student: def __init__(self,name): self.name = name def printinfo(self): self.city = 'delhi' print('my name is {} and from {}'.format(self.name,self.city)) def printcity(self): print('my city is ', self.city)stud1 = Student('tom') stud1.printinfo()my name is tom and from delhi It is one of the rarely used methods, where we use cls instead of self and we…… Engineer
https://nandhabalanmarimuthu.medium.com/?source=post_internal_links---------7----------------------------
CC-MAIN-2021-21
refinedweb
913
53.21
import "github.com/cloudflare/tableflip" Package tableflip implements zero downtime upgrades. An upgrade spawns a new copy of argv[0] and passes file descriptors of used listening sockets to the new process. The old process exits once the new process signals readiness. Thus new code can use sockets allocated in the old process. This is similar to the approach used by nginx, but as a library. At any point in time there are one or two processes, with at most one of them in non-ready state. A successful upgrade fully replaces all old configuration and code. To use this library with systemd you need to use the PIDFile option in the service file. [Unit] Description=Service using tableflip [Service] ExecStart=/path/to/binary -some-flag /path/to/pid-file ExecReload=/bin/kill -HUP $MAINPID PIDFile=/path/to/pid-file Then pass /path/to/pid-file to New. You can use systemd-run to test your implementation: systemd-run --user -p PIDFile=/path/to/pid-file /path/to/binary systemd-run will print a unit name, which you can use with systemctl to inspect the service. NOTES: Requires at least Go 1.9, since there is a race condition on the pipes used for communication between parent and child. If you're seeing "can't start process: no such file or directory", you're probably using "go run main.go", for graceful reloads to work, you'll need use "go build main.go". This shows how to use the upgrader with the graceful shutdown facilities of net/http.) } } }() // Listen must be called before Ready ln, err := upg.Listen("tcp", *listenAddr) if err != nil { log.Fatalln("Can't listen:", err) } server := http.Server{ // Set timeouts, etc. } go func() { err := server.Serve(ln) if err != http.ErrServerClosed { log.Println("HTTP server:", err) } }() log.Printf("ready") if err := upg.Ready(); err != nil { panic(err) } <-upg.Exit() // Make sure to set a deadline on exiting the process // after upg.Exit() is closed. No new upgrades can be // performed if the parent doesn't exit. time.AfterFunc(30*time.Second, func() { log.Println("Graceful shutdown timed out") os.Exit(1) }) // Wait for connections to drain. server.Shutdown(context.Background()) This shows how to use the Upgrader with a listener based service.) } } }() ln, err := upg.Fds.Listen("tcp", *listenAddr) if err != nil { log.Fatalln("Can't listen:", err) } go func() { defer ln.Close() log.Printf("listening on %s", ln.Addr()) for { c, err := ln.Accept() if err != nil { return } go func() { c.SetDeadline(time.Now().Add(time.Second)) c.Write([]byte("It is a mistake to think you can solve any major problems just with potatoes.\n")) c.Close() }() } }() log.Printf("ready") if err := upg.Ready(); err != nil { panic(err) } <-upg.Exit() child.go doc.go dup_file.go env.go fds.go parent.go process.go upgrader.go DefaultUpgradeTimeout is the duration before the Upgrader kills the new process if no readiness notification was received. Conn can be shared between processes. Fds holds all file descriptors inherited from the parent process. AddConn adds a connection. It is safe to close conn after calling this method. AddFile adds a file. Until Go 1.12, file will be in blocking mode after this call. AddListener adds a listener. It is safe to close ln after calling the method. Any existing listener with the same address is overwitten. Conn returns an inherited connection or nil. It is safe to close the returned Conn. File returns an inherited file or nil. The descriptor may be in blocking mode. Listen returns a listener inherited from the parent process, or creates a new one. Listener returns an inherited listener or nil. It is safe to close the returned listener. Listener can be shared between processes. type Options struct { // Time after which an upgrade is considered failed. Defaults to // DefaultUpgradeTimeout. UpgradeTimeout time.Duration // The PID of a ready process is written to this file. PIDFile string } Options control the behaviour of the Upgrader. Upgrader handles zero downtime upgrades and passing files between processes. New creates a new Upgrader. Files are passed from the parent and may be empty. Only the first call to this function will succeed. Exit returns a channel which is closed when the process should exit. HasParent checks if the current process is an upgrade or the first invocation. Ready signals that the current process is ready to accept connections. It must be called to finish the upgrade. All fds which were inherited but not used are closed after the call to Ready. Stop prevents any more upgrades from happening, and closes the exit channel. If this function is called before a call to Upgrade() has succeeded, it is assumed that the process is being shut down completely. All Unix sockets known to Upgrader.Fds are then unlinked from the filesystem. Upgrade triggers an upgrade. WaitForParent blocks until the parent has exited. Returns an error if the parent misbehaved during shutdown. Package tableflip imports 16 packages (graph) and is imported by 3 packages. Updated 2019-11-05. Refresh now. Tools for package owners.
https://godoc.org/github.com/cloudflare/tableflip
CC-MAIN-2019-51
refinedweb
843
62.34
There are a large number of recurring questions on creating dialog-based apps. This is my method of creating dialog-based apps, and in addition, illustrates how to handle the Enter key in an edit control. The most common problems people ask about are "How do I trap the ESC key so it doesn't terminate my application?" and "How do I trap the Enter key so it doesn't terminate my application?". These are easy. First, I do not believe in handling this in PreTranslateMessage. The result of this is distributed knowledge which makes it difficult to maintain the code, particularly when controls are added or deleted. My technique uses subclassing to put the intelligence where it belongs, in the control, and puts the handlers in a known and easily understood place, a message handler. First, create your dialog-based application. You will end up with something that resembles the dialog below (which I've shrunk so it doesn't take up too much space on the page): Enter the ClassWizard. Select IDOK and its BN_CLICKED handler, and click Add Function. Accept the name it gives. Do the same for IDCANCEL. You should end up with something that looks like the illustration shown below. I show the IDCANCEL handler clicked, since that is the last one I added (note that two lines below, the ON_IDOK::BN_CLICKED handler is already present). Next, select the dialog class, and find the WM_CLOSE message handler. Click Add Function. You should now have something like I show below: Go to your source code and examine it. You can either exit ClassWizard via the OK button, or click the Edit Code button. Your code should look like this: void CDialogappDlg::OnOK() { // TODO: Add extra validation here CDialog::OnOK(); } void CDialogappDlg::OnCancel() { // TODO: Add extra cleanup here CDialog::OnCancel(); } void CDialogappDlg::OnClose() { // TODO: Add your message handler code here and/or call default CDialog::OnClose(); } Change it to be as shown below. Delete the bodies of OnOK and OnCancel. Put the CDialog::OnOK call in the OnClose handler. void CDialogappDlg::OnOK() { } void CDialogappDlg::OnCancel() { } void CDialogappDlg::OnClose() { CDialog::OnOK(); } Go back to the dialog. Delete the OK and Cancel buttons. Add in your controls. For example, I want to add an edit control that reacts only when you either leave it or hit Enter, and prior to that it can be changed without any effect. The other control reacts immediately. To create an edit control that reacts immediately, put in an EN_CHANGE handler. Also, create a member variable for the control; I describe how to do this in a companion essay. In order to access the status control which will show the effect, you must assign it an ID other than IDC_STATIC. Create a control variable to represent it. I end up with variables as shown below (note that I have not yet created a variable for IDC_DELAYED): The code for immediate response is simple: void CDialogappDlg::OnChangeImmediate() { CString s; c_Immediate.GetWindowText(s); c_Status.SetWindowText(s); } When running, it produces output such as: As each character is typed in the "Immediate Reaction" edit control, it appears in the box labeled "I see". However, I might not want a reaction to take place until I hit Enter, or leave focus, or both. To do this, I create a subclass of CEdit: Create a class derived from CEdit, which I have called CEnterEdit. Now create a member variable for IDC_DELAYED of that type: Which should leave you with the following definitions: In ClassWizard, select the new class you defined. (Note that if you are continuing from the previous step, you will be prompted to save your changes; select "Yes"). Add handlers for =EN_KILLFOCUS, WM_CHAR, and WM_GETDLGCODE: You must remember to add the header file for your new class to your compilations before any file that uses it. For a dialog-based app, this means the app source and the dialog source must both have it, for example: #include "stdafx.h" #include "dialogapp.h" #include "EnterEdit.h" #include "dialogappDlg.h" Otherwise, you will get compilation errors whenever your ...Dlg.h file is processed. If you use a custom message, you must define it. I prefer to use Registered Window Messages, as outlined in my companion essay, so I added to EnterEdit.h the following declaration. Note that it is critical that when you add a user-defined message, you document its parameters, effect and return result! Doing anything less will lead to unintelligible and unmaintainable code. /**************************************************************************** * UWM_EDIT_COMPLETE * Inputs: * WPARAM: Control ID of the control whose edit completed * LPARAM: CWnd * of the control whose edit completed * Result: LRESULT * Logically void, 0, always * Effect: * Posted/Sent to the parent of this control to indicate that the * edit has completed, either by the user typing <Enter> or focus leaving ****************************************************************************/ #define UWM_EDIT_COMPLETE_MSG _T("UWM_EDIT_COMPLETE-{165BBEA0-C1A8-11d5-A04D-006067718D04}") I declare it in EnterEdit.cpp as shown below, or you could use the more convenient DECLARE_MESSAGE macro I defined in my companion essay. static UINT UWM_EDIT_COMPLETE = ::RegisterWindowMessage(UWM_EDIT_COMPLETE_MSG); This allows me to write the handlers I need. First, in order to bypass the tendency of the dialog superclass to intercept and handle keyboard input, you should make the indicated change in the OnGetDlgCode handler: UINT CEnterEdit::OnGetDlgCode() { return CEdit::OnGetDlgCode() | DLGC_WANTALLKEYS; } This tells the dialog superclass that when focus is in this control, it should deliver to it all the keys pressed. Then, in your OnChar handler, you can do void CEnterEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { switch(nChar) { /* nChar */ case VK_RETURN: GetParent()->SendMessage(UWM_EDIT_COMPLETE, GetDlgCtrlID(), (LPARAM)this); return; } /* nChar */ CEdit::OnChar(nChar, nRepCnt, nFlags); } Why a switch with only one case? Why not? It makes it easy to add other cases, and captures the fact that you are concerned at the moment with some finite set of characters. I prefer switch statements in such contexts. They eliminate the temptation to add complex if- then- else structures, resulting in cleaner and easier-to-maintain code. When an Enter key is seen, the message is sent to the parent which can then react to it. To handle processing when focus is lost, modify the reflected =EN_KILLFOCUS handler as shown below: void CEnterEdit::OnKillfocus() { GetParent()->SendMessage(UWM_EDIT_COMPLETE, GetDlgCtrlID(), (LPARAM)this); } Now you need to add a handler to the parent. This means you must declare a UINT for the Registered Window Message just like you did in the child edit control, and add the indicated message to the MESSAGE_MAP: BEGIN_MESSAGE_MAP(CDialogappDlg, CDialog) ON_REGISTERED_MESSAGE(UWM_EDIT_COMPLETE, OnEditComplete) //{{AFX_MSG_MAP(CDialogappDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_CLOSE() ON_EN_CHANGE(IDC_IMMEDIATE, OnChangeImmediate) //}}AFX_MSG_MAP END_MESSAGE_MAP() IMPORTANT: This should be outside (above or below; I show above) the magic AFX_MSG_MAP comments! Otherwise you can confuse the ClassWizard. You must add a handler to the declarations in your header file: afx_msg LRESULT OnEditComplete(WPARAM, LPARAM); // Generated message map functions //{{AFX_MSG(CDialogappDlg) virtual BOOL OnInitDialog(); IMPORTANT: This must be outside (above or below, I show above) the magic AFX_MSG comments. Otherwise you can confuse the ClassWizard. The handler could look like the one I show here: LRESULT CDialogappDlg::OnEditComplete(WPARAM, LPARAM lParam) { CEnterEdit * edit = (CEnterEdit *)lParam; CString s; edit->GetWindowText(s); c_Status.SetWindowText(s); return 0; } // CDialogappDlg::OnEditComplete In this simple example, I don't care which window generated the message, so I ignore WPARAM, and whatever control was activated, I simply set its text into the status window. In a dialog with many controls, you would probably want to switch on the WPARAM value. Now when I run the app, and type text into the "Delayed Reaction" box, I see the following. Note that the contents of the "I see" status box is whatever was left from the previous typing. But if I hit Enter or change focus, I will get the following result. The new text is in the "I See" box, and the focus (as shown by the caret) is still in the "Delayed Reaction" box. Or, if I switch focus, I will also see the effect. Note that by doing this on a kill focus, I will also see the text activate if I switch to another application. If this is not desired, don't use the =EN_KILLFOCUS reflector, or you must do a more complex test. Note that starting from the first picture, I get the result shown below when I change focus to the upper window. Many people have commented on this technique, "You are creating another subclass. Why do you feel you need to do this?" Never be afraid to create a custom subclass. I have been known to create a dozen in one day. It is a natural paradigm for MFC programming. These are the techniques I use to build real software that is used by thousands of people and maintained by someone other than myself. The views expressed in these essays are those of the author, and in no way represent, nor are they endorsed by, Microsoft. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/dialog/create_a_dialog.aspx
crawl-002
refinedweb
1,488
53.92
Hold:. - From the IIS snap-in, right-click on the Web Sites node and click on Properties - Select the Service tab - Enable Compress application files - Enable Compress static files - Change Temporary Directory to the folder that you created above, or leave it at it's default - Set the max size of the temp folder to something that the hard drive can handle. i.e. 1000. - Save and close the Web Site Properties dialog Note: The temporary compress directory is only used for static pages. Dynamic pages aren't saved to disk and are recreated every time so there is some CPU overhead used on every page request for dynamic content.. - Open the metabase located at C:\Windows\system32\inetsrv\metabase.xml in Notepad- Search for <IIsCompressionScheme -. Falsecscript C:\Inetpub\AdminScripts\adsutil.vbs set w3svc/site#/root/DoDynamicCompression False Note: I was emailed by a reader, David Waters, who noticed a mistake in the Microsoft's documention on adding custom extensions as asked if I would point it out here. The example adds quotes which shouldn't be added. For example, the following: cscript adsutil.vbs SET W3SVC/Filters/Compression/Deflate/HcFileExtensions "htm html txtnewext" should instead be cscript adsutil.vbs SET W3SVC/Filters/Compression/Deflate/HcFileExtensions htm html txt newextJust remove the quotes and it will run as it is supposed to. Follow-up blog: IIS Compression in IIS6.0 Hold on to your hats folks. If you don't have compression installed on your...。我反复看了一下大多数JOB都是有用,都觉得不应该停,呵...。... It is very tricky! It is easy to setup to make it work. But when I turned it off and turned it back. It does't work. When I checked metadata.xml, I found both HcDoDynamicCompression and HcDoOnDemandCompression is FALSE even if enabled compression on IIS service. So I set them to TRUE, and it worked again. What is the difference between dynamic,ondemand? And how to set compression on one virtual site? When you changed the metadata.xml, make sure you reset IIS and also delete all off-line files on your IE. Then the change will take effect. Here are a few good links on IIS 6 compression. IIS6 compression by Scott Forsyth Zdroje: HOW TO: Enable ASPX Compression in IIS PingBack from This is a great blog, thanx. This is working great for compressing the HTTP response content back from server to client.? I am having problem while rendering pdf report when compression is enabled. It displays blank page everytime. If I disable compression it works fine. I tried by adding pdf in script mappings but it didnt work. My other pages are compressed OK as I verified it using Fiddler. This worked perfect first time. Thanks for posting this. 250k pages now compressing down to 35k, well worth it when users are overseas. Good looking blog too. For x64 versions the gzip dll path is now C:\windows\SysWOW64\inetsrv\gzip.dll As anybody actually been able to turn off compression at the file level? Setting DoDynamicCompression to FALSE in the Metabase on files (or folders) didn't work, it only worked at the global level (HcDoDynamicCompression) : <IIsWebFile Location="/LM/W3SVC/1/ROOT/App/output_pdf.aspx" DoDynamicCompression="FALSE" > This is to prevent the dynamic pdf outputting bug mentioned years ago in this article's comments. Anything I could have missed? Thanks for any help... Shaun, The trick is to get an entry for the file in the metabase so that the command does something. What you can do is from the IIS Manager, make a slight change and change it back again. This will create an entry in the metabase for that file. For example, turn off the Log visits, apply, then turn it back on again and apply the settings. Then it should work. i.e. cscript C:\Inetpub\AdminScripts\adsutil.vbs set w3svc/1/root/App/output_pdf.aspx/DoStaticCompression False cscript C:\Inetpub\AdminScripts\adsutil.vbs set w3svc/1/root/App/output_pdf.aspx/DoDynamicCompression False With IIS 6.0 Compression enabled, can I use that for compressing .js and/or .css files?? I tried to add "js" to the HCFileExtensions and HCScriptFileExtensions in the Metabase file (separately and together), but I see the entries are removed after doing an IISReset... has anyone compressed javascript or Css files?? Is it even possible without third-party plugins?? OWScott, Hey I tried your mechanism, and it worked well. I have a situation where I want a particular type of file to not be downloaded as a compressed file so I went to the IIS manager and made a change to the file just as you suggested. Then I ran the ADSUTIL command as stated above to turn off dynamic compression for that one file. I was able to successfully download the files appropriately. Thanks for the solution. Scott, thanks for the great article. I have one question, though: how should I proceed if I need to update any static files (css or js, for example)? IIS Compression 'caches' them and their changes won't show up. How can I force IIS to update the compressed version? Does it have something to do with HcCacheControlHeader? Thanks again for helping! I can't seem to get the compression to work. I followed your directions exactly and I am out of ideas. I need help! I've got an .aspx page that does the following: It pulls a byte[] from a database, response.clear(), sets response.contenttype, response.binarywrite() to the browser, then a response.end(), On IE 7, works great. On IE6, totally hosed. Windows 2003 server, IIS 6. Compression on, it's broken, compression off, works every time. PDF files work pretty consistenly, but .rtf, .tif, etc don't. Any clues? This article was great on explaining the server side. However, if you want to use webservices with anything but a webbrowser, here is some code that will help: I found some code online that with some bug fixes works well as a HttpWebResponse decompressed: using System.Net; using System.IO; using System.IO.Compression; namespace ClientsDataType { public class HttpWebResponseDecompressed : WebResponse { private HttpWebResponse response; public HttpWebResponseDecompressed(WebResponse wResponse) { response = (HttpWebResponse)wResponse; } public override void Close() response.Close(); public override Stream GetResponseStream() Stream compressedStream = null; if (response.ContentEncoding == "gzip") { compressedStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, false); } else if (response.ContentEncoding == "deflate") DeflateStream(response.GetResponseStream(), CompressionMode.Decompress, false); if (compressedStream != null) // Decompress MemoryStream decompressedStream = new MemoryStream(); int size = 2048; byte[] writeData = new byte[2048]; while (size > 0) { size = compressedStream.Read(writeData, 0, size); decompressedStream.Write(writeData, 0, size); } decompressedStream.Seek(0, SeekOrigin.Begin); compressedStream.Close();; } } } Now that you have a class that will decompress your web reponse, all you need is to override a couple methods in your proxy to make it work. (I wish Microsoft would update the proxy creation process to support compression, but right now it doesnt) Namespace ChatImplementation Partial Public Class ChatImplementation Protected Overrides Function GetWebRequest(ByVal uri As System.Uri) As System.Net.WebRequest Dim request As System.Net.WebRequest = MyBase.GetWebRequest(uri) request.Headers.Add("Accept-Encoding", "gzip, deflate") Return request End Function Protected Overrides Function GetWebResponse(ByVal request As System.Net.WebRequest) As System.Net.WebResponse Dim response As HttpWebResponseDecompressed = New _ HttpWebResponseDecompressed(MyBase.GetWebResponse(request)) Return response Protected Overrides Function GetWebResponse(ByVal request As System.Net.WebRequest, ByVal result As System.IAsyncResult) As System.Net.WebResponse HttpWebResponseDecompressed(MyBase.GetWebResponse(request, result)) End Class End Namespace But the important thing is the use of partial classes. This means even if we update our web proxy, it doesn't blow out this code everytime. I got both the sync and async code working, the later which is so much more usefull. The code is pretty straightforward on how it works, but reply to this post if you have any questions. Good luck. We are working in WSS3 and MOSS 2007 environment. We are trying to figure out how to display large pdf files in the brower as fast as possible. I've been trying to research page at a time or byte serving. Does anyone know about how IIS and sharepoint work with this? Also do you have any good articles or information i can read? Thanks in advance, Andy Does anyone know my all my .aspx pages show a size of "-1" when gzip is enabled in IIS6? Any tips appreciated. Thanks. Pingback from IIS6 Compression: other tidbits « You’re a smart guy, figure it out! If you haven't properly leveraged compression in IIS, you're missing out on a lot! Compression is a trade
http://weblogs.asp.net/owscott/archive/2004/01/12/IIS-Compression-in-IIS6.0.aspx
crawl-002
refinedweb
1,422
60.51
, and as a result packages are fundamentally non-modular: every package must use a distinct space in the global namespace.. - New: a module name must be unique within its package (only). That is, a single program can use two modules with the same module name, provided they come from different packages. This is new in GHC 6.6. The old system (no two modules with the same name in the same program) meant that EVERY module in EVERY package written by ANYONE must have different module names. That's like saying that every function must have different local variables, and is a serious loss of modularity. Hence the change. For all this to work, GHC must incorporate the package name (and version) into the names of entities the package defines. That means that when compiling a module M you must say what package it is part of: ghc -c -package-name P1 C.hs Then C.o will contain symbols like "P1.A.B.C.f" etc. In effect, the "original name" of a function f in module M of package P is <P,M.
https://ghc.haskell.org/trac/ghc/wiki/Commentary/Packages/GhcPackagesProposal?version=38
CC-MAIN-2015-22
refinedweb
185
73.68
I am playing with python and am able to get the intersection of two lists: result = set(a).intersection(b) d a b c d d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]] [3,4] for 2.4, you can just define an intersection function. def intersect(*d): sets = iter(map(set, d)) result = sets.next() for s in sets: result = result.intersection(s) return result for newer versions of python: the intersection method takes an arbitrary amount of arguments result = set(d[0]).intersection(*d[:1]) alternatively, you can intersect the first set with itself to avoid slicing the list and making a copy: result = set(d[0]).intersection(*d) I'm not really sure which would be more efficient and have a feeling that it would depend on the size of the d[0] and the size of the list unless python has an inbuilt check for it like if s1 is s2: return s1 in the intersection method. >>> d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]] >>> set(d[0]).intersection(*d) set([3, 4]) >>> set(d[0]).intersection(*d[1:]) set([3, 4]) >>>
https://codedump.io/share/a1rvAgcgOEq7/1/python--intersection-of-multiple-lists
CC-MAIN-2016-44
refinedweb
196
66.54
FAQ - .TH "FAQ" 3 "Thu Aug 12 2010" "Version 1.6.8" "avr-libc" FAQ - .SH "FAQ Index" 1. My program doesn't recognize a variable updated within an interrupt routine 2. I get 'undefined reference to...' for functions like 'sin()' 3. How to permanently bind a variable to a register? 4. How to modify MCUCR or WDTCR early? 5. What is all this _BV() stuff about? 6. Can I use C++ on the AVR? 7. Shouldn't I initialize all my variables? 8. Why do some 16-bit timer registers sometimes get trashed? 9. How do I use a #define'd constant in an asm statement? 10. Why does the PC randomly jump around when single-stepping through my program in avr-gdb? 11. How do I trace an assembler file in avr-gdb? 12. How do I pass an IO port as a parameter to a function? 13. What registers are used by the C compiler? 14. How do I put an array of strings completely in ROM? 15. How to use external RAM? 16. Which -O flag to use? 17. How do I relocate code to a fixed address? 18. My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken! 19. Why do all my 'foo...bar' strings eat up the SRAM? 20. Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly? 21. How to detect RAM memory and variable overlap problems? 22. Is it really impossible to program the ATtinyXX in C? 23. What is this 'clock skew detected' message? 24. Why are (many) interrupt flags cleared by writing a logical 1? 25. Why have 'programmed' fuses the bit value 0? 26. Which AVR-specific assembler operators are available? 27. Why are interrupts re-enabled in the middle of writing the stack pointer? 28. Why are there five different linker scripts? 29. How to add a raw binary image to linker output? 30. How do I perform a software reset of the AVR? 31. I am using floating point math. Why is the compiled code so big? Why does my code not work? 32. What pitfalls exist when writing reentrant code? 33. Why are some addresses of the EEPROM corrupted (usually address zero)? 34. Why is my baud rate wrong?; Back to FAQ Index.. Back to FAQ Index. This can be done with register unsigned char counter asm('r3');. Back to FAQ Index. The method of early initialization (MCUCR, WDTCR or anything else) is different (and more flexible) in the current version. Basically, write a small assembler file which looks like this: ;; begin xram.S #include <avr/io.h> .section .init1,'ax',@progbits ldi r16,_BV(SRE) | _BV(SRW) out _SFR_IO_ADDR(MCUCR),r16 ;; end xram. Back to FAQ Index.: _BV(3) => 1 << 3 => 0x08 However, using the macro often makes the program better readable. Example: clock timer 2 with full IO clock (CS2x = 0b001), toggle OC2 output on compare match (COM2x = 0b01), and clear timer on compare match (CTC2 = 1). Make OC2 (PD7) an output. TCCR2 = _BV(COM20)|_BV(CTC2)|_BV(CS20); DDRD = _BV(PD7); Back to FAQ Index.: o Obviously, none of the C++ related standard functions, classes, and template classes are available. o The operators new and delete are not implemented, attempting to use them will cause the linker to complain about undefined external references. (This could perhaps be fixed.) o Some of the supplied include files are not C++ safe, i. e. they need to be wrapped into extern 'C' { . . . } (This could certainly be fixed, too.) o. Back to FAQ Index.. Note: Recent versions of GCC are now smart enough to detect this situation, and revert variables that are explicitly initialized to 0 to the .bss section. Still, other compilers might not do that optimization, and as the C standard guarantees the initialization, it is safe to rely on it. Back to FAQ Index.. uint16_t read_timer1(void) { uint8_t sreg; uint16_t val; sreg = SREG; cli(); val = TCNT1; SREG = sreg; return val; } Back to FAQ Index. So you tried this: asm volatile('sbi 0x18,0x07;'); Which works. When you do the same thing but replace the address of the port by its macro name, like this: asm volatile('sbi PORTB,0x07;');: asm volatile('sbi %0, 0x07' : 'I' (_SFR_IO_ADDR(PORTB)):); Note: For C programs, rather use the standard C bit operators instead, so the above would be expressed as PORTB |= (1 << 7). The optimizer will take care to transform this into a single SBI instruction, assuming the operands allow for this. Back to FAQ Index. in avr-gdb?. Back to FAQ Index.. Note: You can also use -Wa,-gstabs since: myfunc: push r16 push r17 push r18 push YL push YH ... eor r16, r16 ; start loop ldi YL, lo8(sometable) ldi YH, hi8(sometable) rjmp 2f ; jump to loop test at end 1: ld r17, Y+ ; loop continues here ... breq 1f ; return from myfunc prematurely ... inc r16 2: cmp r16, r18 brlo 1b ; jump back to top of loop 1: pop YH pop YL pop r18 pop r17 pop r16 ret Back to FAQ Index. Consider this example code: #include <inttypes.h> #include <avr/io.h> void set_bits_func_wrong (volatile uint8_t port, uint8_t mask) { port |= mask; } void set_bits_func_correct (volatile uint8_t *port, uint8_t mask) { *port |= mask; } #define set_bits_macro(port,mask) ((port) |= (mask)) int main (void) { set_bits_func_wrong (PORTB, 0xaa); set_bits_func_correct (&PORTB, 0x55); set_bits_macro (PORTB, 0xf0); return (0); }. Note: Because of the nature of the IN and OUT assembly- dev/2003-01/msg000.html for a possible workaround. avr-gcc versions after 3.3 have been fixed in a way where this optimization will be disabled if the respective pointer variable is declared to be volatile, so the correct behaviour for 16-bit IO ports can be forced that way. Back to FAQ Index. o. o. o. o). o. Back to FAQ Index. There. Back to FAQ Index.. Back to FAQ Index.. Optimization flags Size of .text Time for test #1 Time for test #2 -O3 6898 903 s 19.7 ms -O2 6666 972 s 20.1 ms -Os 6618 955 s 20.1 ms -Os -mcall-prologues 6474 972 s 20.1 ms (The difference between 955 s and 972 s was just a single timer-tick, so take this with a grain of salt.) So generally, it seems -Os -mcall-prologues is the most universal 'best' optimization level. Only applications that need to get the last few percent of speed benefit from using -O3. Back to FAQ Index. First, the code should be put into a new named section. This is done with a section attribute: __attribute__ ((section ('.bootloader'))) In this example, .bootloader is the name of the new section. This attribute needs to be placed after the prototype of any function to force the function into the new section. void boot(void) __attribute__ ((section ('.bootloader'))); To relocate the section to a fixed address the linker flag --section- start is used. This option can be passed to the linker using the -Wl compiler option: -Wl,--section-start=.bootloader=0x1E000 The name after section-start is the name of the section to be relocated. The number after the section name is the beginning address of the named section. Back to FAQ Index. completely broken! Well, certain odd problems arise out of the situation that the AVR devices as shipped by Atmel often come with a default fuse bit configuration that doesn't match the user's expectations. Here is a list of things to care for: o All devices that have an internal RC oscillator ship with the fuse enabled that causes the device to run off this oscillator, instead of an external crystal. This often remains unnoticed until the first attempt is made to use something critical in timing, like UART communication. o). o Devices with a JTAG interface have the JTAGEN fuse programmed by default. This will make the respective port pins that are used for the JTAG interface unavailable for regular IO. Back to FAQ Index.: #include <inttypes.h> #include <avr/io.h> #include <avr/pgmspace.h> int uart_putchar(char c) { if (c == '0) '); uart_putchar('0)); return 0; } Note: By convention, the suffix _P to the function name is used as an indication that this function is going to accept a 'program-space string'. Note also the use of the PSTR() macro. Back to FAQ Index. into a 16-bit operation in assembly?: var &= ~mask; /* wrong way! */ The bitwise 'not' operator (~) will also promote the value in mask to an int. To keep it an 8-bit value, typecast before the 'not' operator: var &= (unsigned char)~mask; Back to FAQ Index.. Back to FAQ Index.: Back to FAQ Index.. Back to FAQ Index. TIFR |= _BV(TOV0); /* wrong! */ simply use TIFR = _BV(TOV0); Back to FAQ Index.. Back to FAQ Index. See Pseudo-ops and operators. Back to FAQ Index.. Back to FAQ Index.). Back to FAQ Index. avr-objcopy -I binary -O elf32-avr foo.bin foo.o: avr-objcopy --rename-section .data=.progmem.data,contents,alloc,load,readonly,data -I binary -O elf32-avr foo.bin foo.o: $(OBJDIR)/%.o : %.txt @echo Converting $< @cp $(<) $(*).tmp @echo -n 0 | tr 0 ' 00' >> $(*).tmp @$(OBJCOPY) -I binary -O elf32-avr --rename-section .data=.progmem.data,contents,alloc,load,readonly,data --redefine-sym _binary_$*_tmp_start=$* --redefine-sym _binary_$*_tmp_end=$*_end --redefine-sym _binary_$*_tmp_size=$*_size_sym $(*).tmp $(@) @echo 'extern const char' $(*)'[] PROGMEM;' > $(*).h @echo 'extern const char' $(*)_end'[] PROGMEM;' >> $(*).h @echo 'extern const char' $(*)_size_sym'[];' >> $(*).h @echo '#define $(*)_size ((int)$(*)_size_sym)' >> $(*).h @rm $(*).tmp $(OBJDIR)/%.o : %.bin @echo Converting $< @$(OBJCOPY) -I binary -O elf32-avr --rename-section .data=.progmem.data,contents,alloc,load,readonly,data --redefine-sym _binary_$*_bin_start=$* --redefine-sym _binary_$*_bin_end=$*_end --redefine-sym _binary_$*_bin_size=$*_size_sym $(<) $(@) @echo 'extern const char' $(*)'[] PROGMEM;' > $(*).h @echo 'extern const char' $(*)_end'[] PROGMEM;' >> $(*).h @echo 'extern const char' $(*)_size_sym'[];' >> $(*).h @echo '#define $(*)_size ((int)$(*)_size_sym)' >> $(*).h Back to FAQ Index. The canonical way to perform a software reset of the AVR is to use the watchdog timer. Enable the watchdog timer to the shortest timeout setting, then go into an infinite, do-nothing loop. The watchdog will then reset the processor. The reason why this is preferable over jumping to the reset vector, is that when the watchdog: #include <avr/wdt.h> #define soft_reset() do { wdt_enable(WDTO_15MS); for(;;) { } } while(0) For newer AVRs (such as the ATmega1281) also add this function to your code to then disable the watchdog after a reset (e.g., after a soft reset): #include <avr/wdt.h> // Function Pototype void wdt_init(void) __attribute__((naked)) __attribute__((section('.init3'))); // Function Implementation void wdt_init(void) { MCUSR = 0; wdt_disable(); return; } Back to FAQ Index. code not work?. Back to FAQ Index.. Library call Reentrant Issue Workaround/Alternative rand(), random() Uses global variables to keep state information. Use special reentrant versions: rand_r(), random_r(). strtod(), strtol(), strtoul() Uses the global variable errno to return success/failure. Ignore errno, or protect calls with cli()/sei() or ATOMIC_BLOCK() if the application can tolerate it. Or use sccanf() or sccanf_P() if possible. malloc(), realloc(), calloc(), free() Uses the stack pointer and global variables to allocate and free memory. Protect calls with cli()/sei() or ATOMIC_BLOCK() if the application can tolerate it. If using an OS, use the OS provided memory allocator since the OS is likely modifying the stack pointer anyway. fdevopen(), fclose() Uses calloc() and free(). Protect calls with cli()/sei() or ATOMIC_BLOCK() if the application can tolerate it. Or use fdev_setup_stream() or FDEV_SETUP_STREAM(). Note: fclose() will only call free() if the stream has been opened with fdevopen(). eeprom_*(), boot_*() Accesses I/O registers. Protect calls with cli()/sei(), ATOMIC_BLOCK(), or use OS locking. pgm_*_far() Accesses I/O register RAMPZ. Starting with GCC 4.3, RAMPZ is automatically saved for ISRs, so nothing further is needed if only using interrupts. Some OSes may automatically preserve RAMPZ during context switching. Check the OS documentation before assuming it does. Otherwise, protect calls with cli()/sei(), ATOMIC_BLOCK(), or use explicit OS locking. printf(), printf_P(), vprintf(), vprintf_P(), puts(), puts_P() Alters flags and character count in global FILE stdout. Use only in one thread. Or if returned character count is unimportant, do not use the *_P versions. Note: Formatting to a string output, e.g. sprintf(), sprintf_P(), snprintf(), snprintf_P(), vsprintf(), vsprintf_P(), vsnprintf(), vsnprintf_P(), is thread safe. The formatted string could then be followed by an fwrite() which simply calls the lower layer to send the string. fprintf(), fprintf_P(), vfprintf(), vfprintf_P(), fputs(), fputs_P() Alters flags and character count in the FILE argument. Problems can occur if a global FILE is used from multiple threads. Assign each thread its own FILE for output. Or if returned character count is unimportant, do not use the *_P versions. assert() Contains an embedded fprintf(). See above for fprintf(). See above for fprintf(). clearerr() Alters flags in the FILE argument. Assign each thread its own FILE for output. getchar(), gets() Alters flags, character count, and unget buffer in global FILE stdin. Use only in one thread. *** fgetc(), ungetc(), fgets(), scanf(), scanf_P(), fscanf(), fscanf_P(), vscanf(), vfscanf(), vfscanf_P(), fread() Alters flags, character count, and unget buffer in the FILE argument. Assign each thread its own FILE for input. *** Note: Scanning from a string, e.g. sscanf() and sscanf_P(), are thread safe. *** It's not clear one would ever want to do character input simultaneously from more than one thread anyway, but these entries are included for completeness. An effort will be made to keep this table up to date if any new issues are discovered or introduced. Back to FAQ Index.. AVRs use a paging mechanism for doing EEPROM writes. This is almost entirely transparent to the user with one exception: When a byte is written to the EEPROM, the entire EEPROM page is also transparently erased and (re)written, which will cause wear to bytes that the programmer did not explicitly write. If it is desired to extend EEPROM write lifetimes, in an attempt not to exceed the datasheet EEPROM write endurance specification for a given byte, then writes must be in multiples of the EEPROM page size, and not sequential bytes. The EEPROM write page size varies with the device. The EEPROM page size is found in the datasheet section on Memory Programming, generally before the Electrical Specifications near the end of the datasheet. The failure mechanism for an overwritten byte/page. Back to FAQ Index. Some AVR datasheets give the following formula for calculating baud rates: (F_CPU/(UART_BAUD_RATE*16L)-1): ((F_CPU + UART_BAUD_RATE * 8L) / (UART_BAUD_RATE * 16L) - 1) This is also the way it is implemented in <util/setbaud.h>: Helper macros for baud rate calculations. Back to FAQ Index.
http://huge-man-linux.net/man3/FAQ.html
CC-MAIN-2018-26
refinedweb
2,441
69.18
About this talk Is a SpecBDD tool the same as a TDD tool, or something quite different? This talk will answer these questions, and show how PhpSpec can be integrated into your development workflow to drive quality in your Object Oriented design. Transcript - Thanks for the invitation to speak here, it's nice to go to an event in the midlands. I'm Ciaran, I'm from Starbridge. Has anyone used PhpSpec? Good, because this is an introduction talk. So those two might be bored. Is anyone doing test driven development? - Ish. - Ish. It's TDD but write the test afterwards. My country. -combination. - Yeah. So I'm gonna talk about this tool I maintain called PhpSpec. Try and talk about what it's for, and we'll touch on some subjects to do with TDD and BDD. And a bit about the TDD cycle. I found when I'm showing people this tool, it's most effective when we're sort of pair programming, so I try to make this talk feel like interactive talk. So there's some code examples, we're gonna work through something as in a TDD cycle and see how the tool supports that. So first off if you read about PhpSpec, you'll see it's referred to as a BDD tool. Which is related to TDD and it's worth talking about the differences between them. So BDD, if you ask Dan North who came up with the term what BDD is, it's a second generation outside-in-pull based multiple stakeholder, I couldn't fit it on one slide, multiple-scale, high automation, agile methodology. Which is actually a very good definition of BDD, but it's maybe a bit complicated. All those things are true. Liz Keogh came up with a better definition of behaviour driven development, she said it's when you use examples in a conversation to illustrate behaviour. So that's quite a natural thing, when you're trying to talk about what the system should do, a really easy way to help people understand what the system should is to just give an example, in this case this is what should happen. And BDD, really if you reduce it a lot is about deliberately introducing examples into conversations and deliberately saying as I'm explaining how the system behaves, I'm gonna do that by giving examples of what it will do in different situations. Cool. This is, turns out, it's kind of the same thing as TDD. So it came from TDD, that's important to talk about. So people like Kent Beck came up with test driven development, and I think, was it Kent Beck or Robert Martin came up with the rules of TDD? And it's pretty simple, there's three steps in test driven development, you start by writing a test that fails. Anyone familiar with that? Anyone doing that? Some people. That's the hard bit, you start by writing a test that later will tell you wasn't the correct code. And then after you've written the code, in some automated way you find out if it passed the test. Dan North was in a kind of coaching role, training role, trying to get people up to speed on this TDD thing, TDD is very successful. It changed my life as a developer so you should give it some time. And Dan's trying to teach people this, you start by writing a test that fails and then you write code that passes the test and then once it's passing, once it's passing you then take time to think how you're going to make it better without breaking it. Which is what we call refactoring. If you say you're doing refactoring but you don't have tests you're not doing refactoring. Myron Fowler wrote a book called Refactoring where he defined what refactoring was in Chapter Two, he's like you have to have tests, everyone ignores that. You need to know you're not breaking as you're making these changes, you need to have this safety net, it works, and then I make a little change and it still works and anywhere you really get that confidence is due to having a testing tool telling you everything's still fine. So this works, it works really effectively. Makes you a better developer, blah, blah, blah. So when Dan was teaching this, there was a sort of stumbling block which is that you say to people you have to write to test first. And like I saw a few faces when I said that, it doesn't sound right, the word doesn't sound right. It doesn't sound like a natural thing to do, write a test first. Because in life, we go to school and we take a test. Or in a factory you build something and then you test it, so it feels like test is the thing that happens later. And Dan was really kind of aware of this stuff, he's into neurolinguistic programing, things like that, so he changed the words, and this was the start of behaviour driven development. So BDD, they're doing the same cycle, you're doing the same things but you're calling them different things. And so maybe you're thinking about them differently. So the biggest shift in BDD is that you don't think of it as writing a test first, you think about it as specifying it first. So the idea of a BDD spec and a TDD test are really aligned concepts. In behaviour driven development, before you write the code, you describe using examples what the behaviour of that piece of code will be, and we'll see an example. And that feels more naturally, before I start, I'm gonna think about what it should do and I'm going to describe it. That description is gonna be some code that I type in to a testing framework, but I'm thinking of it as a description of the way the system's going to behave. And then I implement that behaviour and then I make it better so that's BDD. So effectively the thing you're doing is the same as TDD, but you're thinking about it a bit differently, you're thinking more about, instead of thinking about test, which is maybe less natural to think about afterwards, I'm thinking about it as a specification which is natural to think about as something you do first. It's natural to think of the specification as my starting point. Even if it's a quick specification for the next bit I'm doing, because we don't do waterfall projects anymore, right? Right? - Right, yeah. - Yeah. - Yeah. - So you're not specifying the entire thing and then trying to write the code, you're saying well what's the next thing I need to do? I should maybe think what's the next behaviour and write capture that somehow in a way that's going to act as a test later. So to think about the landscape of testing tools in php, why bother having PhpSpec? Because there's a testing tool that everyone uses anyway. But we can kind of plot them on different axes, so, the Y axis here is, what level are you applying your tests? Are you applying your tests one object at a time? Down at the bottom here, or are you exercising your entire system as part of the test? Because we can write a test that just instantiates the class and does stuff with it, or you can write a test that kind of deploys your system to a bunch of containers and hooks them all up together and then does web requests and provides a test database, that's the entire system. And the other axis is, are they more about testing? Or more sort of BDDish tools about describing? Based off, the way the tools API are expressed, are they about tests? Or are they trying to be descriptive and be about specs? And this isn't the official logo for PHPUnit, there is no official logo,told me of, there's no official logo for PHPUnit yet. But someone did this logo and it's really popular, so everyone thinks it's the real logo. So I'm too lazy to change my slide. I started using PHPUnit around 2005, completely changed the way I approach code. Not overnight, took me a few years to learn how to do it, but, you can use PHPUnit for testing your classes, you can also use it for exercising your whole system by driving something like Selenium, you can use it for all the in between levels of testing. So if you want to learn a testing tool that you can use at all these different layers, learn PHPUnit. And to be honest, if you're a PHP developer and you're gonna work on projects, you should probably learn PHPUnit. Because 90% of projects, at least, that do testing are using PHPUnit. Because it has to address all these different types of testing, PHPUnit's got loads of utilities for doing stuff like loading database fixtures before the test, or that's part of DBUnit but it's kind of integrated with PHPUnit. Stuff like partial knocking because as an author, or as maintainers, you don't really know what kind of testing you're gonna use it for. When it was written, it was written, wow, 15 years ago? Which is amazing for a piece of software to still be in use, and still be really good, and have new versions with new features. It's about testing, so I would say most people use PHPUnit using it to test stuff after they write the code. Which isn't a bad thing, sometimes that's what you have to do. So on this side of the axis, there's some other tools, I use behat a lot. Behat's mostly aimed, behat's not mostly aimed at exercising your entire system, although that's what most people use it for. Say it this middle ground of exercising your systems application layer and driving those tests from business use cases, this isn't a behat talk though. And behat's very much a BDD tool, it's all about having a conversation with someone about how the system should work ahead of time, and then exercising some parts of the system to check it, can fulfil those use cases that the user needs the system to be able to do. And PhpSpec's down this end, PhpSpec is just for testing classes. Individually, in isolation. And that gives us some focus. While PHPUnit doesn't know what kind of test you're gonna write and so it has to have a more generic API, we can focus a bit and say this is just an API for testing classes and we can not build in features for loading a database fixtures because it's just for testing classes in isolation quickly and then throwing them away. And because we're from this sort of BDD tradition, we're trying to make it so you can read this specification, and as a human who understands PHP, you can read the specification and kind of understand what is it this class is supposed to do. So we designed the API to try to make it readable and less about validation, it's more about this is what the object should do, less about I'm gonna test this, this is the case. That might all be a bit abstract so we'll get more specific. So PhpSpec was started by Travis Swicegood and Padraic Brady in 2007, and it was inspired very heavily by a tool called Rspec, a lot of BDD practitioners started off in Ruby. The early cool BDD tools got developed in the Ruby community around the same kind of time that Rails was getting trendy and Ruby was the future if you remember. And this book's really good, all code examples are in Ruby but it's a really good sort of BDD testing book. If you want to check it out. So Padraic and Travis started Rspec, it never got to a 1.0 release, it was very much sort of patterned after, sorry they started PhpSpec, it's very much patterned after Rspec and some of the stuff felt a bit Rubyish. I'm not going to say it was a port of Rspec but it was very close to how Rspec behaves. Now my friend and colleague Marcello became lead maintainer. Because if you know Travis and Padraic, they're involved in loads of open source projects, made arguably too many, and they didn't have time to carry this thing on so Marcello got involved, released PhpSpec 1.0 and this is when I sort of started to become aware of the project. Then at some point, Marcello and Konstantin, Konstantin who wrote Behat, they decided to write version 2 as a complete ground up rewrite and they addressed some of the problems with version 1. So there wasn't any backward compatibility between 1 and 2, it was a new project effectively. Marcello and Konstantin got it as far as beta versions for version 2 and then it stayed in that state for about a year, at which point I was using it, people in Enveeker where I work, we were using it on projects successfully, tagging it against devmaster. I started to get pissed off that there wasn't a release. So that's how I got into open source. Just driven by there not being a release recently, I started contributing. Closing off bugs, helping make some new features, and we sort of got it over the PhpSpec 2.0 release. And because I was doing so much work, I ended up taking over the project. So what was the point of PhpSpec? It was optimise the tests to work as descriptions of the behaviour. So optimise the tests for readability, optimise the API to be concise and make it clear what you're testing. To encourage good design, and this is probably the toughest thing, we omit any features that help you test what we think is a bad design. So it's hard to test, if you make it hard to test bad code with your tool, it means if people are doing tests first, they can't write bad code. However this means it's not the ideal thing to apply to your legacy classes. If you're on a legacy project and you're writing new code you can use PhpSpec, but like bolting it on retrospectively to your old classes, that kind of thing, it's not gonna work. We want to encourage the TDD cycle, so we want to make it easier for you to write the test first than it is for you to write the test afterwards. So this means you have a bunch of convenience stuff that means if you write the test first, it's gonna be easier it's just to kind of brainwashing you into doing TDD. So that's the shiny stuff we'll show that looks handy, then sometime later you realise you're always writing the test first, we've got you. So the way we enforce that is by using it constantly for everything, and then finding the bits in my workflow and other people's workflows that feel like they're a bit clunky, and thinking how could a tool help you with that? How can a tool make that workflow smoother? And to address some of the issues with PhpSpec 1, we wanted it more in a php paradigm, less Rubyish, make it something that looks like PHP, conforms of a PHP developer's right code. Well, good PHP developers. So since I took over the project for version 2, I actually took over after version 2. It's, the early work on version 2 is just Marcello and Konstantin, working in private, they dumped it into repository, since then it's really been a community effort, I'm maintaining it, but loads of people contribute and if you start using it, please contribute as well, because I'm not that, I'm quite lazy, so it's amazing to just be able to merge people's pool requests after a bit of review instead of having to build all the features myself. So let's get into it, you instal it with Composer, we're on version 3 now. All we did really with version 2 was drop some depth coded things and bump the php version requirements. And this should be all the configuration you need to get started if you're using PSR-0. PhpSpec will read the Composer autoloader and use that to figure out where all your classes are gonna be so you shouldn't need any extra config, you can just start. Psr 4 is a bit more complicated. We're trying to figure out how to auto detect Psr 4 root locations. Someone's working on that right now. So we start with some top level component, we need to say hello to people when they come to our website, because the marketing team think that will improve conversions, if you get a nice greeting. And the thing we need to do is, we're gonna have to make some objects to achieve this. So we're gonna describe what the object should do. So it's like the TDD cycle, we're gonna start with the description. And we describe it using a specification, a specification is a php class that contains examples, methods called examples, in each example is meant to say in this case, this is what the object will do. In this scenario this is what the object will do. So obviously that maps to a test case and test methods. We're trying to say so for example in this situation this is how our object will behave. And we can start by using the command PhpSpec describe and then the name of the class. So we need to call the class something. So I just name the class, I can use namespaces, whatever. And in this project I've just got the Composer JSON I showed you, it's installing PhpSpec, and nothing else yet. I've got spec in a source folder with nothing in. So when I say describe greeter, PhpSpec generates a new specification for me. So if I look in the spec folder, come on I didn't ask for that, if I look in the spec folder, there's a greeter spec that describes what the class we're gonna write, how it should behave. So any behaviour we have by default is it's initializable and it should have a type. That's a good starting behaviour for a class, right? It exists. Okay. So the next step is I need to check if the specification matches reality, so for that I use the command PhpSpec run. What do you think will happen? You'll fail, right? Because the thing doesn't exist, yeah. Said it fails in a specific way, I'll read out what it says. One example, one broken, so it's not actually a failure, broken means something went wrong while trying to execute this. I tried to run the thing you described but some php thing broke, and what broke is the class doesn't exist. So we've tried to optimise this workflow, because how many ways are there of fixing class not existing? There's one. So any time when there's only one way of doing it, probably some computer should do it for you. So it says do you want me to create phpWorksGreeter for you? I can say yes. The class greeter has been created at this path, and then it runs the test again and this time it's green, because the only behaviour is the class exists and is instantiatable. And in the source folder, there's a greeter, which, is just a class. Ignore the final thing, that's my personal template. You can template it. So that's pretty simple, so I describe what the behaviour is, the tool checks if it's true, tests pass, green now, so my next thing is to describe how that class should behave. No one's gonna crash, that's good. Did that. So now we're gonna have to come up with some real behaviour. So you give an example, an example is in a particular situation this is what should happen. And you can talk to your pairing partner if you have one of those. What's the first thing it should do? This is a point with TDD, we're gonna break down solving a complex problem into small steps. So what's the next small step we're gonna take? When it greets someone it should return "Hello". In TDD would say oh we have to write what failing test should we write next? Which is harder to think about. In this BDD cycle, it's more sort of what's the next thing it needs to be able to do? When it greets it should return "Hello". So open my specification. Got that one example about it being initializable. So I have to describe that when I greet someone, it should say "Hello". It says hello. This in a spec refers to the object we're describing. So on a technical level, forget about that a second, on a technical level what happens is the spec proxies the calls through to the real object and then checks what comes back. When you're writing it as a description we're using the fact that there's a keyword called this in PhP and saying this object we're talking about, let's describe it's behaviour. So this greet shouldReturn 'Hello'. See how close that was to the sentence? We're trying to make this API quite expressive and easy to understand. Don't worry about my funny font that does the arrows. So what's gonna happen when I run it? - Fail. - Why would it fail? - There's no greeter. - There's no greet, right. Says it's broken, so the one example passed, one example was broken. Because the function didn't exist. Do you want me to create a method called greet for you? Yes. So now it's red, red means fail, so it didn't break. But the error is I expected hello and I got null instead. And it's because the class, yeah the tool can generate the method for you but some logic is more complicated. There's actually a way, there's a flag I can pass called fake just for this case, or you can turn it on in your own personal preferences. Where in these cases it will prompt and say do you want me to make the greet method always return hello? I'm gonna say yep. And then all the tests pass. So that's, not everyone likes that, it only does it when the method's empty, so you can turn that on if you like that cycle, and the point is, by writing the test first it's been easier for me to write this class, I haven't had to do anything yet. This is just, it's really good for new people to get them into the TDD cycle. You might feel it's gimmicky, but when you're using it all the time, I haven't made a class, I haven't typed a class whatever for ages. That's not the point of the tool, it's just a way to get people into this TDD cycle, the point of the tool is this expressive syntax we're using to describe behaviour. And trying to optimise the workflow. Yep, done that. So how do we describe values? You saw should return, I called a method and I said it should return, and matchers, if you've used PHPUnit they're a bit like insertions. So the way you use them is you call a method and then you say something about what the result of this method should be. So this should return hello, the sum of 3 plus 3 should equal 6. GetEmail should return some sort of email object. GetSlug should match this regx, getNames should return an array that contains this value. It's a bunch of built in assertions. The opposite works in each case, so you say should not return, should not equal, should not have time, that kind of thing. And extensions can add extra assertions pretty easily, extra matches. There's a couple of special ones, so if you say should be something, it looks for a method called is something on the object and checks it returns true. Matches because that's a pattern that loads with php developers seem to use is a common naming thing, so, should be seems to work, and I don't say should have, if you say should have something, it'll look for has something method and check it returns the right value. They're optional of course. And you can also do find your own matchers, so, in this case I'm getting some JSON and I'm saying it should have a JSON key called username. I can pretty easily define a callback that does that assertion for me. Can do that inline in the example, so inline in the spec. I can also write matcher objects and have it in my projects and just sort of reference them in a config file and they get picked up. So there's something you're checking a lot, it's quite easy to add a new matcher. So that's the testing objects bit, testing objects on their own bit, but the most important thing about objects really is that they talk to other objects and in case that's the, he regretted calling it object oriented programming, because people think it's about the objects. It's actually about the messages between the objects and the way the objects talk to each other, that's the important bit. So we have, we want to be able to describe how one object speaks to another. Says come up with another example, when I greet someone called Bob, it should say Hello Bob. Makes sense, right? So we started with a simple case, that's important. Started with a simple case where it's just saying hello, and now I'm trying to come up with a more complicated case. You shouldn't start with the most complex case, because then, your test that triggers the most complex case you're gonna have to write code that solves the entire problem and that might take a long time. You start by solving the simple cases. You'll find when you have to solve the complex version, it's all done for you, half of it's done for you already. So when it greets Bob it should return Bob. And the interaction between our object and the person is we're gonna ask the person what their name is. So our greeter's gonna say hey, what's your name? This is called a query. There's roughly two ways objects can interact, they can either tell another object to do something, Persist this to the database. Approve this invoice. Commands when I don't really expect anything back. Or queries where they go hey give me this data. So I start with queries. My greeter's gonna ask the user what it's name is so that it can say hello. And so we use what's called a stub, a stub will use the method willReturn. So I somehow have to describe how it's gonna interact with a person. What should I call it? The example? Yeah. It_says_hello_by_name, something like that. So this greet, in this case, it's gonna say hello Ciaran. But that doesn't look right, why would it say Ciaran instead of someone else? We have to pass in the person that you're gonna say hello to so I'm gonna have, like when you greet this person, you're gonna say hello. So now I need to think, well okay, there's gonna be a person object. The way we ask PhpSpec to produce one is just by typing into. Put a nice namespace on it. So when I greet a person, it's gonna say Hello Ciaran. So why Ciaran instead of something else? I have to tell the testing tool this is someone called Ciaran. So I have to set this stub up, person, getName, I hate getters, but, you know. WillReturn Ciaran. So trying readable because a person when you ask the person for their name they're gonna say their name is Ciaran. It's just kind of the preamble to the spec. And the spec is when I greet this guy it's gonna say hello Ciaran. Make sense? Kind of readable. So what's gonna happen when I run it any bits? Break why? There's no person, right? Yeah, this is good, we're kind of gonna figure out what person looks like by talking about how someone else is going to use it. So yeah, broken, purple. Do you want me to make an interface called person? And I'm gonna say no. So why is it asking about interface instead of a class? So because of this thing, we noticed if you immediately create a class, you kind of lose the opportunity to create an interface. And the uncle Bob's interface segregation principle is no client should be forced to depend on methods it doesn't use, so I start thinking about a person, does this object, does this greeter really need to depend on person? I feel like my person in my system is gonna do other stuff as well, it's gonna have more to it than just a name. So if I depend directly on person then person might end up with more API. And actually my class doesn't depend on all these full methods, my class just wants to know about a name. So it makes more sense for me to have an interface called something like named, you can have your own naming convention, name interface. If you have to. I'd rather depend on an interface, that question makes me sort of think I'd rather depend on an interface. So I'm gonna choose it's named. Oh, come on, come on. I don't actually know how to use PhpSpec at all. So it's saying do you want me to make a named interface? And this time I'm going to say yes. You're calling getName and the named interface doesn't have that method in it, do you want to add that to that interface, yeah. And now it fails, so if we look at what it's created, I've now got this interface for named that I've defined by thinking about how the greeter's gonna greet people, I've kind of generated an interface and later I'm gonna have to make some new implement syntax. And it's failing now with the red because I expected hello Ciaran but I got hello. Because I said when you greet someone whose getName returns Ciaran you get Hello Ciaran. But actually it clearly doesn't do that. So now I'll write some code. So I've got to accept a named thing. And then just run the test. It's good to get used to running the tests all the time. Oh, doesn't like it, oh because sometimes we call it without a parameter. So I kind of have to make that optional. I can do this thing now, can't I? Oh my God. Nope, oh no you can't. That doesn't let you not specify, it lets you pass a null. So if you want to make it optional, you still have to pass. So it's still failing because it doesn't say Hello Ciaran so now I have to do, I have to make it pass. So if you're failing tests, you want to make the test pass as quickly as you can. With the minimum kind of mental effort. Doesn't mean the smallest like code golf style amazing solution, means just like whatever you think of, do it that way. So I'm gonna do return, if, if named return hello dot named, can't type, can't type in front of people. So that passes. So this is the point where you refactor and make your solution better, so it's good to get it passing. It's easy to make it better when it works. Like if your car's broken, you can't start tuning it, you have to fix it and then start tuning it, so, there's probably something I can do better here. Well what I could do, okay, what I could do is have a thing called name, and in this case, it's empty. And then I do this thing. So now what? Oh, expected hello but I got hello with a space on the end. So now I trim that. That' works, still doesn't look good. Any suggestions? Oh I could turn that into a turnery couldn't I? It is name, that or that, so I can get rid of all of this and all of this. No, I did it wrong, what did I do wrong? Named, see how the test is kind of supporting me. That moment of panic I just had, I could see how to fix it, what other option we meant to hit undo, because it was passing like 10 seconds before, and then I thought I think I can make this change and then it fails. I could have just hit undo and gone okay it's working again. I'll try that refactor again. That's why having passing tests is so important, because you always know it literally just worked, so that thing I tried didn't work, but I can go back. I get about 2 minutes and then I kind of time out and get check out dash dash. Okay so it's passing, can that get any better? Oh what? Do what with a what? Sprint F? I can inline this, can't I? I don't think php has done that correctly. So I hit Undo, it's all good, I've hit Undo and the test tells me I'm safe again so my heart rate goes down. So you can see what it did, oh yeah it's because it needs some brackets, right? Yeah, that's good enough, so now I'll go to the next test. So I'll raise above the jet brains about that. That all makes sense, right? Oh I know how I can do it without the trim. No, we can spend too long on that. So we've described how if you give it something with a name it will say hello to that name, otherwise it will just say hello. So now we can go through the whole cycle again quicker, and we're gonna now make a person, I'll do it faster. So what's the first thing I do to make a person? PhpSpec, I have to describe it, I'm gonna describe a person, I'm gonna get a specification, I shouldn't have described a person, I should have described PhpWarks here, person, so to meet that thing. I'm gonna run it, says there's no such thing as a person so I'm just gonna let the tool fix that. What is there about a person? It_is_a_named, so it should have the type named. It fails. Someone's actually working on getting PhpSpec to fix that for you but it doesn't yet because it turns out to be really complicated. So what do I need to do to pass that test? Implements named. So what's the next behaviour? You go through this cycle, so, I'll make that bigger, sorry. It_knows_its_name. It's name is gonna be Bob. Notice when I was stubbing it in the other test, I said willReturn to sort of say when you're asked this is the data you're going to return, will is describing how we're setting up our doubles, our stubs or our knocks, should is always checking something. So getName should return Bob, why is it gonna be Bob? This be, how is that class gonna know it's called Bob? I'm gonna say be constructed with Bob. So when the class is constructed with Bob and then I call getName it's gonna return Bob. I haven't written this class yet, we start here in the description, so you start by thinking about the naming of the class, thinking about what the methods are called, thinking about what parameters those methods take. Do you want to give it a constructor? Because I'm trying to use constructor, yes. Now I've added a constructor, it needs to be constructed in both places. Cool, now it's failing because it expected Bob but got null. That's because this is the class. So now I have to write the code that implements this complicated behaviour. So gonna get name. Return this name. Seems alright. All this rubbish. That passes, so now we've got a class that, the behaviour we've just described was it knows its name. It can be renamed, so let's say we've got someone called Bob and then we call renameTo, getName, shouldReturn 'Alice'. Do you want me to add renameTo, yes. It got Bob, it didn't work. So that's a pretty, this is pretty simple behaviour to implement, we just need to set the name. Passes again. Hope that's given you an idea of the workflow. I'm spending my time at start thinking about what's the next behaviour, what's the API, what's the method called, what are the parameters, what's the behaviour? To an extent, the tool generates some of that boiler plate stuff for me and then I think okay, how do I achieve that? So that's one type of collaboration, the type of collaboration where one object asks another object for something. It's called a query, you always have commands, sometimes we care that an object calls a method on another object. I care that the email gets sent, I care that the invoice is approved, but the outcome of the example is that some method gets called on another object. used a thing called mocks. It's when it greets Bob, hello Bob should be logged. How am I going to describe that? I'm not going to describe that in terms of some return value the outcome of the example is the logger gets called with a method, the log gets written to. So we'll show you how that works. We use things for mocks or spies. They're very similar to stubs, instead of willReturn and stuff like that we're using methods like shouldBeCalled. The outcome of the test is this method is called, or should have been called. So example for the greeter is it logs the greetings. Let's go do that with a logger. And when I greet, then what should happen is logger, log, I guess, shouldHaveBeenCalled. So we do a different collaborator object. I'm saying when this object greets, the logger's log method should have been called. So how did this object know about the logger? I can run this already and I'll get prompted, there's no such thing as a logger yet, do you want to make it? Logger interface doesn't have a log method yet, but you're talking about it here, do you want to create it? Yes. And then it fails because it never got called. How might my,how can the greeter know about the logger? Inject it in the constructor, sure. BeConstructedWith the logger. So now I'll say hang on, the greeter didn't have a constructor, do you want me to make a constructor? Yes. That fails because in all the other examples, we didn't give it a logger. The greeter now has this constructor. We touch, oh. It has this logger thing which isn't being provided in the other examples. So what I can do, outside of all the examples in this spec I can use the function let. Let this beConstructedWith a logger. And now I don't need to have that in each example, it's kind of used in each example. And kind of magically this instance of logger is the same as this instance of logger. Kind of magically. So now I have one failing test, we didn't log the message. And that's because there's this logger and we're not doing anything and somewhere in here we need to log it, so I can construct a variable message. I can initialise that field as a logger. And then here I guess I do this, logger log message. And you see that everything passes. If I comment that out. It contains now I want to log the message. So in between failing tests I'm writing quite small bits of code. This example doesn't have a lot of main logic, so I'm not having to do a lot of thinking in each step when it's a really complex problem you're having to do a little bit of thinking in each step. Because you're breaking down a problem across multiple steps you're doing small amounts of thinking. So what have we built? Now we ended up with these types, there's a greeter that depends on an interface called named and we've made an implementation of the named interface. We also defined a Logger interface. We're probably not going to make a concrete thing, it's probably going to be an adapter to some logging library that we're gonna decide later, monologue probably. We can also run PhpSpec and it would output all of the examples for each class. So because we'll see maybe from that, these things become a way of understanding the code, you can hopefully read this and understand pretty much what the person does. It's constructed with Bob and has a particular type. It's constructed with Bob, it should say it's name's Bob, if it's constructed with Bob and you rename it to Alice it should say it's name's Alice. That's pretty simple, we can kind of understand what the object does by reading the spec. So PhpSpec focuses on being descriptive, tries to make the really common boring annoying stuff easy and automated, it tries to get you to do this pattern where you're designing first through the specs and then you're writing code. Current, I think the last release was 3.2. What is new matchers for warnings, because some people simply decided to start omitting those deprecation warnings and people want to test that. Previously ignored warnings is the thing people want to test because everyone uses exceptions now. But we added some stuff for testing warnings, and some matchers for testing iterations, iterators. Should iterate as this, this, this stuff. Under course of development, we're gonna reach version 4 in June, we do a kind of annual release cycle where each summer we drop deprecated things and bump some of the memo versions so version 4 is only gonna support php 7. Version 3 is gonna live until 2018 and then probably die. But die just means we're not fixing it, we're not gonna delete the tag or anything. And some things we want to build. When I said that the person should implement named, I want PhpSpec to say do you want me to make it into an interface for you? But that refactoring when you drill into it has loads of edge cases so that's kind of under development. We want to make it easier to use PSR 4, the moment you kind of have to replicate your different namespaces and folders into the PhpSpec xaml we want to read that from Composer. And somebody's working on that. And I've got a branch where we handle fatal errors. Even in php 7 there are fatal errors that you can't catch. We've got a strategy for dealing with that that involves processes. And we want to roll that out because it will make things on php 5 easier, php 5 users will be able to catch errors. So I want to get that into version 3, so it's available for version 3 that will still support php 5. This is me, I work for Enveeka, I should say that because I adapted enough to come here. So if you want to know about Enveeka we do software development and consultancy and training, and I do a lot of training, so if you want training come and talk to me. I maintain PhpSpec and i really want more people to be involved in helping the project and do pool requests. I also co-organize BDD London meetup which is every two months in London, which is 20 pounds return on the train and only takes an hour each way. And we're doing a twice monthly meetup where we talk about BDD with people from other programming languages and stuff. The videos are available online, and I guess if you've got any questions I can answer them. Does anyone have any questions, yes? Yeah you can, so here you're describing construction. We don't actually instantiate the class until you do something like this, that prompts you to instantiate it, so you could, for instance here, it doesn't make any difference in this test but you can override how it's gonna be constructed, and then it's actually constructed when this method's called what you can't do is then here try and change how it's constructed, you'll get an error message. So we support thing like named static constructors. Yes, you can do like, it's hard to explain. Since, let's do an example, instead of beConstructedWith Bob, I can do beConstructedNamed Bob. beConstructedNamed Bob. And when I run it, it'll say do you want me to make a static method called named? Yes, boom. And it will, you'll be able to construct the person by calling this. And if I haven't already got a constructor, it will say do you want to make a private constructor as well? If you don't have an existing constructor. But not everyone uses named constructor so I didn't mention it. But yeah you can override how the object's constructed as long as it's before something that would need the object to exist. Anything else? That was quite a deep dive, any more easy questions? - [Audience Member] Are there many notable projects that have been used? - At Enveeka we use it on loads of projects. Silius uses it which is an ecommerce platform. At one point, Laravel decided to start bundling it. I don't think that was Taylor's idea. But they added it as a dev dependency and then I think it later got removed. But it's hard to tell from packages because there's loads of Laravel projects depending it and then completely not using it. So it's really hard to tell from the stats. Silius is probably the biggest open source project I can think of. Because they use PhpSpec and Behat. - [Audience Member] Do you have, like a like an example that maybe you've done recently? Like just see how we bail out of, how crazy they can get? - No open source, PhpSpec tests itself with PhpSpec. And Behat. I think Silias is a good reasonable example of some big ecommerce framework that's trying to use this stuff. Most of the time it's used for the core domain model, because it's classes and not infrastructure, but frameworks tend to not have a domain model, unless it's something like an ecommerce framework that you're gonna sort of instal, libraries tend not to have it. We've used it for creating stuff like magenta extensions. Where we needed a nice clean, not everyone makes extensions as a nice clean domain model, but, we wanted a core domain model that's completely tested and then a layer of stuff that adapts it into a magenta extension. I think some of those are open source under Enveeka organisation. Yes. Normally this is too low level to talk to businesses about. So you do try and capture the words and phrases they're using in the business to describe these things, but, start asking, like if you're making a car for someone, asking them what size the nuts and bolts should be is like there's a mismatch there, so normally when I'm working on software, we've had conversations with business experts and tried to write scenarios we can use Behat to test, and then with those failing scenarios, then you're using PhpSpec, so, iterate through until the scenario passes. But I think it's really aimed, it's not readable by nontechnical people, it's meant to be really readable to people who understand php. Yeah, yeah. Yeah, when I've done event storming and then taking it towards a test, I then turn that into Behat test. And then,event storms, the past events map well on to given, commands map well on to when, and the events it produces map well on to then. So you can write that out as and use it in Behat or you can use PHPUnit or something to test the command is the right thing. Any others? Yes. Yeah, so, autonomous vehicle sounds cool. So if you think about your application, you've got different layers, you've got your core domain model which is how it really works inside. And then you tend to have, maybe you don't have it but you should. I'm gonna do an octagon just to confuse people. Like an application layer, this is the services that your application exposes that things like controllers would use. It's good to have that separation if you don't. And then you have stuff like user interfaces and databases, like frameworks other people write or infrastructure other people write that you have to plug into. So like from your symphony app, your calling methods in the application layer. So in terms of where these tools are aimed, the PhpSpec really kind of aimed at this core domain model. When the objects inside the domain represent the concepts of the domain and how they interact, and they're just pure php objects. I'll draw that bigger because you might have lots of domain and a little bit of application. And then things like Behat they tend to address this application layer, because Behat scenarios are written from a user perspective so they're representing things a person has to be able to do with the system. Whether it's through the UI or by ringing you up or whatever these are the actions a user has to be able to accomplish through this system, so you want to have an API here that corresponds to the things people do. Like if people constantly approve invoices you want a method called improve invoice. So driving this layer that exposes a service that knows how to prove invoices with use cases from people from Behat means that gonna be nicely aligned, but in the middle you might need to have a concept of an invoice and a concept of what approval means and that's what you're driving with PhpSpec. These domain concepts. A lot of people don't separate the domain and the applications, that's okay. Just makes it harder to rejig your application because you already control using as objects. And this Api can be services you're exposing, it can be having a list of commands that it can accept, something like that. Any others? When does this time out? If you have more questions I can do this all night. Ask me in the pub? Thanks everyone, hope you enjoyed it.
https://www.pusher.com/sessions/meetup/php-warwickshire/driving-design-with-phpspec
CC-MAIN-2019-39
refinedweb
8,956
79.9
Java, J2EE & SOA Certification Training - 33k Enrolled Learners - Weekend - Live Class. In this thread.yield() in Java, we will cover the following topics:. Syntax: public static native void yield(); public class JavaYieldExp extends Thread { public void run() { for (int i=0; i&amp;lt;3 ; i++) System.out.println(Thread.currentThread().getName() + " in control"); } public static void main(String[]args) { JavaYieldExp t1 = new JavaYieldExp(); JavaYieldExp t2 = new JavaYieldExp(); // this will call run() method t1.start(); t2.start(); for (int i=0; i&amp;lt;3; i++) { // Control passes to child thread t1.yield(); System.out.println(Thread.currentThread().getName() + " in control"); } } } Output: The next example shows the usage of java.lang.Thread.yield() method: import java.lang.*; public class ThreadDemo implements Runnable { Thread t; ThreadDemo(String str) { t = new Thread(this, str); // this will call run() function t.start(); } public void run() { for (int i = 0; i &amp;amp;amp;lt;"); } } Output: With this, we have come to the end of our article. I hope you understood how the thread.yield() in Java works and how it is used the programming language. “Thread.yield() in Java” blog and we will get back to you as soon as possible.
https://www.edureka.co/blog/thread-yield-in-java/
CC-MAIN-2019-43
refinedweb
198
67.25
Results 1 to 2 of 2 Thread: Need to wait for data to load - Join Date - Sep 2006 - 1 - Thanks - 0 - Thanked 0 Times in 0 Posts Need to wait for data to load I have an island which says: <xml id="myXML" ondatasetcomplete="relatedRelationshipsComplete()" src</xml> Now, I want to do the processing in the same function where I set the src. When I say xmlRelatedRelationships.src = "URL"; the next line I say var tmp = myXML.selectSingleNode("//MYNODE"); At this line I get the Javascript error "The data necessary to complete this operation is not available". I know I have to wait for the data to get loaded. Can something be put in between: myXML.src = "URL"; and var tmp = myXML.selectSingleNode("//MYNODE"); so that the code waits until the data is loaded and then carries on? I am putting an alert which solves the purpose but I do not want users to click on an alert and then view the data on the page . - Join Date - Apr 2005 - 1,051 - Thanks - 0 - Thanked 0 Times in 0 Posts you need to have a callback function to handle the data after it loads. in that function run your code.public string ConjunctionJunction(string words, string phrases, string clauses) { return (String)(words + phrases + clauses); } <--- Was I Helpfull? Let me know ---<
http://www.codingforums.com/javascript-programming/95542-need-wait-data-load.html
CC-MAIN-2017-43
refinedweb
220
72.26
hello , i am starting to program my project in c++ i need help in direction. my project is like wikpedia . i should enter about 3 value in each catagory (3*7) . the search will be by pressing some value and then a list will open with all the value that it found. choice will happen by pressing a number (1-5) and there will be another botton (6) that will send to another page with more choices. the user can typing a value and the pc will ask if it is the value he want if Y he will show the value if N he will open the search window again. pressing Y will enter the user to a window that show : 1. free search: a. the exect value. b. at least 1 word. 2.serch by category . 3. random search the pc will found randomly value and then he will ask if the user want this value.Y will enterr N will cancel and go to the search again. creat an account: by fill in private details , USER NAME , passwor (6 numbers), question for restore the password 3 incorect pass typing will bring to an exit there be an restore password option. the value name will be bold and with color and the other txt will not. i wrote the begening code i have some problam : 1) when im pressing 'C' he show me an error , he say that question and answer allready in use. 2) for exemple: when im pressing Y or N in the 'Q' option he do nothing. and show the press any key to continue. 3)how do i program an option to do an accountt? how the password will show like ******** 4) how do i program that if i press little letter q instade of Q he will recognize it like Q ? this is the code: /* search_engine */ #include <iostream> #include <string> using namespace std; void log_in (string name , string password); void creat (string name , string password , float question , float answer ); int main(int argc, char* argv[]) { char choice ; string name, password; int quit; float question, answer; cout <<"\n\t\t-----------------------------------------"; cout << "\n\t\t Hello Guest! Welcome to search engine!\n"; cout<<"\t\t-----------------------------------------\n"; cout << "What would you like to do: \n\n"; cout << "[L]og In \n" << "[C]reat an account \n" ; cout << "[G]uest \n" << "[Q]uit \n\n"; cout <<"Press a letter (L , C , G , Q): "; cin >> choice; switch (choice) { case 'L': log_in (name , password) ; break; case 'C': creat (name ,password , question, answer); break ; case 'G': cout <<"\n\t\t\t\t-----\n"; cout <<"\t\t\t\tGuest\n"; cout<<"\t\t\t\t-----\n"; break; case 'Q': cout << "Are you sure you want to exit the program? Y/N \n"; cin >> quit; if (quit == 'Y' ) exit (0) ; else choice ; break; } return 0; } void log_in (string name, string password) { cout <<"\n\t\t\t Log in for an existing account. \n\n"; cout << "User Name: "; getline (cin,name); cout <<'\n'; cout <<"Password: "; cin >> password; cout <<"\n\n"; cout <<"Welcome Back " << name; cout <<"\n\n"; cout << "Press [H]istory to view your search history"; } void creat (string name , string pass , float question , float answer ) { cout <<"\n\t\t\t Creat an account. \n"; cout <<"\t\t Please fill in the following questions \n"; cout <<"User Name:"; getline (cin,name); cout <<'\n'; cout <<"Password (6 numbers max):\n"; cin >> pass; cout <<'\n'; cout <<"Re-type your password: "; cin >> pass; cout <<'\n'; cout <<"Question to restore your password: "; cin >> question; cout <<'\n'; cout <<"Answer: "; cin >> answer ; cout <<'\n'; } any help will welcome!!
https://www.daniweb.com/programming/software-development/threads/251736/hello-help-in-project
CC-MAIN-2016-50
refinedweb
599
75.44
Documentation ¶ Overview ¶ Package astutil contains common utilities for working with the Go AST. Index ¶ - func AddImport(fset *token.FileSet, f *ast.File, ipath string) (added bool) - func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added bool) - func DeleteImport(fset *token.FileSet, f *ast.File, path string) (deleted bool) - func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (deleted bool) - func Imports(fset *token.FileSet, f *ast.File) [][]*ast.ImportSpec - func NodeDescription(n ast.Node) string - func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Node, exact bool) - func RewriteImport(fset *token.FileSet, f *ast.File, oldPath, newPath string) (rewrote bool) - func Unparen(e ast.Expr) ast.Expr - func UsesImport(f *ast.File, path string) (used bool) Constants ¶ This section is empty. Variables ¶ This section is empty. Functions ¶ func AddImport ¶ AddImport adds the import path to the file f, if absent. func AddNamedImport ¶ AddNamedImport adds the import path to the file f, if absent. If name is not empty, it is used to rename the import. For example, calling AddNamedImport(fset, f, "pathpkg", "path") adds import pathpkg "path" func DeleteImport ¶ DeleteImport deletes the import path from the file f, if present. func DeleteNamedImport ¶ DeleteNamedImport deletes the import with the given name and path from the file f, if present. func Imports ¶ Imports returns the file imports grouped by paragraph. func NodeDescription ¶ RewriteImport rewrites any import of path oldPath to path newPath. func Unparen ¶ Unparen returns e with any enclosing parentheses stripped. Types ¶ This section is empty.
https://pkg.go.dev/github.com/alecthomas/gometalinter@v3.0.0+incompatible/_linters/src/golang.org/x/tools/go/ast/astutil
CC-MAIN-2021-31
refinedweb
252
55.5
Hey all, I'm busy with an assignment for which a question, due to being too complicated, has been cancelled (i.e. no longer required to be done). The lecturers told us that if we still included this question in our assignment answers, they would give us the marks for it if we attempted it (even if the final program doesn't work). The question is: Suppose we want to display the following pattern on the screen: &******&******&******&******&******&******&******& *&******&******&******&******&******&******&****** **&******&******&******&******&******&******&***** ***&******&******&******&******&******&******&**** **&******&******&******&******&******&******&***** *&******&******&******&******&******&******&****** &******&******&******&******&******&******&******& "The size of the pattern is determined by counting the number of groups of '*' characters in the first line, or the number of rows in the pattern. Note that the pattern in the first line starts with an '&' character and ends with an '&' character, with each group of size - 1 '*' characters seperated by an '&' character as well. The size of the above pattern is 7. Note that the input value for the size of the pattern must be an odd number. A pattern of size 5 will look as follows:" &****&****&****&****&****& *&****&****&****&****&**** **&****&****&****&****&*** *&****&****&****&****&**** &****&****&****&****&****& Question 4a: one value parameter "We give the main function below. Write a function drawPattern that will display such a pattern on the screen. The function must have one parameter of type int, representing the size of the pattern. Use the main function and input 7 as the size. Make sure the pattern displays correctly. Hint: Use a nested for loop. The outer loop runs from 1 to size/2+1. This will handle the pattern from the start row to the middle row (including the middle row). The inner for loop runs from size 1 to size * size + 1, completing the row. Then another nested for loop handles the rest of the pattern. i.e. the outer loop runs from size/2 to 1, decrementing the loop counter. This is done to make the pattern turn to the left. The inner loop works the same as for the first nested for loop. Test the program with different sizes." This is the fragment of the program we have been provided with: #include <iostream> using namespace std; //The required function [B]drawPattern[/B] should be inserted here. (that which I have inserted is in bold) [B]void drawPattern (int ptrnSize) { for (int i = 1; i <= ptrnSize/2 +1; i++) { for (int j = 1; j <= ptrnSize * ptrnSize +1; j++) }[/B] int main( ) { int size = 0; do { cout << endl << "Please enter the size of the pattern. " << endl; cout << "(You must enter an odd number) : " << endl; cin >> size; }while (size % 2 !=1); drawPattern (size); return 0; } could anyone please assist me as it would only benefit me to gain these marks. any help would be much appreciated, Brandon. Edited by BrandonB: Fixed closing tag
https://www.daniweb.com/programming/software-development/threads/268045/stuck
CC-MAIN-2017-39
refinedweb
447
80.51
. Include both You can't do this directly. One solution is to use a third header file called defs.h which has forward declarations for the classes. However that presupposes that you are using pointers to classes. It *can* also be an indication that your design is bad. In any case, I would look at the design again and ask myself, why I would need to do this. Get this small utility to do basic syntax highlighting in vBulletin forums (like Codeguru) easily. Supports C++ and VB out of the box, but can be configured for other languages. Put a forward declaration in each file, eg In a.h class b; // forward declaration //note do NOT #include "b.h" class a { ... b m_b; }; ------------------------------ In b.h #include "a.h" class b { ... a m_a; }; ------------------------------- In the classes, stick to using pointers, otherwise you may find you run into problems, depending on what you're trying to do with the other class. You may need to do the forward declaration the other way around, depending on which file your compiler looks at first. This may be a sign of bad design, but is frequently inevitable. For example you have to do this to implement the 'visitor pattern' - a famous OO design solution. Last edited by JonnoA; February 6th, 2004 at 02:11 PM. Take a look at the following FAQ... Ciao, Andreas "Software is like sex, it's better when it's free." - Linus Torvalds Article(s): Allocators (STL) Function Objects (STL) Forum Rules
http://forums.codeguru.com/showthread.php?282034-cross-referencing-includes&p=891163
CC-MAIN-2015-27
refinedweb
252
77.23
>>. Finally (Score:2, Insightful) It's about time PHP has native support for unicode.: (Score:2, Insightful): (Score:3, Interesting) Re: (Score:3, Funny) But you can use Boost [boost.com] with any language, I don't see your point. Re: (Score:3, Informative) Re:Finally (Score:4, Informative) PHP is much, much closer to C than C++ with truckloads of STL piled on top. Ask a C programmer to comprehend that mess and you'll likely have a suicide on your hands. It is very un-C-like. The point is that the PHP syntax for arrays is very nearly identical in behavior and syntax to C, just with lots of extra functionality (variable length associative array). I never said that C++ couldn't do those things, but as far as I've seen, when you do it in C++, you're generally way off the deep end as far as being syntactically familiar to C programmers. I guess what it comes down to is this: if you think templates are elegant, then we will never agree about what makes a good language design. From my perspective, templates are what happens when somebody forgets that we have a perfectly good C preprocessor and decides to reinvent the wheel with a clumsy syntax that doesn't provide anything more than what C preprocessing could already provide, wedging the concept into the language itself for no apparent reason. It is anathema. It is absolutely the antithesis of good language design. As for OO in PHP, I don't see why you think dynamic typing decreases the value of object-oriented programming. If you really are mostly using the same code with different underlying types, then there's little point in doing OO, but in my experience, that's the exception rather than the rule. Most of the situations where I've used OO with polymorphism, I've had polymorphism, but the underlying implementation has differed substantially, and the only thing similar was the method name (and the general concept for what the function does). Also, it is nice to use classes even when you don't need polymorphism. This reduces pollution of the global function namespace. It also makes it easy to create complex data structures that make life easier. (PHP doesn't have the notion of a struct, so you have to either use a class or an associative array.) Finally PHP is still very much a typed language. It's not like there is no notion of types and everything is polymorphic with everything. The type of a variable is determined when the variable is assigned, and some types can be coerced into other types in certain use cases, but it isn't universal. I can't do if ($arrayA < $scalarB), for example. PHP even has the notion of casting to force type conversion just like you do in C. For example: function myfunc($mynumber) { ... $mynumber = (int)$mynumber; } Dynamic typing doesn't mean the types aren't there. If you call a method on an object that doesn't exist on that object, it is still an error. And so on. Dynamic typing just makes it a little easier to shoot yourself in the foot by not throwing up an error when you make the assignment or function call in the first place. :-) Re: (Score:3, Informative) There's nothing preventing a native foreach notation built into the language instead of glued on. They just didn't do it that way, and they should have. Sure. It's pretty easy. You just define two macros (e.g. BASE_TYPE and ARRAY_TYPE) and then #include a header. #define BASE_TYPE uint64_t * #define ARRAY_TYPE uint64_t_pointer #include <CustomArray.h> And in CustomArray.h>: #define MAX_SIZE 32 class ARRAY_TYPE { Re: (Score:3, Informative) No, there's nothing preventing you from including that header file multiple times for different types. That's the beauty of token gluing. It concatenates the base type as part of the name of the derived array type, so you can create arbitrary numbers of them for arbitrary types. And unlike the template class, whenever you use the resulting type, it just looks like an ordinary C++ class instance with no need for template parameters. Thus, when you actually use the class, you just use "Array_int *foo" or Re: (Score:2) Funny, very very dry, but damn funny. Re: : (Score:2, Informative) Interesting thought. Does anyone use PHP for anything other than its ubiquity? Re:Finally (Score:5, Insightful) Ubiquity is a pretty compelling feature. I mean, BeOS is pretty bitchin', but I'm not spending any of my time on developing applications for it. Re: (Score:2, Funny) Re: (Score:2) $output = fopen('outputfile.txt', 'wt'); // writes out data in UTF-8 encoding fwrite($fp, $uni); ..... not where you expect it it dossent.... Re:Finally (Score:5, Funny) Too bad Slashdot still wonâ(TM)t. I mean, won't. Re:Finally (Score:5, Funny) That's so cliché. So... (Score:5, Informative) without wanting to be overly sarcastic.. What features are they gonne break this time? Re:So... (Score:5, Insightful). Re: (Score:2) Re: (Score:2) mod +1; I also hate the Needle/Haystack Haystack/Needle operator ordering.. of course upgrading your code to make it compliant will be a PITA... Re:So... (Score:5, Informative) At my work we host and have build and maintain a little over 200 php websites. We host them all ourselves. ( the CMS that we use is build in PHP ) We earn money from both the hosting and the developing. Many of our customers don't want to pay for the porting of their websites to PHP5, let alone PHP6. usually this requires upgrading the CMS as well, making modifications to custom extentions written by outsourcing partys, etc. All in all quite expensive for the site owner. "Threatening" them with PHP4 server shutdowns only makes them go away to other hosting providers that will over PHP4 to them. So we ended up virtualising all the PHP4 sites together with a good backup system and making our customers understand that we provide no warrenty anymore. We will help them when things blow up on an paid per hour basis. Another problem is that we cannot reuse a lot of our code anymore now. Many of our new plugins require php5 so we have to modify them to make them php4 compatible again. when php6 comes out we will have to support three different php versions... the horrors of that vision already scare me today.. t Re: (Score:2) Is there a business in supplying coal for instance? Some people still heat their houses with it, but does that mean YOU as a business man have to run a business to supply them? No, but it does mean if YOU choose not to supply them with coal, somebody else will. The parent isn't complaining because he doesn't want to stay up to date. He's complaining that they have a lot of customers who don't want to stay up to date, and there's nothing he can do about that except stop taking their money. Ask yourself, how much time does it cost you to keep the people happy who want PHP4 and how much that same time could have earned you in business from PHP5 customers. Unfortunately, turning away PHP4 customers doesn't mean more PHP5 customers will suddenly sign up. They are currently supporting both, and while of course there is a cost associated with continue Re: . Re: (Score:2) If you want something that maintains compatibility, go with java. Depending on your point of view, that could be a negative or a positive. Re: (Score:2) If you want something that maintains compatibility, go with java. Depending on your point of view, that could be a negative or a positive. This was the first PHP related story on Slashdot that didn't have a few dozen replies that mention Java until you went ahead and ruined it. I'd choose Java over PHP any day though. Re: (Score:3, Informative) At least I ruined it by being informative. :P Java applets coded back in 1996 still run [slashdot.org] in the newest JRE. Pretty impressive for the consumer/user, though it must be a nightmare to maintain. I'm not aware of any huge changes to Apache Tomcat in the past few years - certainly nothing that required re-coding an entire website from scratch. Re: (Score:3, Funny) Re: (Score:3, Informative) I wish i was trolling, but trust me, i work for a company that hosts sites, and there is still plenty of php4 around. Most people don't mind the upgrading and staying up to date part so much. But they usually don't like the price that comes attached with it. Re: (Score:2) Still recalling a horror of writing in Perl in 90s, I would say PHP is good, more or less. Re: (Score:2) It won't happen to the base functions simply for backwards-compatibility, but given that namespace support is being added into PHP6 (I think it's also in 5.3; I have 5.2.6 on my machine so I don't know for sure) they could re-map all of those old functions in the global namespace into new logically-named and consistent functions. Array and string manipulation functions come to mind as the worst offenders, but there's plenty of other bad stuff as well. I think a lot of it would do well to be remade into bui Re: (Score:3, Informative) You must be confused, are you thinking of Perl? PHP has been VERY careful about breaking features, and have essentially openly mocked the people who suggest they "fix" PHP's functions by randomly swapping argument order on functions that have been working just fine for years. The only thing I can think of they've broken is MAGIC_QUOTES and registered globals. Both are Very Bad Things that it was important they do away with. Any sane PHP code will react to their removal by simply removing a few chunks of goo Re: (Score:2) But if Python does it, its okay? No. From whose ass did you pull that strawman from?. Re: (Score:3, Funny) Re: (Score:3, Informative) Time to pay the piper... (Score:4, Insightful) Re:Time to pay the piper... (Score:5, Funny) This is why I never write legacy code, only progressive forward thinking code! People who write legacy code are just not thinking of the future. Re: (Score:2) You will love it when they add functional approach and constructs. Declarative style in php for more points! Re:Time to pay the piper... (Score:4, Insightful) You're not far off track. A lot of PHP's problems stems from the fact that the language itself was more or less kind of thrown together rather than planned out (from the early simple Personal Home Page scripting stuff to PHP3 that just kept extending things and adding more functionality bolted on). They only just began to start to stabalize some of that in PHP4 and really only started to fix a lot of issues in PHP5 and now PHP6. They are making good strides but there's a lot of work to do (and a lot of backwards compatible considerations, I'm sure). The good news for PHP developers with legacy code is that they've had a long time to fix things. Stuff that is going away has been deprecated for many versions now so none of this should be a surprise. The people that will get hit are the site administrators using PHP based apps that haven't been updated in forever. Re:Time to pay the piper... (Score:5, Funny) I think PHP developers with legacy code are going to be paying the price for several versions to come. I prefer to call it "job security". question: (Score:5, Insightful) Re:question: (Score:4, Informative) Yes :( Re:question: (Score:5, Funny) Re: (Score:3, Interesting) Re:question: (Score:5, Funny) Can you blame them for trying to escape?. A likely story (Score:5, Insightful) Given that PHP 6 was "rumored" to be out at least a year ago. I can't decide if the title "An Early Look" is meant to be ironic, or is just a sad indicator of progress. Despite that, I would say that three things have recently happened demonstrating the improvement in quality of PHP: I would say that (1) and (2) easily are more important for the language than is (3). PHP 5.3's improvements should be a huge change: Namespaces (I know there's a huge amount of hate for this implementation: get over it. It's going to be very useful), Closures / Lambda Functions, and Late Static Bindings in particular make it hard to wait so long for PHP 5.3. So, stop talking about PHP 6! Lets get PHP 5.3 out. Hope it handles Search/Replace better (Score:2) I hope it handles search/replace better. I tried doing a search/replace on a 88MB large string and the stupid script crashed! ;-) Seriously, though, if anyone knows of any good tactics for large-string searching/replacing, I'd be happy to hear them. My current attempt is multiple page loads in an iFrame while the user is presented with a "working on it..." message. Re:Hope it handles Search/Replace better (Score:4, Informative) Re:Hope it handles Search/Replace better (Score:4, Insightful) Loading 88MB file into memory is not going to work by default anyhow, unless you set the memory limit in PHP from the default you will get out of memory errors every time. I think even a find/replace in a Windows app like Notepad or Notepad++ will "work" but it will definitely be slow. When I used to search large logs I would use some sort of file splitter and search each file itself. And here the rest of us are grepping and sedding multi-gigabyte files without thinking twice. Seriously, what's your idea of a large file? Re: (Score:3, Informative) If you want to process large files (or any large chunks of data such as blob columns) in PHP without loading the entire file into memory, look into streams. Re: (Score:2) Seth Re: (Score:2) Assuming this 88MB string is in a file, you should never load the whole file. Open the file and read it chunk by chunk. As you read it chunk by chunk, do a search/replace on each chunk and write the replaced chunk to another file. You need to remember to catch the matches that span more than once chunk though. The question should really be why you are dealing with an 88MB file in PHP... Re: (Score:2) Well, I once had to use PHP to re-import a MSSQL DB that was something like 25GB because no SQL machine was able to import even one of the 133 (?) files that made up the DB contents. Had to leave it running for something like 17 hours, but I think it ended up getting the job done well enough for what needed to be done. But yeah, I tend to avoid dealing with any large files in PHP whenever possible. Limited cleanup (Score:5, Insightful) clean-up of several functions Does that include safe_quote_string_this_time_i_really_freaking_mean_it, or do_foo(needle, haystack) and foo_do(haystack, needle)? At least it gets namespaces after all this time, even if they're almost deliberately ugly. Re: (Score:3, Insightful) All I want is for $foo[0] and $foo["0"] to not be the same reference. Re:Limited cleanup (Score:5, Funny) But that might break something that two people found convenient in 1997 and therefore can never be repudiated. One of these things is not like the OOthers (Score:5, Insightful) One of these things just doesn't belong python: myArray.append(myvalue) ruby: myArray.push(myvalue) objective-c: [myArray addObject: myvalue] smalltalk: myArray add: myvalue PHP: array_push($myarray, $myvalue) Re:One of these things is not like the OOthers (Score:5, Informative) Or... PHP: $myarray[] = $myvalue; Re: (Score:2) Re: (Score:2) Python: myArray.append(myvalue) Well, you could do something like: and squint until it looks like list_append, but that's kinda silly. And that $myarray[]=$myvalue; syntax? That should be taken out and shot. Indeed it does not (Score:2, Insightful) Market share: PHP 50%, ASP 49%, rest perl. When PHP and ASP don't totally dominate the job listings, please come back to me again. In the meantime I know which of the function calls pays for my food. Oh and $array[] = $value; Coding, you should learn it.: (Score:2) Fun fact: arrays are not objects in PHP*. Not surprisingly, this means that they don't have properties or methods. *Another poster already pointed out that PHP does have array objects, and having looked, array objects DO have an append method. Re: (Score:2) They should have used # instead of the backslash for namespaces, that way, what I type will coincide with what I wish I was doing to the asshat that came up with that namespace delimiter. Re: (Score:2) Octothorpe? Re: (Score:2) In no language has quote escaping been the correct approach to putting untrusted data into a SQL statement for quite a long time (even if a language provides only this approach, it's still not the right approach). That stuff is kept for legacy support. Switch to PDO and start using bound parameters. No matter what happens with the database and heretofore unconsidered character sets, this will never suddenly become vulnerable to a SQL injection when you upgrade your database server. My items to be fixed (Score:3, Insightful) Re: (Score:3, Informative) PHP compiles regex's transparently automatically. If you've used a pattern recently, it will not reparse the statement. Re: (Score:2, Informative) Improve array speed (for simple arrays, use internally one simple C array/list - current days, any array is a map); Try the SplFixedArray class [php.net]. The SPL data structures are much, much faster. [blueparabola.com] I actually rather like the "easy by default, fast when you need it" dichotomy. Re: (Score:3, Funny) You also forgot: <p> Re: (Score:2) Change your default post settings to "Plain old text" and it will. Re: (Score:2) No problem. Incidentally, HTML still works in "Plain old text" posting mode... so you have to use the HTML entities <, >, &, etc. Re: (Score:3, Insightful) # Insert optional configurations by project (and not by host); -1 You can already do this via .htaccess sans security resourse limits which should be per host on shared hosting. Re: (Score:2) Look into ini_set(). There are a couple odd things you can't override through that, but 95% of the standard configuration can be changed that way. The only thing that doesn't that immediately comes to mind is one of the magic_quotes settings, presumably because the superglobals have already been established by the time you've hit the override function - and magic quotes is finally going away in php6 so that'll be a non-issue moving forward. Re: (Score:2): (Score:3, Funny) Re: (Score:2) Use {$Foo} instead. It's the proper way to put variables in a string. Re: (Score:3, Insightful) It will print Hello 3 Because the namespace begins with a backslash ('\foo\n') and when using it inside double quoted strings must be "\\foo\\n". Re: (Score:2) Say that $Foo=3 It will print Hello 3 Because the namespace begins with a backslash ('\foo\n') and when using it inside double quoted strings must be "\\foo\\n". The example in the article didn't mention leading with a backslash, or at least I don't think it did (it's been slashdotted, apparently). And seriously? You have to escape the backslashes? What if you want a literal backslash now? Re: (Score:2) Hey, I can't imagine that would be asked a lot or anything. There's no way that would be in the PHP FAQ [php.net]! Oh wait... Re: (Score:2) It'll print $Foo followed by a newline. Foo\$n would print $n in the Foo namespace. I think. Strictly speaking, you should wrap it in curly braces if you're using anything other than a "non-complex" (for lack of a better term) variable, including array contents and object members. If variable $Foo was a string that contained the name of some namespace ("bar", for example), then if it wasn't in a quoted string context it would look for constant bar\n, but constants aren't echoed when quoted. That said, I still Re: (Score:3, Funny) Gesundheit. Well wouldn't you know (Score:5, Insightful) In the finest tradition of PHP, they made Unicode behaviour dependent on a setting. Have these people learnt nothing from the past? magic_quotes anyone? Bleh. All languages have their warts, but the amount of bad design decisions in this one is just staggering. FTFY (Score:2) All languages have their warts, but the total lack of design decisions in this one is just staggering. Re:Well wouldn't you know (Score:5, Insightful) Stack Overflow has a question from last year titled Worst PHP practice found in your experience?. Earlier today, I submitted the answer whose summary is "The worst practice in PHP is having the language's behavior change based on a settings file." Great minds think alike! New to this version (Score:3, Informative) Its like fast food.. (Score:5, Funny) PHP: its like fast food.. You know its bad for you... You feel like crap after eating it... But damnit, its right there, oh so conveniently located on the way to work, and sometimes a greasy cheeseburger just hits the spot, even though you know you'll pay for it later in heartburn and much later in high cholesterol and love handles, even though right now its really cheap on the wallet. Its a guilty pleasure. And while you're sucking down that greaseball burger, you see the local soup and salad restaraunt and think "next time, I'll eat right.." But come the next day and you see that taco joint and.. Broken Link in Summary (Score:5, Informative) Re: (Score:3, Informative) Re: (Score:3, Insightful) PHP5 has a fairly proper inheritance and member visibility model and is truly reference based (i.e. $objX = $objY means, in PHP5, that they are reference to the same object instance... opposed to PHP4 where $objX = $objY made a FULL copy of the object to $objX). So they've got to the level of Java 1.0. Congratulations! Oh, actually, sorry, they didn't, since there are still no namespaces. But there will be soon, and then it'll be at the level of Java 1.0. Once again, congratulations! Re: (Score:3, Informative) How good is the object oriented support in PHP these days? Everyone involved with PHP pretty openly admits that PHP5's OO model is a direct ripoff of Java, so inheritance, abstracts, interfaces, and access modifiers work pretty much the same way as they do in Java. If you like Java's OO, you should be fine with PHP5's. Re: (Score:2) Re: (Score:3, Funny) I hate to say it, but this wouldn't be the first time on /. when an article was submitted with a link that was a year or more older and the article made it to the main page. Particularly since the article the GP linked to is a year old to the day. I can only imagine the submitter/approver looked at the date, say May 6th, and went "OMG, that's today!!!111" Re: (Score:2)
http://developers.slashdot.org/story/09/05/06/180235/an-early-look-at-whats-coming-in-php-v6
CC-MAIN-2015-06
refinedweb
3,983
71.85
modifying an input file based on pattern matching Subhash Sriram Greenhorn Joined: Nov 10, 2003 Posts: 12 posted Nov 25, 2003 22:31:00 0 Hi, I could REALLY use some help here..I have a program that is suppose to take in an input file, along with command line arguments, could be there, doesnt have to. The main function of the program is to check the input file for "tabs", and change all tabs to 3 spaces by default, or if the user specifies another amount, between 1 & 9, it is suppose to change it to that. Also, an optional [-d] option will take off all ^M's from the file (the result of windows --> unix ftp)... I am using REGEX to check for a pattern , but I am lost as what to do when it finds a pattern, am also getting a couple of errors..Any help would be greatly appreciated. Here is my code so far: //Homework.java //Subhash Sriram import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.io.BufferedReader; import java.io.FileReader; import java.util.regex.*; public class Homework { public static void main(String[] args) { boolean remove = false; int spaces = DEFAULT_SPACES; inFile = null; if (args.length < 1 || args.length > 2) showUsage(); try { for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { char option = args[i].charAt(1); if (option == 'd') { remove = true; spaces = Integer.parseInt(args[i].substring(2)); } else { spaces = Integer.parseInt(args[i].substring(1)); } } else { if (inFile == null) inFile = new File(args[i]); else showUsage(); } } if (remove) spaces = -spaces; processTest(); } catch (NumberFormatException exception) { System.out.println("Key must be an integer: " + exception); } } public static void showUsage() { System.out.println("Usage: java Homework [-d#] Filename"); System.exit(1); } public static void processTest() { REGEX = "\\s{4}";); while (matcher.find()) { System.out.println("blah"); } } } public static final int DEFAULT_SPACES = 3; public static String REGEX; public static String INPUT; public static BufferedReader reader; public static Pattern pattern; public static Matcher matcher; public static boolean found; public static File inFile; } Thanks in advance. Subhash Angel Dobbs-Sciortino Ranch Hand Joined: Sep 10, 2003 Posts: 101 posted Nov 26, 2003 07:54:00 0 What kind of errors are you getting? Post what the screen shows. Angel Subhash Sriram Greenhorn Joined: Nov 10, 2003 Posts: 12 posted Nov 26, 2003 12:48:00 0 Hi, Thank you for the reply..I modified the processTest function to the following. I found an article on how to do replacements using REGEX, but not when the INPUT is a file, that is what is really confusing me.. Below is the modified function: public static void processTest() { REGEX = "\\t";); StringBuffer test = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(test, "\\s\\s\\s"); found = matcher.find(); } matcher.appendTail(test); } } And, this is the error that I am getting when running the file. C:\cis3020\temp> java Homework -5 tester.java Exception in thread "main" java.lang.StringIndexOutOfBoundsException : String ind ex out of range: -1 at java.lang.String.substring(Unknown Source) at java.lang.String.subSequence(Unknown Source) at java.util.regex.Matcher.getSubSequence(Unknown Source) at java.util.regex.Matcher.appendReplacement(Unknown Source) at Homework.processTest(Homework.java:90) at Homework.main(Homework.java:52) Also, I am not sure how to write the modified line back to the file. We are suppose to have a renameTo function which saves the inFile as a temp file, and then when the changes are made, it renames it back to the same as the input file...Would that have to be done first? Thanks again Subhash Sriram Greenhorn Joined: Nov 10, 2003 Posts: 12 posted Nov 26, 2003 13:33:00 0 Well, I have noticed a few problems with it right off the bat...I guess I am going back to the drawing board... If anyone can give me some advice on how to tackle this problem, I would really appreciate it. Leslie Chaim Ranch Hand Joined: May 22, 2002 Posts: 336 posted Nov 26, 2003 14:35:00 0 Unless this is part of your homework, your approach is very complex A couple of points: In appendReplacement the argument for replacement is not a regex. Compile your REGEX only once. (not in a loop) Consider using the replaceAll method of the String class. Follow the coding conventions that you were taught. I think that all you need is the repalceAll: inputLine.replaceALL ("\\t", " "); Normal is in the eye of the beholder Stan James (instanceof Sidekick) Ranch Hand Joined: Jan 29, 2003 Posts: 8791 posted Nov 26, 2003 17:41:00 0 You might also check your requirement. Is it really replace tab with "n" spaces or like a code editor insert enough spaces to get the next character up to 1 + a multiple of "n" columns from the left? In my favorite text editor tabs are set to 3. If I hit tab in column 2 it does not insert 3 spaces. It inserts 2 spaces to get me to column 4. For that I'd probably abandon a regex solution and read char by char. BTW: I did once in Pascal and there were some surprising gotchas. Maybe cause I was 20 years younger. Make yourself some good test cases! A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi Subhash Sriram Greenhorn Joined: Nov 10, 2003 Posts: 12 posted Nov 26, 2003 18:50:00 0 Hi, Thank you all for the replies... I think I have a fairly ok idea of what to do, except for one thing. I am reading in a file one character (byte) at a time, and I need to compare each byte to the tab character to see if there is a tab, and then replace with either the default number of spaces or the user specified number of spaces, but I have no idea how to compare the two! BTW, if it helps, the assignment is shown here: Thanks again. [ November 26, 2003: Message edited by: Subhash Sriram ] I agree. Here's the link: subject: modifying an input file based on pattern matching Similar Threads Regex problem Problem inputting and outputting strings correctly (weird error) Topic: Regex problem for pattern and grouping Hot to deal with OutOfMemoryError Ecryption program question All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/372339/java/java/modifying-input-file-based-pattern
CC-MAIN-2015-40
refinedweb
1,109
66.23
Opened 6 years ago Closed 5 years ago #12517 closed (fixed) Mistake in example for django.db.models.get_prep_lookup() Description In the example, the return value for an exact lookup is wrapped in a list: def get_prep_lookup(self, lookup_type, value): # We only handle 'exact' and 'in'. All others are errors. if lookup_type == 'exact': return [self.get_prep_value(value)] This then gets passed to the DB connection's compiler in get_db_prep_lookup, and seeing a list, does a typecast to ARRAY (in the case of Postgres). I think the example should in fact return just the value, not wrapped in a list (also as per the default implementation of get_prep_lookup in the source): def get_prep_lookup(self, lookup_type, value): # We only handle 'exact' and 'in'. All others are errors. if lookup_type == 'exact': return self.get_prep_value(value) By making this change to a custom field I have, the undesired typecast behaviour described above is avoided. Attachments (1) Change History (3) Changed 6 years ago by timo comment:1 Changed 6 years ago by timo - (In [13213]) Fixed #12517 -- Corrected get_prep_lookup example in custom field docs. Thanks to django@… for the report.
https://code.djangoproject.com/ticket/12517
CC-MAIN-2015-32
refinedweb
186
63.8
Since this is probably the most-often reused piece of code I’ve written recently, I thought it may be worth sharing. It is pretty raw still, so I will post it to the wiki as well, and hopefully people will see ways to improve it (and show us!). Here is the link to the wiki page: Generic List Provider in C#. I wrote this because I found myself constantly writing code to fill lists of objects from database commands. I was too far into the project and the project was a little to small to justify moving to an ORM like NHibernate, but I thought there must be a better way to do this. It turns out we can do it, using a couple of my favorite features in .NET 2.0, Reflection and Generics. By making this ListProvider a generic class, we can return a list of objects of any type. And by using reflection we can interrogate the type we are working with at runtime, and assign its’ properties. There is one pretty major limitation of this method, and that is that your property names need to match the column names that you return from the database. When limiting access to the database to stored procs, this is pretty easy to enforce, so I have not needed to find a way around it. I’m sure there is a way to do this by adding a list of database field names and their associated properties that the calling code can provide, but I have not needed to do it yet. Hopefully someone will add to the wiki page and do it for me 😀 Anyways here is the code, it is pretty self explanatory: using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Data; namespace MyApp.Utilities { public class ListProvider<T> where T: new() { public List<T> FindAll(IDbCommand com, IDbConnection con) { //ensure that command object's connection is set, open connection com.Connection = con; con.Open(); //create data reader used in filling objects IDataReader rdr = com.ExecuteReader(); //instantiate new list of <T> that will be returned List<T> returnList = new List<T>(); //need a Type and PropertyInfo object to set properties via reflection Type tType = new T().GetType(); PropertyInfo pInfo; //x will hold the instance of <T> until it is added to the list T x; //use reader to populate list of objects while (rdr.Read()) { x = new T(); //set property values //for this to work, command's column names must match property names in object <T> for (int i = 0; i<rdr.FieldCount; i++) { pInfo = tType.GetProperty(rdr.GetName(i)); pInfo.SetValue(x, rdr[i], null); } //once instance of <T> is populated, add to list returnList.Add(x); } //clean up -- assumes you don't need command anymore con.Close(); com.Dispose(); rdr.Dispose(); return returnList; } } } I tried to remove most of the comments that didn’t add much (parameter descriptions and what not) but I think its’ still pretty easy to understand. As I said this is a work in progress (I just need to run into a reason to actually need the progress 😉 ) so don’t be too rough on me. And feel free to do my job for me offer suggestions to make this better! Took you example and modified it to use attributes instead of the property names. this way your property names don’t have to look like your datacolumn names from the database. Great work. Would anyone have some hints on how to do what Jim suggested, using attributes instead of property names? Also, can anyone suggest a rough strategy for plugging in Update functionality so edits can be pushed back into the database?
http://blogs.lessthandot.com/index.php/desktopdev/mstech/generic-list-provider-in-c/
CC-MAIN-2017-22
refinedweb
618
62.17
To delete any particular word from the string/sentence in Java Programming, first, you have to ask to the user to enter the string/sentence, second ask to enter the any word present in the string/sentence to delete that word from the string. After asking the two, now check for the presence of that word and perform the deletion of that word from the sentence as shown in the following program. Following Java Program ask to the user to enter a string/sentence then ask to enter a word to be delete from the string, then display the new string/sentence after deleting the given word: /* Java Program Example - Delete Word from Sentence */ import java.util.Scanner; public class JavaProgram { public static void main(String args[]) { String strOrig, word; Scanner scan = new Scanner(System.in); System.out.print("Enter a String : "); strOrig = scan.nextLine(); System.out.print("Enter a Word to be Delete from the String : "); word = scan.nextLine(); System.out.print("Deleting all '" + word + "' from '" + strOrig + "'...\n"); strOrig = strOrig.replaceAll(word, ""); System.out.print("Specified word deleted Successfully from the String..!!"); System.out.print("\nNow the String is :\n"); System.out.print(strOrig); } } When the above Java Program is compile and executed, it will produce the following output: You may also like to learn and practice the same program in other popular programming languages: Tools Calculator Quick Links
https://codescracker.com/java/program/java-program-delete-words-from-sentence.htm
CC-MAIN-2019-13
refinedweb
230
53.21
Michael Meijer Download the Code Sample So you have a voluminous and potentially infinite stream of events such as a clickstream, sensor data, credit-card transaction data or Internet traffic. It’s infeasible to store all events or analyze them in multiple passes. Why not resort to a window of recent events to simplify analysis? Suppose you want to count the number of interesting events in a large window covering the latest N events of the stream. A naïve approach to counting requires all N events to be in memory and a full iteration over them. As the window slides upon the arrival of a new event, its oldest event expires and the new event is inserted. Counting over the new window from scratch wastes the processing time spent on N-2 events shared. Yuck! This article explains a data structure to reduce memory space usage and processing time to a small fraction of what would be required with that method, while supporting an event rate exceeding many thousands of events per second on commodity hardware. This article also shows how to embed the data structure in a user-defined stream operator in C# for the Microsoft streaming data processor, StreamInsight 2.1. Intermediate programming skills are required to follow along, and some experience with StreamInsight can come in handy. Before diving into StreamInsight, I’ll investigate the seemingly trivial problem of counting. For simplicity, assume the stream has events with payloads of 0 or 1—uninteresting and interesting events, respectively (regardless of what constitutes “interesting” in your specific scenario). The number of 1s is counted over a (fixed-size) count-based window containing the most recent N events. Naïve counting takes O(N) time and space. As an astute reader, you probably came up with the idea of maintaining the count between consecutive windows and incrementing it for new 1s and decrementing it for expired 1s, sharing the N-2 events already processed. Good thinking! Maintaining the count now takes O(1) time. However, should you decrement for an expired event or not? Unless you know the actual event, the count can’t be maintained. Unfortunately, to know the events until they have expired requires the entire window in memory—that is, it takes O(N) space. Another strategy might be to filter out the uninteresting events and count only the remaining interesting events. But that doesn’t reduce computational complexity and leaves you with a variable-size window. Can the memory beast be tamed? Yes, it can! However, it requires a compromise between processing time and memory space at the expense of accuracy. The seminal paper by Mayur Datar, Aristides Gionis, Piotr Indyk and Rajeev Motwani titled “Maintaining Stream Statistics over Sliding Windows” (stanford.io/SRjWT0) describes a data structure called the exponential histogram. It maintains an approximate count over the last N events with a bounded relative error ε. This means that at all times: Conceptually, the histogram stores events in buckets. Every bucket initially covers one event, so it has a count of 1 and a timestamp of the event it covers. When an event arrives, expired buckets (covering expired events) are removed. A bucket is created only for an interesting event. As buckets are created over time, they’re merged to save memory. Buckets are merged so they have exponentially growing counts from the most recent to the last bucket, that is, 1, 1, ..., 2, 2, ..., 4, 4, ..., 8, 8 and so on. This way, the number of buckets is logarithmic in the window size N. More precisely, it requires O(1⁄ε log N) time and space for maintenance. All but the last bucket cover only non-expired events. The last bucket covers at least one non-expired event. Its count must be estimated, which causes the error in approximating the overall count. Hence, the last bucket must be kept small enough to respect the relative error upper bound. In the next section, the implementation of the exponential histogram in C# is discussed with a bare minimum of math. Read the aforementioned paper for the intricate details. I’ll explain the code and follow up with a pen-and-paper example. The histogram is a building block for the StreamInsight user-defined stream operator developed later in this article. Here’s the bucket class: [DataContract] public class Bucket { [DataMember] private long timestamp; [DataMember] private long count; public long Timestamp { get { return timestamp; } set { timestamp = value; } } public long Count { get { return count; } set { count = value; } } } It has a count of the (interesting) events it covers and a timestamp of the most recent event it covers. Only the last bucket can cover expired events, as mentioned, but it must cover at least one non-expired event. Hence, all but the last bucket counts are exact. The last bucket count must be estimated by the histogram. Buckets containing only expired events are themselves expired and can be removed from the histogram. Using just two operations, the exponential histogram ensures a relative error upper bound ε on the count of interesting events over the N most recent events. One operation is for updating the histogram with new and expired events, maintaining the buckets. The other is for querying the approximate count from the buckets. The histogram class outline is shown in Figure 1. Next to the linked list of buckets, its key variables are the window size (n), the relative error upper bound (epsilon) and the cached sum of all bucket counts (total). In the constructor, the given window size, the given relative error upper bound and an initial empty list of buckets are set. Figure 1 The Exponential Histogram Class Outline [DataContract] public class ExponentialHistogram { [DataMember] private long n; [DataMember] private double epsilon; [DataMember] private long total; [DataMember] private LinkedList<Bucket> buckets; public ExponentialHistogram(long n, double epsilon) { this.n = n; this.epsilon = epsilon; this.buckets = new LinkedList<Bucket>(); } public void Update(long timestamp, bool e) { ... } protected void ExpireBuckets(long timestamp) { ... } protected void PrependNewBucket(long timestamp) { ... } protected void MergeBuckets() { ... } public long Query() { ... } } The maintenance of the histogram is performed by this update method: public void Update(long timestamp, bool eventPayload) { RemoveExpiredBuckets(timestamp); // No new bucket required; done processing if (!eventPayload) return; PrependNewBucket(timestamp); MergeBuckets(); } It accepts a discrete timestamp, as opposed to wall-clock time, to determine what the latest N events are. This is used to find and remove expired buckets. If the new event has a payload of 0 (false), processing stops. When the new event has a payload of 1 (true), a new bucket is created and prepended to the list of buckets. The real fireworks are in merging the buckets. The methods called by the update method are discussed in sequence. Here’s the code for the removal of buckets: protected void RemoveExpiredBuckets(long timestamp) { LinkedListNode<Bucket> node = buckets.Last; // A bucket expires if its timestamp // is before or at the current timestamp - n while (node != null && node.Value.Timestamp <= timestamp - n) { total -= node.Value.Count; buckets.RemoveLast(); node = buckets.Last; } } The traversal starts from the oldest (last) bucket and ends at the first non-expired bucket. Each bucket whose most recent event’s timestamp is expired—that is, whose timestamp is no greater than the current timestamp minus the window size—is removed from the list. This is where the discrete timestamp comes in. The sum of all bucket counts (total) is decremented by the count of each expired bucket. After expired events and buckets are accounted for, the new event is processed: protected void PrependNewBucket(long timestamp) { Bucket newBucket = new Bucket() { Timestamp = timestamp, Count = 1 }; buckets.AddFirst(newBucket); total++; } A new bucket for the event with a payload of 1 (true) is created with a count of 1 and a timestamp equal to the current timestamp. The new bucket is prepended to the list of buckets and the sum of all bucket counts (total) is incremented. The memory space-saving and error-bounding magic is in the merging of buckets. The code is listed in Figure 2. Buckets are merged so that consecutive buckets have exponentially growing counts, that is, 1, 1, ..., 2, 2, ..., 4, 4, ..., 8, 8 and so on. The number of buckets with the same count is determined by the choice of the relative error upper bound ε. The total number of buckets grows logarithmically with the size of the window n, which explains the memory space savings. As many buckets as possible are merged, but the last bucket’s count is kept small enough (compared to the sum of the other bucket counts) to ensure the relative error is bounded. Figure 2 Merging Buckets in the Histogram protected void MergeBuckets() { LinkedListNode<Bucket> current = buckets.First; LinkedListNode<Bucket> previous = null; int k = (int)Math.Ceiling(1 / epsilon); int kDiv2Add2 = (int)(Math.Ceiling(0.5 * k) + 2); int numberOfSameCount = 0; // Traverse buckets from first to last, hence in order of // descending timestamp and ascending count while (current != null) { if (previous != null && previous.Value.Count == current.Value.Count) numberOfSameCount++; else numberOfSameCount = 1; // Found k/2+2 buckets of the same count? if (numberOfSameCount == kDiv2Add2) { // Merge oldest (current and previous) into current current.Value.Timestamp = previous.Value.Timestamp; current.Value.Count = previous.Value.Count + current.Value.Count; buckets.Remove(previous); // A merged bucket can cause a cascade of merges due to // its new count, continue iteration from merged bucket // otherwise the cascade might go unnoticed previous = current.Previous; } else { // No merge, continue iteration with next bucket previous = current; current = current.Next; } } } More formally, buckets have non-decreasing counts from the first (most recent) to the last (oldest) bucket in the list. The bucket counts are constrained to powers of two. Let k = 1⁄ε and k⁄2 be an integer, or else replace the latter by . Except for the last bucket’s count, let there be at least k⁄2 and at most k⁄2 + 1 buckets of the same count. Whenever there are k⁄2 + 2 buckets of the same count, the oldest two are merged into one bucket with twice the count of the oldest bucket and the most recent of their timestamps. Whenever two buckets are merged, traversal continues from the merged bucket. The merge can cause a cascade of merges. Otherwise traversal continues from the next bucket. To get a feeling for the count approximation, look at the histogram’s query method: public long Query() { long last = buckets.Last != null ? buckets.Last.Value.Count : 0; return (long)Math.Ceiling(total - last / 2.0); } The sum of the bucket counts up to the last bucket is exact. The last bucket must cover at least one non-expired event, otherwise the bucket is expired and removed. Its count must be estimated because it can cover expired events. By estimating the actual count of the last bucket as half the last bucket’s count, the absolute error of that estimate is no larger than half that bucket’s count. The overall count is estimated by the sum of all bucket counts (total) minus half the last bucket’s count. To ensure the absolute error is within bounds of the relative error, the last bucket’s influence must be small enough compared to the sum of the other bucket counts. Thankfully, this is ensured by the merge procedure. Do the code listings and explanations up to this point leave you puzzled about the workings of the histogram? Read through the following example. Suppose you have a newly initialized histogram with window size n = 7 and relative error upper bound ε = 0.5, so k = 2. The histogram develops as shown in Figure 3, and a schematic overview of this histogram is depicted in Figure 4. In Figure 3, merges are at timestamps 5, 7 and 9. A cascaded merge is at timestamp 9. An expired bucket is at timestamp 13. I’ll go into more detail about this. Figure 3 Example of the Exponential Histogram Buckets (Timestamp, Count) Newest … Oldest Relative Error 5 (merge) 7 9 (cascaded merge) Figure 4 A Schematic Overview of the Histogram Depicted in Figure 3 The first event has no effect. At the fifth event, a merge of the oldest buckets occurs because there are Text Box: k⁄2 + 2 buckets with the same count of 1. Again, a merge happens at the seventh event. At the ninth event, a merge cascades into another merge. Note that after the seventh event, the first event expires. No bucket carries an expired timestamp until the 13th event. At the 13th event, the bucket with timestamp 6 no longer covers at least one non-expired event and thus expires. Note that the observed relative error is clearly less than the relative error upper bound. In Figure 4, a dotted box is the window size at that point; it contains the buckets and implies the span of events covered. A solid box is a bucket with timestamp on top and count on bottom. Situation A shows the histogram at timestamp 7 with arrows to the counted events. Situation B shows the histogram at timestamp 9. The last bucket covers expired events. Situation C shows the histogram at timestamp 13. The bucket with timestamp 6 expired. After putting it all together, I wrote a small demonstration program for the exponential histogram (check out the source code download for this article). The results are shown in Figure 5. It simulates a stream of 100 million events with a count-based window size N of 1 million events. Each event has a payload of 0 or 1 with 50 percent chance. It estimates the approximate count of 1s with an arbitrarily chosen relative error upper bound ε of 1 percent, or 99 percent accuracy. The memory savings of the histogram are huge compared to windows; the number of buckets is far less than the number of events in the window. An event rate of a few hundred thousand events per second is achieved on a machine with an Intel 2.4 GHz dual-core processor and 3GB of RAM running Windows 7. Figure 5 Empirical Results for the Exponential Histogram Perhaps you’re wondering what Microsoft StreamInsight is and where it fits in. This section provides some basics. StreamInsight is a robust, high-performance, low-overhead, near-zero-latency and extremely flexible engine for processing on streams. It’s currently at version 2.1. The full version requires a SQL Server license, though a trial version is available. It’s run either as a stand-alone service or embedded in-process. At the heart of streaming data processing is a model with temporal streams of events. Conceptually, it’s a potentially infinite and voluminous collection of data arriving over time. Think of stock exchange prices, weather telemetry, power monitoring, Web clicks, Internet traffic, toll booths and so on. Each event in the stream has a header with metadata and a payload of data. In the header of the event, a timestamp is kept, at a minimum. Events can arrive steadily, intermittently or perhaps in bursts of up to many thousands per second. Events come in three flavors: An event can be confined to a point in time; be valid for a certain interval; or be valid for an open-ended interval (edge). Besides events from the stream, a special punctuation event is issued by the engine called the Common Time Increment (CTI). Events can’t be inserted into the stream with a timestamp less than the CTI’s timestamp. Effectively, CTI events determine the extent to which events can arrive out of order. Thankfully, StreamInsight takes care of this. Heterogeneous sources of input and sinks of output streams must somehow be adapted to fit into this model. The events in the (queryable) temporal streams are captured in an IQStreamable<TPayload>. Event payloads are conceptually pulled by enumeration or pushed by observation into the stream. Hence, underlying data can be exposed through an IEnumerable<T>/IQueryable<T> (Reactive Extension) or IObservable<T>/IQbservable<T> (Reactive Extension), respectively, parameterized with the type of data exposed. They leave the maintenance of temporal aspects to the processing engine. Conversion from and to the various interfaces is possible. The sources and sinks just discussed live on the boundaries, whereas the actual processing happens within queries. A query is a basic unit of composition written in LINQ. It continuously processes events from one or more streams and outputs another stream. Queries are used to project, filter, group-apply, multicast, operate/aggregate, join, union and window events. Operators can be user-defined. They work on events (incremental) or on windows (non-incremental) as they arrive. A note on windowing is in order. Windowing partitions a stream into finite subsets of events that might overlap between consecutive windows. Windowing effectively produces a stream of windows, reflected by an IQWindowedStreamable<TPayload> in StreamInsight. Currently, three different kinds of windowing constructs are supported: count-based, time-based and snapshot windows. Count-based windows cover the most recent N events and slide upon the arrival of a new event, expiring the oldest and inserting the newest. Time-based windows cover the most recent events in the most recent interval of time and slide by some interval (also called hopping or tumbling). Snapshot windows are driven by event start and end times; that is, for every pair of closest event start and end times, a window is created. In contrast to time-based windows driven by intervals along the timeline, regardless of events, snapshot windows aren’t fixed along the timeline. That just scratches the surface. More information is available from several sources, including the online Developer’s Guide (bit.ly/T7Trrx), “A Hitchhiker’s Guide to StreamInsight 2.1 Queries” (bit.ly/NbybvY), CodePlex examples, the StreamInsight team blog (blogs.msdn.com/b/streaminsight) and others. The foundations are laid. At this point, you’re probably wondering how approximate counting is brought to life in StreamInsight. In short, some (temporal) source stream of point-in-time events, carrying a payload of 0 or 1, is required. It’s fed into a query that computes the approximate count of 1s over the N most recent events using the exponential histogram. The query produces some (temporal) stream of point-in-time events—carrying the approximate count—that’s fed into a sink. Let’s start with a user-defined operator for approximate counting. You might be tempted to capture the N most recent events using the count-based windowing construct. Think again! That would defy the memory-saving benefits of the exponential histogram. Why? The construct forces entire windows of events to be kept in memory. It’s not required by the exponential histogram, because it has an equivalent implicit notion of windowing through the maintenance of buckets. Moreover, having an operator over windows is non-incremental, that is, with no processing of events as they arrive, but only when a (next) window is available. The solution is a user-defined stream operator without explicit windowing constructs on the query. The code is listed in Figure 6. Figure 6 User-Defined Stream Operator Implementation [DataContract] public class ApproximateCountUDSO : CepPointStreamOperator<bool, long> { [DataMember] private ExponentialHistogram histogram; [DataMember] private long currentTimestamp; // Current (discrete) timestamp public ApproximateCountUDSO(long n, double epsilon) { histogram = new ExponentialHistogram(n, epsilon); } public override IEnumerable<long> ProcessEvent( PointEvent<bool> inputEvent) { currentTimestamp++; histogram.Update(currentTimestamp, inputEvent.Payload); yield return histogram.Query(); } public override bool IsEmpty { get { return false; } } } The operator derives from the abstract CepPointStreamOperator<TInputPayload, TOutputPayload>. It has an exponential histogram instance variable. Note the decoration with DataContract and DataMember attributes. This informs StreamInsight how to serialize the operator—for example, for resiliency purposes. The operator overrides the IsEmpty operator to indicate it’s non-empty, that is, the operator is stateful. This prevents StreamInsight from messing with the operator when minimizing memory utilization. The ProcessEvent method is the operator’s core. It increments the current (discrete) timestamp and passes it along with the event payload to the histogram’s update method. The histogram handles the bucketing and is queried for the approximate count. Make sure to use the yield-return syntax, which makes the operator enumerable. Operators are generally wrapped in some extension method hidden in a utility class. This code shows how it’s done: public static partial class Utility { public static IQStreamable<long> ApproximateCount( this IQStreamable<bool> source, long n, double epsilon) { return source.Scan(() => new ApproximateCountUDSO(n, epsilon)); } } That’s it! Plug the operator into a query via the extension method. A bit of extra code is required to actually demonstrate its use. Here’s a trivial source stream: public static partial class Utility { private static Random random = new Random((int)DateTime.Now.Ticks); public static IEnumerable<bool> EnumeratePayloads() { while (true) // ad infinitum { bool payload = random.NextDouble() >= 0.5; yield return payload; } } } This generates random payloads of 0s and 1s. The yield-return syntax turns it into an enumerable source. Put it in a utility class, if you will. The infamous Program class is shown in Figure 7. It creates the in-process embedded StreamInsight server instance. A so-called application instance named ApproximateCountDemo is created as a streaming processing (metadata) container, for example, for named streams, queries and so on. An enumerable source of point-in-time events is defined, using the payload-generating utility method described earlier. It’s transformed into a temporal stream of point-in-time events. The query is defined with LINQ and selects the operator approximate counts computed over the source stream. This is where the extension method for the user-defined operator comes in handy. It’s bootstrapped with a window size and relative error upper bound. Next, the query output is transformed into an enumerable sink, stripping the temporal properties. Finally, the sink is iterated over, thereby actively pulling the events through the pipeline. Execute the program and enjoy its number-crunching output on the screen. Figure 7 Embedding and Executing in StreamInsight class Program { public const long N = 10000; public const double Epsilon = 0.05; static void Main(string[] args) { using (Server server = Server.Create("StreamInsight21")) { var app = server.CreateApplication("ApproximateCountDemo"); // Define an enumerable source var source = app.DefineEnumerable(() => Utility.EnumeratePayloads()); // Wrap the source in a (temporal) point-in-time event stream // The time settings determine when CTI events // are generated by StreamInsight var sourceStream = source.ToPointStreamable(e => PointEvent.CreateInsert(DateTime.Now, e), AdvanceTimeSettings.IncreasingStartTime); // Produces a stream of approximate counts // over the latest N events with relative error bound Epsilon var query = from e in sourceStream.ApproximateCount(N, Epsilon) select e; // Unwrap the query's (temporal) point-in-time // stream to an enumerable sink var sink = query.ToEnumerable<long>(); foreach (long estimatedCount in sink) { Console.WriteLine(string.Format( "Enumerated Approximate count: {0}", estimatedCount)); } } } } To briefly recap, this article explains how to approximate the count over a window of events in logarithmic time and space with upper-bounded error using an exponential histogram data structure. The histogram is embedded in a StreamInsight user-defined operator. The histogram and operator can be extended to support variable-size windows, such as time-based windows. This requires the histogram to know the window interval/timespan rather than the window size. Buckets are expired when their timestamp is before the new event’s timestamp minus the window timespan. An extension to compute variance is proposed in the paper, “Maintaining Variance and k–Medians over Data Stream Windows,” by Brian Babcock, Mayur Datar, Rajeev Motwani and Liadan O’Callaghan (stanford.io/UEUG0i). Apart from histograms, other so-called synopsis structures are described in literature. You can think of random samples, heavy hitters, quantiles and so on. The source code accompanying this article is written in C# 4.0 with Visual Studio 2010 and requires StreamInsight 2.1. The code is free for use under the Microsoft Public License (Ms-PL). Note that it was developed for educational purposes and was neither optimized nor tested for production environments. Michael Meijer is a software engineer at CIMSOLUTIONS BV, where he provides IT consulting services and software development solutions to companies throughout the Netherlands. His interests in StreamInsight and streaming data processing started during his research at the University of Twente, Enschede, Netherlands, where he received a Master of Science degree in Computer Science–Information Systems Engineering. Thanks to the following technical experts for reviewing this article: Erik Hegeman, Roman Schindlauer and Bas Stemerdink More MSDN Magazine Blog entries > Browse All MSDN Magazines Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
http://msdn.microsoft.com/en-us/magazine/jj891055.aspx
CC-MAIN-2014-15
refinedweb
4,085
56.55
Why My Queries Hate Application Service Layers Last week, I was trying to take an old, procedural style ColdFusion application and factor out queries into some sort of Service layer. I wasn't trying to create an Object Oriented ColdFusion application - I was merely trying to centralize some business logic such that it wasn't so distributed throughout the application. At a glance, this seems like a rather simple concept; and, when I've applied it to simple applications like OOPhoto, adding a Service layer was a snap. But, this is quite a complex application that I'm working with and I quickly found adding a Service layer to be an extremely painful task. The first thing that tripped me up was figuring out what the "gesture" of the query was. Meaning, what was the query doing and how could I name the Service layer method to reflect this intention. Furthermore, how could I define the method in such a way that made it reusable in different situations since it's only in the reusable nature of centralized queries that make them worthwhile (otherwise, you might as well just have them inline). It was this "reuse" part that really slammed me into a wall. As I examined my queries, I realized that they were almost all different in some way. And I don't mean that they had slightly different WHERE clauses - I mean that they had completely different JOIN clauses and calculated columns based on the page in which they were used. I was really stumped. The queries seemed to be right, but they all seemed to be a bit too different to reuse in any way. This vexed me greatly as I started to become concerned that this same issue would challenge me on future projects. Then, after staring blankly at a query for no less than 20 minutes, it finally occurred to me why my queries were so distinct and non-reusable: The queries themselves were used for a combination of both data retrieval and data validation in a contextual way. It's the contextual data retrieval and validation aspects that was making them so page specific and non-reusable. Let me give you an example: Suppose I am on a page where a user get's to download a Asset with the given ID for a given Project. Well, rather than just getting the Asset at the given ID, I get the Asset at the given ID with it associated project details (project name) in the context of the given Project (untested code): - a.id, - a.name, - a.filename, - a.project_id, - ( p.name ) AS project_name - FROM - asset a - INNER JOIN - project p - ON - ( - a.id = #asset_id# - AND - p.id = #project_id# - AND - a.project_id = p.id - ) Yes, I am simply getting back the given Asset at the given ID with this query. But, the query doesn't just hit the Asset table; rather, it hits the asset table in the context of a Project-based JOIN on the project ID and returns project information as well. Meaning, it uses the query not only to get the Asset and the Project, but also to enforce the fact the given Asset belongs to the given project. In the end, I know that if the query doesn't return any rows, any of the following might be true: - Asset ID was incorrect. - Project ID was incorrect. - Given Asset was not part of the given Project. This was really useful because it made my post-query validation a snap. But, it is this type of contextual query that is making my Service layer a nightmare to create (I have, in fact, stopped for the time being). Because the query performs several actions (two explicit and one implicit), it really ties each query quite tightly to the page in which it is used, making it almost entirely non-reusable across the application. So, how would I fix this going forward in future applications? I am not 100% sure that this is correct, but I suppose that I would have to separate multi-table data retrieval and pull the context validation out of the query and perform validation in a secondary step. For example (pseudo code): - qProject >> - p.id, - p.name - FROM - project p - WHERE - p.id = #project_id# - qAsset >> - a.id, - a.name, - a.filename, - a.project_id - FROM - asset a - WHERE - a.id = #asset_id# - Validation >> - if - (NOT qProject.RecordCount) OR - (NOT qAsset.RecordCount) OR - (qProject.id NEQ qAsset.project_id) - then - // Throw error that data was not valid. Now that the asset query is just getting back the asset information and the project query is just getting back the project information and the context validation is performed after both queries have run, suddenly the two separated, cohesive queries become much more easily definable and reusable across the application. Thinking back now, I have a serious habit of making my SQL queries complex with all kinds of JOINs to build data retrieval and data validation into a single step. Understanding this, I now realize that upgrading my existing applications to be less "spaghettified" is going to not only require factoring out queries, but also completely changing the way in which they were used. That's probably not going to happen; looks like a forward-only type of change. As a final note, I just want to say that I really like the complex queries. They seemed to have so much more "intent". These little, table-access queries just seem so... I don't know... not exciting. But, I guess it's just that thinking that has come back to bite, I've been struggling with similar issues in my current application: a large number of my queries aren't reusable because they are specific to single use/display. I'm hopeful that this post might spark some discussion, but I really don't agree with your closing design. Breaking a single query with a join into two or more queries plus a CF validation bit is horribly inefficient, and that will come back to haunt you. In my current application I started with lots of flexible general use queries and would do things to reuse them like: x = getSites() y = getSections(ValueList(x.siteID)) And in almost every case I've had to go back and convert these into joins for efficiency. in other words, while it might be a prettier solution to be able to reuse chunks, it can't come at the cost of performance. But, Ben, if your function or view needs data from more than one table, a well-written query with the proper joins gets you the needed data with one call to the database rather than two or three separate calls. Avoiding multi-table queries (which is what you seem to be contemplating here) is only going to increase the number of database transactions in your application and slow down its performance. @Jon, Yeah, I am hoping there is some good discussion here. Hopefully others can either sympathize with this or tell me why it's junk :) @Brian, I agree with you 100%. The problem, however, that I was experiencing is that this "efficiency" made my queries almost completely non-reusable. So, perhaps its just a trade off? I have struggled with this one a bit myself in creating an OO application and trying to keep the queries as reusable as possible. But my biggest hurdle has been more of a query performance issue. For example if I have an article table and at some point I want to retrieve articles based on date, and at another point I want to retrieve articles based on author, I could write a single simple query that retrieves all the data I need and then use the application to filter out the data I want. But the database and systems guys compel me to write these as two separate queries for performance sake since over all the queries would be quicker if those clauses were defined within the sql syntax. This is a simplified example of much more complex data retrieval requirements that actually cause us to regard performance highly and unfortunately also causes us to write many queries for thing like "articles". @Brian, I understand completely. If you want articles by author, depending on your structure, you could simply JOIN article to author table on a given author id. That's why I think sometimes methods like: getArticlesByAuthorID() ... made with the appropriate JOIN. Of course, whether this can be reused is another issue. But then again, not every query can be reused. However, that said, I think sometimes, the complex queries can be made more reusable if they were split up more.... but at a trade off. Yep, and so I end up with many getArticlesBy*() functions. And yes I realize this is pretty much an inherent issue we must live with, but I am for sure looking forward to the day where query performance on a database server makes this issue much more moot. @brian, For your example, I would suggest writing dynamic queries where the filter is determined at runtime. So, for example you could have a getByfilter() method that determines whether to return articles based on author or date (or whatever) depending on what arguments you pass in. So, for instance, articleManager.getByFilter(date="< #now()#") or articleManager.getByFilter(author="Brian"). @Tony, The issue with that, as I am sure Brian will attest to, is that a query that filters on "Date" might have a completely different structure than one that is optimized to filter on "Author". For example, the Date-based filter might not bother using a JOIN on authors. @Tony seems to have hit it on the head! In .NET development, there is an add-on called nHybernate. Once you set up some XML mapping in your application, you just make calls to a DAO and pass in parameters that are used by the DAO to automatically run just the right query and return just the right data. I don't see anything wrong with writing CFC's that do basically the same thing--execute any of a number of possible optimized queries based on params/filters passed in. Then, it's the METHOD and/or CFC that is reusable and we don't have to focus so much on the SQL until we find that one or more of the queries the METHOD runs has performance issues. Then we just update the SQL but all our calls to the METHOD or CFC don't have to be changed when the queries do. Why don't you wrap that 1st query in a function and return a struct with the values needed and handle the logic in just to access one property is pretty inefficient. Anyway, I think it's a question of balance and of thinking about how much we want to optimize. As things stand, there are inline queries throughout the code. Bringing all the queries into a central location is better, imo, because it's easier to make changes when all the code is one place. Next, if some of the queries can be reused as they are, that's an extra bonus. And if some can be generalized to better handle reuse, then that's a third benefit. But I think it's a case by case situation. For some very complex queries where performance is important, it will make sense to keep them very specific. Kind of like how game programming is much more low level than other programming because it needs to be very efficient in its execution. In my experience, abstaction leads to performance penalties. We've accepted this with programming but we're not so used to encountering this with queries. Anyone have examples of the contrary? more than what i need, otherwise I would use it myself. Something to think about! @ Ben/Tony Yes Ben this is exactly the case. @ David Is this now where we enter into ORM territory? And speaking of nHybernate, is this similar to the Hibernate that is slated for cf9? @Brian, I'm not sure about CF9 but nHybernate is definitely all about ORM. At my current office I work with a guy who has been writing Java (no CF, just Java) for about 10 years. We have talked about this quite often. His explanation is that we often centralize our apps around the database instead of the other way around. If we are programmers, not dba's, then why do we try to have the db do so much? In other words- use your strengths. If your strength is CF, then use CF to handle the logic. Let the application become huge, not the queries. It will become so much more maintainable that way. @ brandon Sure, and I would love to do it this way but since I work for an organization where not only i am told to do it in this certain manner, but it makes sense to write very specific queries because of the sheer traffic our sites get to where we need all the database performance we can sqeeze out of our db cluster is very important. I doubt the average java program has database traffic/performace issues to the degree web applications do. I don't think the issue is whether or not we can wrap queries up in a service layer. You can always take code written in one place and move it behind a method call. But, there is a question of naming. For example, @Hatem, what would I name the first query method? It gets the asset AND the project using the Asset ID and the Project ID. The only thing fitting would be something like: GetAssetAndProjectByAssetIDAndProjectID() ... but that's a bit crazy :) You can't go with GetByFilter() because AssetID and ProjectID are not optional filter items - they are essential to the intent of the query. ... not really sure how to even move this into a query gracefully. @Brandon, I like the concept... but even in that mindset, I think we run into similar issues. For example, see my above comment about naming. How can we name the intent of such a query? @Ben, It would look more like this: GetAssetAndProject(assetId, projectId) That method could, ultimately, handle multiple signatures. You might create a case for: GetAssetAndProject(userId) and another for: GetAssetAndProject(accountId, loginId) Basically, write the Method so that you can get what you are asking for via whatever you MIGHT pass in. Detail(), assuming that I don't have to return assets any other way. I would imagine the project info is required to return an asset in this case. @Ben, Long method names are totally fine, the one you mentioned was a bit longer than what I would like, but in some cases you have to have a descriptive method name! @David, My concern there is that the intent of the method becomes a bit "surprising". I would prefer explicit methods over multi-signature methods. Plus, I think with that kind of approach, optimizing becomes awkward; everytime you add another method signature, you have to start looking at existing, internal solutions to see if they can be updated to use new signature or if a completely new query needs to be run internally. @Hatem, I would definitely be all for creating various CFCs to handle the application "verticals". However, I am not sure the intent of the method is really to simply get the Asset Detail as it does get project information as well. I think we could easily think of a use to get asset details that are not related to projects (ex. a page that list 5 most recent asset uploads with download link). This would not be in the context of a project, simply for asset retrieval. Maybe its a silly example... maybe the long, wordy name is really the only way to express the true intent of the underlying request. I am OK with that - it's just that it doesn't make the query reusable (much). Put the complexity into the Method, rather than the flow control/logic. The method name should be simple: GetSomething() The params passed in should be a set of optional params--obviously, SOMETHING should be passed in--but the signature of what is passed should be used by the method to determine which query to run. This isn't supported very well in CF but I still think it's worth pursuing in many cases. It makes for less maintenance of the business logic. @ Ben I do a combination of what Hatem and David suggest. Actually this is what I am developing at the moment, and feel free everyone to comment on this. For each "object" of data i need, for instance, user or article, I have a separate package named as such, with each containing a CRUD, and a Gateway object. If it isn't obvious, the CRUD object handles creates,reads,updates,and writes to single rows. The Gateway object handles reads of entire recordsets. Now, withing my gateway since it already inherently belongs to "article" my method looks like so: qryByAuthor( authorid ); or qryByDate( date ) ; So in your case Ben instead of: GetAssetAndProjectByAssetIDAndProjectID() The method could be getByAssetAndProject() ; In this case could the ID portion be assumed? @David I disagree with you. A method should have only one purpose. As soon as you do as you suggest your method now has multiple purposes. In other words the method should used the passed in data to perform a task, rather than use the passed in data to decide which task to perform. That logic belongs outside of the method call, deciding which method to call. @Brian, I think that makes sense. However, even with this, all we've done is moved the query into a method. We have done nothing to make the method more general and therefore more reusable, which I think is still a point of contention. What I don't want to end up with is a server layer or gateway layer that has 40 methods, each of which only gets used once in the application. I mean, if that's the way it needs to be, that's the way it needs to be; but, is that how it is because my original query did *too* much? still allow reuse of code and expressive code. I often have data layer methods that conditionally JOIN across different tables. @Brian I am pretty sure that java apps get plenty of traffic. Think LinkedIn. Any site that has the extension .do is a java app behind the scenes. @Ben It is always much harder to come to a complete app and refactor, so in some ways, you are in a difficult place. It seems like the app was designed around a database instead of the other way around. So, while it would be great to think that there is a lot that you can do, you are in a difficult place and might have to keep a lot of logic in the query. But going forward, it is great to use an ORM, such as Hibernate, that way you are thinking in terms of OBJECTS not in terms of queries or databases. This allows the application to flow a lot more smoothly. @Sean, That sounds pretty good. Conditional joins can be nice; but, the one thing I don't like about them is that filter logic then usually needs to be duplicated to some respect. For instance, if I have a JOIN, naturally, I would move as much filter logic into the ON clause of the JOIN. However, if I don't have a JOIN, some of that filter logic needs to be moved into a WHERE clause. So, there's just a lot of checking to see what should go where and whether or not different clauses need to be defined. Not the end of the world, but something that has always seems error-prone. @Brandon, It's interesting; I don't think I think in terms of the database - I think in terms of data "points". For example, I don't need a "project record" - I need a "project name". Maybe its the same thing, maybe it's a slightly different take on it. Remind me again: what exactly is so great about reusable queries? @Hal, That question must be answered with another question, which is I think the driving force behind the first: What so wrong with inline queries? I think the answer to your question has its foundation in the answer to this question. I am still a journeyman and not one who can truly answer such a question. My gut tells me that these two go hand in hand. That an inline query would not be *bad* unless it involved duplication. Therefore, to refactor, I assume would require something to be reusable (otherwise, there would be no point to refactoring). Perhaps there is an assumption somewhere that's wrong - a straw man or something. @Hal, It limits the number of times that you have to write the same query with different params, lol! use a cfswitch with four cases: Select, Update, Insert, Delete. Now you're down to one cfquery tag for your entire app! Sweet! @Ben, yes, the JOIN ON / WHERE logic can get a bit hairy if you have lots of options in a method. It's a fine line to walk figuring out what should go in a generic method vs when to add a custom method for a complex query. @Hal, that's a good question. If a query really only used in one place and there's no similar query elsewhere in the app, it doesn't need to be shoehorned into reuse. If you have several similar queries sprinkled all over the application, don't you think it makes maintenance easier to centralize those? I don't think that methods should necessarily have one purpose (as Brian stated). Even in Java, you have method overloading, where the method's purpose is determined by its arguments. In CF we can do this with duck typing. I've lately gotten into using base classes for my data access and use an approach similar to what Sean suggests where the intent of the method is reflected in its arguments. If you want to have more "expressive" methods, you can add in some syntactic sugar by having facade methods. So getByAuthor(id) calls getByFilter(authorID=id) behind the scenes. As you abstract more of this out, you do end up with more "standardized" queries. But for me the need for really complex un-reusable queries is more of an edge case. Ben -- in response to my last comment, you said "the Date-based filter might not bother using a JOIN on authors." That's actually something else that can be parametrized. My base getByFilter method can take an optional argument which is a comma-delimited list of fields to return (even those joined by a foreign key). So getArticleByAuthor(id) calls getByFilter(authorid=id) and getArticleByDate(date) calls getByFilter(date=date, fields="articleID,date,summary,body"). There you go -- no superfluous author field. These kinds of dynamic queries can get pretty complex, but the beauty of it is that you only have to write them once. @Matt, I hope no one actually tries that! You illustrate well the trap that folks can fall into if they take the drive for reuse too far. Any given application contains an inherent amount of complexity. You can put it all in one file/method (and have the ultimate procedure app) or distribute every single little piece of it into separate objects (and have the ultimate OO app). The complexity is still there. In the former, it's explicit in the logic. In the latter, it's more implicit in the relationships between all those objects (and that's something folks can have a really hard time with when they're relatively new to OO). The trick - as always - is striking a balance and finding the best set of trade offs for your application and your team's skill set. I'd like to submit my vote for the "straw man" theory! my plan. I suspect that you had your tongue firmly in cheek when you wrote your comment. ;-) In fact, I think that code with conditionals scattered through it is a sign of UNmaintainability. Over the years, I've learned to be extremely wary of conditionals creeping into my code: they're almost always a sure sign that I'm on the wrong track. SQL is all about taking encapsulated, separate tables (forgive me for using bad terminology, Dr. Codd) and "flattening" them. It's wonderfully clever but the price paid is reusability of atomic pieces of code. It's a price I'm well willing to pay: I want optimized queries that run fast. I can get reusability by having separate queries rather than a join, but THAT price -- slow execution -- is too great. or merely ACCIDENTALLY the same?" Answering that question correctly has saved me a lot of grief. pretty well expresses my feelings about superqueries. the same SQL in both, factoring that commonality out provides extremely marginal benefits but comes, as I said, at a very high price vis-a-vis performance. I've definitely been following these comments and I have to say this is all very interesting stuff to see everyone's different approach to accomplishing the same basic tasks. Getting data from the database in the easiest way and fastest way possible is really is what this is all about. @ Ben Trying to get back your blog post, I would like to ask you what is the purpose of your service layer? If all you are trying to do is pull your queries out from inline code and get them all in the same easily accessible area, does it really need to be any more than that in the case of this procedural app? @ Hal Wouldn't another good reason to pull that query out be to have your queries in a central location for easier editing in many circumstances? Obviously small applications it wouldn't matter, but the larger they get, the more buried your queries my become. @Brian Good point, Brian., if you ever want to make a new view for the data then you would be better off with the data call in the service layer rather than inline. Also, potentially important, the UI layer of your application can't be reused because there's an inline query sitting in it. Admittedly, you probably won't be reusing your UI logic somewhere else, although once you start pulling out all the inline stuff it's amazing how similar data views are. Still, this is the same sort of stuff I think about when I'm refactoring my service layer. If I wanted to get more complex, after moving the inline call to the service layer, the first thing I would probably do is to move it again to a data layer. Then when I create the service I pass in some sort of information about the project. Depending on that information the service would load a different data access object. Since the service already knows about my project from when I instantiate the service now the only parameter I need in my service method is assetId and the method GetAsset(assetId) is likely a pretty reusable service call. Many posts later and I that I'm still in the same boat at least. I think the discussion has basically said that putting all queries together is good for mainainability, but reuse is only important if it doesn't impact performance. Thats pretty much the rule I follow. I try to make my queries flexible (customizable column returns, order bys, and limits) but just make a new query when I need really different stuff. @Hal, Well, actually the main purpose of my approach as outlined here is to deal with the more repetitive SQL -- the boilerplate CRUD stuff I don't want to cut-and-paste everywhere and change the field and table names. Do I try to use my generalized methods as much as I can? Yes, because it makes me more efficient. But I'm not naive to think that it's always practical. I have nothing against highly specific methods or queries when they're called for. So I wouldn't characterize my approach in general as a "do all" approach. I have to agree with Hal. Normalization of a database means that it will be spread over multiple tables and each query is going to join on these tables differently. This is what makes OLTP efficient. @Hal, I love your wording of "accidentally similar" query definitions. One thing to keep in mind is database coding is different to procedural and OO coding; and attempting to apply their best practices to it may not work. My personal belief is to encapsulate queries in logical CFCs (not table based), for example: Client, Administrator, Manager; instead of User. This approach allows for reuse of small queries (like filling lists) and maintainability of code. If there is a need for multiple queries, then there is a need. I would like to point out that SQL it self is an extracted layer. You don't have to know how it selects/updates/inserts/deletes your data to use it. ;) been running into this one with increasing frequency the more unit testing I do: if your queries are completely contained in functions, then you can mock them in unit tests. This pattern has served me very well..... I have a function that "does things", i.e. contains "business logic". It gets its data, and operates on that data. For example, let's say I have a function named "preventRollbackOnOutstandingOrders" or some such thing. Now, the purpose of this function is to "do stuff" when there are outstanding orders. Even in this case, rather than have the query to retrieve outstanding orders inside of that function, i'll pull it out: "getOutstandingOrders". and then my preventRollback.... function will call getOutstandingOrders() and then do whatever it needs to do with that result. this might seem stupid. but here's what it gets me. in my unit tests, I can now easily test all teh logic in preventRollback... because I can mock the getOutstandingOrders query to return all the different kinds of resultsets i need to prepare for in the real world. (shameless plug: I addressed this at cfobjective in the "writing easy-to-test code presentation. You can download it here:). In a nutshell, for me, keeping the queries separate gives me *freedom* name, and may only be used in one place. Reuse is not the holy grail. If you can't find the reuse in a resonable time frame, it's probably not a candidate. Otherwise, you risk spend an eon chasing it down. Just because a query SEEMS similar to others and it SEEMS like you might be repeating yourself, chances are if you've had to put this much thought into what to do with it, it's probably a one-off query that runs great, and is used for a single purpose. Put it inside it's own function, grouped with similar functions, in whatever layer you think it belongs, and leave it alone! You can always refactor if you discover a means of reuse later, and as long as you are continually thinking about your app, refactoring should always be on the table, at each step. The idea of splitting it up into multiple queries is nonsense... and it's the type of stuff that makes for really piss-poor performance. You'd be abstracting away just about everything that is great about your database tier. I get seriously irked when I see that in an app... probably more than any other poor programming practice I've had to recode. And I've been playing code janitor for a long time. Everyone worries so much about having "dumb objects" (or whatever the term is nowadays), but I think it's worse to treat your database tier as if *IT* were dumb. It's certainly not. And it's not at all bad to have a few single purpose, single use functions. It's going to happen in just about any application... so don't worry about it. At least not until Hal finishes his Do() app. Then we're all home free! ;) Get on that, Hal.. Between that and the cfargument tags, I'm guessing you won't ever have trouble figuring out what that particular function does. And you get the added benefit of generating your good documentation automatically using CFCDoc, which picks up all those hints/descriptions. Once a method name reaches critical mass, this is truly a good fallback option, IMO. @All, I am sorry that I used the phrase Service Layer or even talked about data-access layers; not because that was not my intent, but rather because I think they are very loaded phrases and I think the conversation here has gotten somewhat off track from my original point (which perhaps I did not express very clearly). When I write a procedural application with queries on a per-page level (usually in "Action" files), it is very easy and satisfying to write a beefy, complex query that: 1. Gets ONLY the data required by the give page (with no extra columns returned). 2. Has additional calculated columns that are ONLY used in this page. 3. Performs validation of data across all aspects of the possible JOIN clauses. That's really nice to do because: 1. It requires a minimum number of calls to the database. 2. It does not return any extraneous data. Now, clearly, this is thinking in terms of data (NOT THE DATABASE - let's please draw that distinction - I don't care about the database - it only influences my JOINs - I care only about the data that I get back). This is fine because it is efficient on a page-level basis. BUT, my real, original question / thought was, does optimizing each query for its singular use hinder me too severely in ability to reuse logic. And, if so, is that even a problem? simply for the sake of "reuse", consider that your last resort. If the query really is complex and built the way it is because it's the best way to get back the data that is needed in the vie, then I don't consider that a problem at all. It's where you PUT the query, and how you choose to group it with similar functionality somewhere in your app that will lead to maintainability and the potential for reuse down the line. If you are building complex views that use data that is assembled from the database in a complex way, that may just be the nature of your app. Optimizing your queries for singular use will make your users happy when the app screams, and putting those queries in a logical place will make YOU or any future developer working on the code just as happy. If you have logic that's based on the results of a query, and that logic applies to more than one query, abstract it out if you can; otherwise, document it's existence and move on. As you can tell by now, I'm against making inefficient queries, so anything you do to your nice efficient query had better be for a darn good reason. I guess only you can decide though, what the threshold is; where you cross over into "a good reason". Size and anticipated load of the app come into play too, but I don't think "small" is a good enough reason to abandon good SQL just because it can't be reused. @Marc F, Hmmm, I always dislike the "no right answer", but I've come to accept that it's just a way of life :( Here's an interesting concept though, that this brings up - a person who is a SQL guru will probably think about their data access in a completely different way than someone who knows the basics. I am not saying that I am a SQL guru by any means (I just love JOINs), but it seems that the more someone knows about SQL, the more they can view every situation as an "opportunity" for optimization that may or may not completely conflict with "design for reuse". code reuse. Then, they might argue that their way is "better" simply because of the code reuse they inadvertently realized. If there's any place that optimization should be explored, it's in the access to an RDBMS. I've seen the arguments, ad nauseum, over such drivel as "which is faster, CFIF or CFCASE", or other such things with so little overall processing time to gain, while the database tier is left to substantial abuse, with HUGE repercussions. So, even though I myself am not a "guru" of SQL, I continually strive to make the database access as efficient as possible up-front because a mistake there is much more costly to me in development than whether something was reusable, or even "optimally maintainable". I'd much rather have to go back and do the small stuff, than futz with replacing several queries with one good one when the app load started to demand it. If *every* query is in conflict with code reuse, then you have a truly unique situation. Any developer that is at the level to be talking about layers of abstraction, and the type of code reuse you're discussing, is already "thinking right" in my view, and is capable of seeing whether or not a query can be made more generic or whether it's a one-off request for a specifically formatted dataset. You make the best decision you can about how to structure your queries, hopefully with "leveraging the best features of the database tier" (or at least "not ignoring") at the top of the list, and those that can be reused will fall into place. I suppose I've already made this too clear, and am repeating myself, but I think it would be a real shame for someone to "know" which SQL statement would be best, and choose not to use it for the mere sake of "reusability", and a true disservice to the users, the hardware and software that's been purchased to do the job, and the folks that put so much effort into creating whatever outstanding RDBMS you've chosen (and today, ALL of them are pretty outstanding). If you are more advanced with SQL, then your queries SHOULD reflect that, and I don't think they should be the first thing to be abandoned, in order to bend to the way someone thinks their app should "look" or be organized. But some people do, I'm sure. If you love JOINs, what about all the OTHER cool things that an enterprise-tier database can do? CUBE, ROLLUP, stored procs, views, and the ever-important execution analysis... if you start down that slippery slope of bending your "best choice" SQL with absolute commitment to your app design goals, could you be eventually ignoring or circumventing those features too? Do we want anyone else that's learning this stuff to believe that they don't HAVE to become better at SQL, or leverage what their DB tier offers? I don't think so. Call it "data centric" or whatever other derogatory terms will come along, but if you're pulling data from your database, do it the best way possible for how it's going to be used, and if it's reusable great. If not, no big deal. It's not just an "opportunity" for optimization -- the db tier and the language are *designed* to give you the optimization, all you have to do is leverage it. You can either embrace that or circumvent it. It's just one area that I feel NOT leveraging it is much more expensive if you find you have to later. UGH... how am i ever going to learn to write without being so long-winded... @Marc F, Long winded or not, I like what you have to say. Very though provoking. Thank you for your feedback. I don't think that *every* SQL statement that I have is optimized so highly for the given page; however, almost ANY query that joins a table(s) has potential for page-specific differentiation. Even something simple like: contact / contact_information. The same could be said about most join relationships (sometimes the JOIN'd information is simply irrelevant even if it is part of a "whole" concept). Lots to think about here! Perhaps my preoccupation with things like not pulling down extra columns is a silly form of optimization, especially with small data sets. ." This is the exact reason that you use an ORM. You don't have to worry about what type of query to run (as much). Because they often use lazy loading, they only run the queries when needed. Of course, this can get expensive at times, which is why it can be overridden, but it will also save A TON of development time. It has been said time and time again that hardware is cheap. Developers are not. As one of the devs that I work with says- "Premature optimization is the root of all evil." Don't worry about optimizing your query until you know that you need to. A great book (with a free html version) is Getting Real by 37 Signals. @Brandon, Thanks for the book link; I'll definitely be checking it out. I was not away that ORMs do / could lazy-load JOIN-based information. That seems pretty cool; seems like a super complicated process (depending on the number of joins that might be there).. Just my 2c of course... there WILL be those that Object (pun intended) and I don't discount their position, I simply don't agree with it. ." HA... those two list items are the same damned thing. Guess I'd better get my coffee on. =) ORMs like Hibernate can be asked to handle object joins in either a lazy or non-lazy manner, even on a specific query. That's nice because it means you can say contact / contact_information is lazy but still override it with HQL (Hibernate Query Language) when you want a non-lazy version: The nice thing about this is that you can design and program your application with an object-centric approach and then apply query optimization where you need it. So it doesn't have to be all-application or all-SQL in terms of building performance in from the start, you can have your ORM cake and eat it too.
http://www.bennadel.com/blog/1614-why-my-queries-hate-application-service-layers.htm?_rewrite
CC-MAIN-2015-32
refinedweb
7,178
69.92
Parsing YAML without a schema When using strictyaml you do not have to specify a schema. If you do this, the validator “Any” is used which will accept any mapping and any list and any scalar values (which will always be interpreted as a string, unlike regular YAML). This is the recommended approach when rapidly prototyping and the desired schema is fluid. When your prototype code is parsing YAML that has a more fixed structure, we recommend that you ‘lock it down’ with a schema. The Any validator can be used inside fixed structures as well. Example yaml_snippet: a: x: 9 y: 8 b: 2 c: 3 from strictyaml import Str, Any, MapPattern, load from ensure import Ensure Parse without validator: Ensure(load(yaml_snippet)).equals({"a": {"x": "9", "y": "8"}, "b": "2", "c": "3"}) Parse with any validator - equivalent: Ensure(load(yaml_snippet, Any())).equals({"a": {"x": "9", "y": "8"}, "b": "2", "c": "3"}) Fix higher levels of schema: Ensure(load(yaml_snippet, MapPattern(Str(), Any()))).equals({"a": {"x": "9", "y": "8"}, "b": "2", "c": "3"}) Executable specification Page automatically generated from non-schema-validation.story.
https://hitchdev.com/strictyaml/using/alpha/howto/without-a-schema/
CC-MAIN-2019-09
refinedweb
184
52.49
Understanding Struts Controller Understanding Struts Controller  .... ActionServlet uses the configuration defined in struts-config.xml file to decide...-config.xml file to map the request to some destination servlet or jsp file. The class struts-config.xml struts-config.xml What are the important sections in Struts Configuration File ? struts-config.xml more than one struts-config.xml file more than one struts-config.xml file Can we have more than one struts-config.xml file for a single Struts application-config.xml - Struts struts-config.xml in struts-config.xml i have seen some code like in this what is the meaning of "{1}". when u used like this? what is the purpose of use - Struts Struts Hi, I m getting Error when runing struts application. i have already define path in web.xml i m sending -- ActionServlet... /WEB-INF/struts-config.xml 1 File Upload and Save ;); } } Defining form Bean in struts-config.xml file Add the following entry in the struts-config.xml file for defining the form bean... in the struts-config.xml file: <action path STRUTS STRUTS Request context in struts? SendRedirect () and forward how to configure in struts-config.xml struts - Struts struts shud i write all the beans in the tag of struts-config.xml Struts File Upload Example in struts-config.xml file Add the following entry in the struts-config.xml file... entry in the struts-config.xml file: <action... Struts File Upload Example   struts ; <h1></h1> <p>struts-config.xml</p> <p>...struts <p>hi here is my code can you please help me to solve...;<struts-config> <form-beans> <form-bean name }//execute }//class struts-config.xml <struts...;!-- This file contains the default Struts Validator pluggable validator... in the struts-config.xml under the plug-in element for the ValidatorPlugIn Developing Struts Application it to a specified instance of Action class.(as specified in struts-config.xml...,forms, action-forwards etc are given in struts-config.xml... ( besides the web.xml & struts-config.xml files) Where is the much-spoken Developing Struts PlugIn the following line your struts-config.xml file. <plug-in className... can create your own PlugIn. Understanding PlugIn Struts PlugIns are configured using the <plug-in> element within the Struts configuration file Exception in Struts - Struts Exception in Struts 1.How we handle exception in struts? 2.How we write our custome exception in struts? 3.When the struts-config.xml will be loaded Validator Framework - lab oriented lesson ,the ActionServlet(controller) is invoked. It looks into the struts-config.xml file... entered by us in the struts-config.xml file .The Action class does not do.... The entire thing allows Declarative change management through the struts-config.xml struts <html:select> - Struts , allowing Struts to figure out the form class from the struts-config.xml file...struts i am new to struts.when i execute the following code i am... in the Struts HTML FORM tag as follows: Thanks Struts Step by Step the web.xml for the application 3. Write struts-config.xml, which is main configuration file in struts 1.x framework 4. Write ActionForm classes 5. Write...Struts Step by Step Step by step Struts Tutorials Here we are providing Step Struts - Struts Struts Hi All, Can we have more than one struts-config.xml in a web-application? If so can u explain me how with an example? Thanks in Advance.. Yes we can have more than one struts config files.. Here we Reg struts - Struts Reg struts Hi, Iam having Booksearch.jsp, BooksearchForm.java,BooksearchAction.java. I compiled java files successfully. In struts-config.xml Is this correct? I would like to know how do i have to make action servlet action not available - Struts config /WEB-INF/struts-config.xml 2 action *.do index.jsp struts-config file...servlet action not available hi i am new to struts and i am how to print the content of file in 2d matrix having same dimension as given in file(n*m). how to print the content of file in 2d matrix having same dimension as given in file(n*m). here is code: import java.io.File; import... IOException { Scanner s = new Scanner(new File("rfg.txt")); List list = datasource in jsp using struts datasource in jsp using struts how to get the datasource object in jsp.datasource is configured in struts-config.xml struts first example - Struts welcome.title=Struts Blank Application welcome.heading=Welcome! index.jsp struts-config.xml...struts first example I got errors in struts first example like file uploading - Struts Struts file uploading Hi all, My application I am uploading files using Struts FormFile. Below is the code. NewDocumentForm newDocumentForm = (NewDocumentForm) form; FormFile file The server encountered internal error() - Struts org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml... the problem in struts application. Here is my web.xml MYAPP... file I use the following code. Do I need to add something about that uri struts struts why doc type is not manditory in struts configuration file m mad m mad pratiksha says - how to code the project?? :P Struts Struts What is called properties file in struts? How you call the properties message to the View (Front End) JSP Pages followin dat upload file in db tutorial Create a table named .................. //********** cfg file Struts Guide , Action, ActionForm and struts-config.xml are the part of Controller...? - - Struts Frame work is the implementation of Model-View-Controller (MVC) design... the official site of Struts. Extract the file ito java file upload in struts - Struts java file upload in struts i need code for upload and download file using struts in flex.plese help me Hi Friend, Please visit the following links: http Struts Struts 1)in struts server side validations u are using programmatically validations and declarative validations? tell me which one is better ? 2) How to enable the validator plug-in file) Difference between Action form and DynaActionForm? 2) How the Client request was mapped to the Action file? Write the code and explain DynaActionForm in the struts-config.xml file. Add the following entry in the struts... in the struts-config.xml file...-config.xml file. So, it makes the FormBean declarative and this helps Java + struts - Struts += byteRead; } String file = new String(dataBytes); /** * Content-Disposition: form-data; name="file"; filename="D:\testing.xls...("===================file end========================"); */ String saveFile Form Bean - Struts Form Bean How type of Formbean's property defined in struts config.xml? EmployeeDetailsForm is form1...:// - Struts in struts 1.1 What changes should I make for this?also write struts-config.xml..., For read more information,Tutorials and Examples on Struts visit to : Thanks Understanding Struts Action Class Understanding Struts Action Class In this lesson I will show you how to use Struts Action...-config.xml file (action mapping is show later in this page). Here is validation using validator-rules.xml - Struts struts-config.xml... form using Validator-rules.xml. I am using Eclipse 3.0 Struts 1.1 and Tomcat...-INF I created an XML file and named it as validation.xml Here Struts Tutorials struts-config.xml file for an existing Struts application into multiple... to struts-config.xml file. Then, open an editor for the struts-config.xml file... of the struts-config.xml file. 4. Struts Application Wizard - Turns your existing project Tag: ; } Defining form Bean in struts-config.xml file : Add the following entry in the struts-config.xml file for Form Bean. <form... the Action Mapping in the struts-config.xml   Request[/DispatchAction] does not contain handler parameter named 'parameter'. This may be caused by whitespace in the label text. - Struts struts-config.xml file & three jsp pages but it shows the warning Request... be caused by whitespace in the label text. struts-config.xml... Struts File Upload Working Of DispatchAction Class Works So Struts - Struts Struts hi, I am new in struts concept.so, please explain example login application in struts web based application with source code . what are needed the jar file and to run in struts application ? please kindly Struts Forward Action Example an Action Class Developing the Action Mapping in the struts-config.xml... Struts Forward Action Example  ... about Struts ForwardAction (org.apache.struts.actions.ForwardAction STRUTS STRUTS Suppose if you write label message with in your JSP page. But that "add.title" key name was not added in ApplicationResources.properties file? What happens when you run that JSP? What error shows? If it is run Struts integration with EJB in JBOSS3.2 \deploy\kala.war\web-inf>edit struts-config.xml In the struts-config.xml file... Controller) Architecture. It is open source and free. Struts frame work... Enterprise level applications Struts provide its own Controller component The Simply MEPIS 3.4-3 RC3 has been released The Simply MEPIS 3.4-3 RC3 has been released It is hoped that SimplyMEPIS... party printer utilities. A missing hotplug file was reinstalled. This may help... to the plustek.conf file. The floppy driver is being loaded automatically, like in Difference between Struts and Spring is specified in Struts-config.xml file. It than creates an instance of this action...To know the difference between Struts and Spring, we must first explain... a framework to integrate OR mapping, JDBC etc. Apache Struts framework Struts Introduction to Struts 2 Framework Configuration In Struts 1 struts-config.xml is used for configuring the application. In Struts 2 struts.xml file is used for the application configuration. Controller In Struts 1 ActionServlet works Struts-It makes view and modify Struts-config.xml much easier and more quickly... Struts-It Struts-It is a set of Eclipse plugins for developing Struts-based web hint:theritacle dought in structs - Struts flow. The ActionServlet is responsbile for looking up the struts-config.xml file to identify the particular action class and instantiate it if necessary... and it definitely acts as a Controller in the MVC pattern as described Struts LookupDispatchAction Example ;Each ActionForward is defined in the struts-config.xml file (action mapping... in the action tag through struts-config.xml file). Then this matching key is mapped... to a property in the Struts Resource bundle file (ie Struts LookupDispatchAction Example ;Each ActionForward is defined in the struts-config.xml file (action mapping... in the action tag through struts-config.xml file). Then this matching key is mapped... to a property in the Struts Resource bundle file (ie..ApplicationResource.properties INTERNATIONALIZATION in the application.properties file index.info=STRUTS TUTORIAL. Now we have to add entry in the struts-config.xml file for all the properties files. The entry and its... introduction we shall see how to implement i18n in a Simple JSP file of Struts. g Struts Dispatch Action Example in the struts-config.xml file (action mapping is shown later in this page... Bean in struts-config.xml file Add the following entry in the struts...; Struts-Configuration file). Here the Dispatch_Action
http://roseindia.net/tutorialhelp/comment/846
CC-MAIN-2014-35
refinedweb
1,829
62.54
import gui def sayHello(): name = window.main.user_name gui.tell("Hello " + name + "!") </form> </body> </html> """ window = gui.show(windowHtml)Don't ask me how the namespaces work here - i'm BrainStorming! Oh, and gui.tell is a convenience method which pops up a dialogue box (or a little ordinary window) with some text in - inspired by HyperCard's AskAndAnswer?. This does require that users learn HTML before they learn python, but i don't think this is a huge problem - indeed, it might be good to get them to learn HTML first, as a 'zeroth language', since it's very simple, gives immediate positive feedback (web pages!), and is of quite a lot of practical value. -- TomAnderson Learn HTML before learning Python? Learn HTML before any programming language? Do you know how many people mislearn HTML? Do you know how many people write invalid HTML? Do you know how many people get the hang of separating content from presentation? HTML is not all that simple, and I do believe the world would be a slightly better place if people wrote better HTML. Besides, if you really want people using web pages for their UserInterface, you might as well start out teaching them JavaScript, not PythonLanguage. JavaScript isn't nearly as much fun or powerful as Python, but it is relatively easy and it automatically comes with the student's browser. No complicated installation or special libraries required. -- ElizabethWiethoff I am not sure what you are proposing and why learning HMTL first is a bad idea just because it may be hard. It is more practical if you ask me. As far as SeparateDomainFromPresentation, a lot of that mantra is malarky in my opinion. --top
http://c2.com/cgi/wiki?ComputerProgrammingForEverybody
CC-MAIN-2016-22
refinedweb
284
65.52
i have two projects, each is deployed as a jar inside of an ear. projecta.jar -> projecta.ear, projectb.jar -> projectb.ear. Both of the jar files are switchyard deployments, They use jms to endpoints to interact today, I'd like to convert to an SCA binding. is there anything I need to be aware of when referencing projectb.jar's components from projecta.jar? Is this possible? I had read some folks had class loading issues and needed to put the interface classes into a common module that was shared by both ear/jars files? Any thoughts would be most appreciated! Thanks! Yes shared interface/class should be exposed as a common library, otherwise possibly causes ClassCastException. One another thing I remember is about the namespace, I'd recommend to use different namespace for each SY application using SCA as SCA remote binding looks for the service with using namespace, otherwise possibly the SY applications using same namespace pollutes each other. Thanks! We got it working using this method.
https://developer.jboss.org/message/964488
CC-MAIN-2020-40
refinedweb
170
55.34
This guide is intended to help you get from an idea of fixing a bug or implementing a new feature into a nightly Scala build, and, ultimately, to a production release of Scala incorporating your idea. This guide covers the entire process, from the conception of your idea or bugfix to the point where it is merged into Scala. Throughout, we will use a running example of an idea or bugfix one might wish to contribute. Other good starting points for first-time contributors include the Scala README and contributor’s guidelines. The Running Example Let’s say that you particularly enjoy the new string interpolation language feature introduced in Scala 2.10.0, and you use it quite heavily. Though, there’s an annoying issue which you occasionally stumble upon: the formatting string interpolator f does not support new line tokens %n. One approach would be to go the mailing list, request that the bug be fixed, and then to wait indefinitely for the fix arrive. Another approach would be to instead patch Scala oneself, and to submit the fix to the Scala repository in hopes that it might make it into a subsequent release. Of note: There are several types of releases/builds. Nightly builds are produced every night at a fixed time. Minor releases happen once every few months. Major releases typically happen once per year. 1. Connect Sometimes it’s appealing to hack alone and not to have to interact with others out of fear, or out of comfort. However, in the context a big project such as Scala, this might not be the very best idea. There are people in the Scala community who have spent years accumulating knowledge about Scala libraries and internals. They might provide unique insights and, what’s even better, direct assistance in their areas, so it is not only advantageous, but recommended to communicate with the community about your new patch. Typically bug fixes and new features start out as an idea or an experiment posted on one of our mailing lists to find out how people feel about things you want to implement. People proficient in certain areas of Scala usually monitor mailing lists, so you’ll often get some help by simply posting a message. But the most efficient way to connect is to cc your message to one of the people responsible for maintaining the aspect of Scala which you wish to contribute to. A list of language features/libraries along with their maintainer’s full names and GitHub usernames is in the Scala repo README. In our running example, since Martin is the person who submitted the string interpolation Scala Improvement Proposal and implemented this language feature for Scala 2.10.0, he might be interested in learning of new bugfixes to that feature. As alluded to earlier, one must also choose an appropriate mailing list. Typically, one would use the Scala Contributors mailing list, as it is devoted to discussions about the core internal design and implementation of the Scala system. However, since this issue has been discussed previously on the scala-user mailing list, in this example, we post to the the scala-user mailing list about our issue. Now that we have the approval of the feature’s author, we can get to work! 2. Set up Hacking Scala begins with creating a branch for your work item. To develop Scala we use Git and GitHub. This section of the guide provides a short walkthrough, but if you are new to Git, it probably makes sense to familiarize yourself with Git first. We recommend - the Git Pro online book. - the help page on Forking a Git Repository. - this great training tool LearnGitBranching. One hour hands-on training helps more than 1000 hours reading. Fork Log into GitHub, go to and click the Fork button in the top right corner of the page. This will create your own copy of our repository that will serve as a scratchpad for your work. If you’re new to Git, don’t be afraid of messing up– there is no way you can corrupt our repository. Clone If everything went okay, you will be redirected to your own fork at, where username is your github user name. You might find it helpful to read, which covers some of the things that will follow below. Then, clone your repository (i.e. pull a copy from GitHub to your local machine) by running the following on the command line: 16:35 ~/Projects$ git clone Cloning into 'scala'... remote: Counting objects: 258564, done. remote: Compressing objects: 100% (58239/58239), done. remote: Total 258564 (delta 182155), reused 254094 (delta 178356) Receiving objects: 100% (258564/258564), 46.91 MiB | 700 KiB/s, done. Resolving deltas: 100% (182155/182155), done. This will create a local directory called scala, which contains a clone of your own copy of our repository. The changes that you make in this directory can be propagated back to your copy hosted on GitHub and, ultimately, pushed into Scala when your patch is ready. Branch Before you start making changes, always create your own branch. Never work on the master branch. Think of a name that describes the changes you plan on making. Use a prefix that describes the nature of your change. There are essentially two kinds of changes: bug fixes and new features. - For bug fixes, use issue/NNNNor ticket/NNNNfor bug NNNN from the Scala bug tracker. - For new feature use topic/XXXfor feature XXX. Use feature names that make sense in the context of the whole Scala project and not just to you personally. For example, if you work on diagrams in Scaladoc, use topic/scaladoc-diagramsinstead of just topic/diagramswould be a good branch name. Since in our example, we’re going to fix an existing bug 6725, we’ll create a branch named ticket/6725. 16:39 ~/Projects/scala (master)$ git checkout -b ticket/6725 Switched to a new branch 'ticket/6725' If you are new to Git and branching, read the Branching Chapter in the Git Pro book. Build The next step after cloning your fork is setting up your machine to build Scala. You need the following tools: - A Java SDK. The baseline version is 6 for 2.11.x and 8 for 2.12.x. It’s possible to use a later SDK for local development, but the continuous integration builds will verify against the baseline version. sbt, an interactive build tool commonly used in Scala projects. Acquiring sbt manually is not necessary – the recommended approach is to download the sbt-extras runner script and use it in place of sbt. The script will download and run the correct version of sbt when run from the Scala repository’s root directory. curl– the build uses curlin the pull-binary-libs.shscript to download bootstrap libs. OS X and Linux builds should work. Windows is supported, but it might have issues. Please report to the Scala bug tracker if you encounter any. Building Scala is as easy as running sbt dist/mkPack in the root of your cloned repository. In general, it’s much more efficient to enter the sbt shell once and run the various tasks from there, instead of running each task by launching sbt some-task on your command prompt. Be prepared to wait for a while – a full “clean” build takes 5+ minutes depending on your machine (longer on older machines with less memory). On a recent laptop, incremental builds usually complete within 10-30 seconds. IDE There’s no single editor of choice for working with Scala sources, as there are trade-offs associated with each available tool. Both Eclipse and IntelliJ IDEA have Scala plugins, which are known to work with our codebase. Both of those Scala plugins provide navigation, refactoring, error reporting functionality, and integrated debugging. See the Scala README for instructions on using Eclipse and IntelliJ IDEA with the Scala repository. There also exist lighter-weight editors such as Emacs, Sublime or jEdit which are faster and much less memory/compute-intensive to run, while lacking semantic services and debugging. To address this shortcoming, they can integrate with ENSIME, a helper program, which hosts a resident Scala compiler providing some of the features implemented in traditional IDEs. However despite having significantly matured over the last year, support for our particular code base is still being improved, and is not as mature as for Eclipse and IntelliJ. Due to the immense variability in personal preference between IDE/editor experience, it’s difficult to recommend a particular tool, and your choice should boil down to your personal preferences. 3. Hack When hacking on your topic of choice, you’ll be modifying Scala, compiling it and testing it on relevant input files. Typically you would want to first make sure that your changes work on a small example and afterwards verify that nothing break by running a comprehensive test suite. We’ll start by creating a sandbox directory ( ./sandbox is listed in the .gitignore of the Scala repository), which will hold a single test file and its compilation results. First, let’s make sure that the bug is indeed reproducible by putting together a simple test and compiling and running it with the Scala compiler that we built using sbt. The Scala compiler that we just built is located in build/pack/bin. 17:25 ~/Projects/scala (ticket/6725)$ mkdir sandbox 17:26 ~/Projects/scala (ticket/6725)$ cd sandbox 17:26 ~/Projects/scala/sandbox (ticket/6725)$ edit Test.scala 17:26 ~/Projects/scala/sandbox (ticket/6725)$ cat Test.scala object Test extends App { val a = 1 val s = f"$a%s%n$a%s" println(s) } 17:27 ~/Projects/scala/sandbox (ticket/6725)$ ../build/pack/bin/scalac Test.scala 17:28 ~/Projects/scala/sandbox (ticket/6725)$ ../build/pack/bin/scala Test 1%n1 // %n should've been replaced by a newline here Implement Now, implement your bugfix or new feature! Here are also some tips & tricks that have proven useful in Scala development: - After building your working copy with the compilesbt task, there’s no need to leave the comfort of your sbt shell to try it out: the REPL is available as the scalatask, and you can also run the compiler using the scalactask. If you prefer to run the REPL outside sbt, you can generate the scripts in build/quick/binusing the dist/mkQuicktask. - The sbt workflow is also great for debugging, as you can simply create a remote debugging session in your favorite IDE, and then activate the JVM options for the next time you run the scalaor scalactasks using: > set javaOptions in compiler := List("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8002") > scalac test.scala [info] Running scala.tools.nsc.Main -usejavacp test.scala Listening for transport dt_socket at address: 8002 - Also see the Scala README for tips on speeding up compile times. - If after introducing changes or updating your clone, you get AbstractMethodErroror other linkage exceptions, try the cleantask and building again. - Don’t underestimate the power of Trees, you might want to use showRawto get the ASTrepresentation. - You can publish your newly-built scala version locally using the publishLocaltask in sbt. - It’s convenient to enable the following local settings to speed up your workflow (put these in local.sbtin your working copy): // skip docs for local publishing publishArtifact in (Compile, packageDoc) in ThisBuild := false // set version based on current sha, so that you can easily consume this build from another sbt project baseVersionSuffix := s"local-${Process("tools/get-scala-commit-sha").lines.head.substring(0, 7)}" // show more logging during a partest run testOptions in IntegrationTest in LocalProject("test") ++= Seq(Tests.Argument("--show-log"), Tests.Argument("--show-diff")) // if incremental compilation is compiling too much (should be fine under sbt 0.13.13) // antStyle := true - Adding a macro to the Predefobject is a pretty involved task. Due to bootstrapping, you cannot just throw a macro into it. For this reason, the process is more involved. You might want to follow the way StringContext.fitself is added. In short, you need to define your macro under src/compiler/scala/tools/reflect/and provide no implementation in Predef( def fn = macro ???). Now you have to set up the wiring. Add the name of your macro to src/reflect/scala/reflect/internal/StdNames.scala, add the needed links to it to src/reflect/scala/reflect/internal/Definitions.scala, and finally specify the bindings in src/compiler/scala/tools/reflect/FastTrack.scala. Here’s an example of adding a macro. Documentation There are several areas that one could contribute to – there is the Scala library, the Scala compiler, and other tools such as Scaladoc. Each area has varying amounts of documentation. The Scala Library Contributing to the Scala standard library is about the same as working on one of your own libraries. Beyond the Scala collections hierarchy, there are no complex internals or architectures to have to worry about. Just make sure that you code in a “don’t-repeat-yourself” (DRY) style, obeying the “boy scout principle” (i.e. make sure you’ve left the code cleaner than you found it). If documentation is necessary for some trait/class/object/method/etc in the Scala standard library, typically maintainers will include inline comments describing their design decisions or rationale for implementing things the way they have, if it is not straightforward. If you intend on contributing to Scala collections, please make sure you’re familiar with the design of the Scala collections library. It can be easy to put an implementation in the wrong location if you are unfamiliar with the collections architecture. There is an excellent and very detailed guide covering the Architecture of Scala Collections, as well as a larger more general Scala collections Guide covering the sequential portion of collections. For parallel collections, there also exists a detailed Scala Parallel Collections Guide. The Scala Compiler Documentation about the internal workings of the Scala compiler is scarce, and most of the knowledge is passed around by email (Scala Contributors mailing list), ticket, or word of mouth. However the situation is steadily improving. Here are the resources that might help: - Compiler internals videos by Martin Odersky are quite dated, but still very useful. In this three-video series Martin explains the general architecture of the compiler, and the basics of the front-end, which has recently become Scala reflection API. - Reflection documentation describes fundamental data structures (like Trees, Symbols, and Types) that are used to represent Scala programs and operations defined on then. Since much of the compiler has been factored out and made accessible via the Reflection API, all of the fundamentals needed for reflection are the same for the compiler. - Reflection and Compilers by Martin Odersky, a talk at Lang.NEXT 2012 in which Martin elaborates on the design of scalac and the architecture of the reflection API. - Scala compiler corner contains extensive documentation about most of the post-typer phases (i.e. the backend) in the Scala compiler. - Scala Contributors, a mailing list which hosts discussions about the core internal design and implementation of the Scala system. Other Projects Tools like Scaladoc also welcome contributions. Unfortunately these smaller projects have less developer documentation. In these cases, the best thing to do is to directly explore the code base (which often contains documentation as inline comments) or to write to the appropriate maintainers for pointers. Interlude To fix the bug we’re interested in we’ve tracked the StringContext.f interpolator down to a macro implemented in MacroImplementations.scala There we notice that the interpolator only processes conversions, but not tokens like %n. Looks like an easy fix. 18:44 ~/Projects/scala/sandbox (ticket/6725)$ git diff diff --git a/src/compiler/scala/tools/reflect/MacroImplementations.scala b/src/compiler/scala/tools/ index 002a3fce82..4e8f02084d 100644 --- a/src/compiler/scala/tools/reflect/MacroImplementations.scala +++ b/src/compiler/scala/tools/reflect/MacroImplementations.scala @@ -117,7 +117,8 @@ abstract class MacroImplementations { if (!strIsEmpty) { val len = str.length while (idx < len) { - if (str(idx) == '%') { + def notPercentN = str(idx) != '%' || (idx + 1 < len && str(idx + 1) != 'n') + if (str(idx) == '%' && notPercentN) { bldr append (str substring (start, idx)) append "%%" start = idx + 1 } After applying the fix and running sbt compile, our simple test case in sandbox/Test.scala started working! 18:51 ~/Projects/scala/sandbox (ticket/6725)$ cd .. 18:51 ~/Projects/scala (ticket/6725)$ sbt compile ... [success] Total time: 18 s, completed Jun 6, 2016 9:03:02 PM Total time: 18 seconds 18:51 ~/Projects/scala (ticket/6725)$ cd sandbox 18:51 ~/Projects/scala/sandbox (ticket/6725)$ ../build/pack/bin/scalac Test.scala 18:51 ~/Projects/scala/sandbox (ticket/6725)$ ../build/pack/bin/scala Test 1 1 // no longer getting the %n here - it got transformed into a newline Test To guard your change against accidental breakage in the future, it is important to add tests. I have already written one test earlier, so that’s a good start but not enough! Apart from obvious usages of our new functionality, we need to cover corner-cases as well. Adding tests to the test suite is as easy as moving them to the appropriate directory: - Code which should compile successfully, but doesn’t need to be executed, needs to go into the “pos” directory. - Code which should not compile needs to go into the “neg” directory. - Code which should compile and get executed by the test suite needs to go into the “run” directory and have a corresponding .checkfile with the expected output. You will get test failures if the content of a .checkfile is different from what the test produces while running. If the change in the output is an expected product of your work, you might not want to change the .checkfile by hand. To make partest change the .checkfile, run it with a --update-checkflag, like so ./test/partest --update-check path/to/test.scala. For more information on partest, please refer to its documentation. - Everything that can be unit-tested should go to “junit” directory - Property-based tests go to the “scalacheck” directory Here are some more testing tips: - If you have several tests, and want a tool for only running tests that conform to some regular expression, you can use partest-ackin the toolsdirectory: ./tools/partest-ack "dottype". partest-ackwas removed in 2.12. - If you want to run all scalacheck tests from sbt use scalacheck/testOnly - To run scalacheck tests by name when in sbt use scalacheck/testOnly <test1> ... <testN>, for example scalacheck/testOnly scala.tools.nsc.scaladoc.HtmlFactoryTest If your tests fail in the following way: test.bc: [echo] Checking backward binary compatibility for scala-library (against 2.11.0) [mima] Found 2 binary incompatibiities [mima] ================================ [mima] * synthetic method [mima] scala$package$Class$method(java.lang.String)Unit in trait [mima] scala.package.Class does not have a correspondent in old version [mima] * synthetic method [mima] scala$package$AnotherClass$anotherMethod(java.lang.String)Unit in trait [mima] scala.package.AnotherClass does not have a correspondent in old version [mima] Generated filter config definition [mima] ================================== [mima] [mima] filter { [mima] problems=[ [mima] { [mima] matchName="scala.package.Class$method" [mima] problemName=MissingMethodProblem [mima] }, [mima] { [mima] matchName="scala.package.AnotherClass$anotherMethod" [mima] problemName=MissingMethodProblem [mima] } [mima] ] [mima] } [mima] ... Finished: FAILURE This means your change is backward or forward binary incompatible with the specified version (the check is performed by the migration manager). The error message is actually saying what you need to add to bincompat-backward.whitelist.conf or bincompat-forward.whitelist.conf to make the error go away. If you are getting this on an internal/experimental api, it should be safe to add suggested sections to the config. Otherwise, you might want to target a newer version of scala for this change. Verify Now to make sure that my fix doesn’t break anything I need to run the test suite. The Scala test suite uses JUnit and partest, a tool we wrote for testing Scala. Run sbt test and sbt partest to run all of the JUnit and partest tests, respectively. partest (not sbt partest) also allows you to run a subset of the tests using wildcards: 18:52 ~/Projects/scala/sandbox (ticket/6725)$ cd ../test 18:56 ~/Projects/scala/test (ticket/6725)$ partest files/run/*interpol* Testing individual files testing: [...]/files/run/interpolationArgs.scala [ OK ] testing: [...]/files/run/interpolationMultiline1.scala [ OK ] testing: [...]/files/run/interpolationMultiline2.scala [ OK ] testing: [...]/files/run/sm-interpolator.scala [ OK ] testing: [...]/files/run/interpolation.scala [ OK ] testing: [...]/files/run/stringinterpolation_macro-run.scala [ OK ] All of 6 tests were successful (elapsed time: 00:00:08) partest was removed in 2.12. 4. Publish After development is finished, it’s time to publish the code and submit your patch for discussion and potential inclusion into Scala. In a nutshell, this involves: - making sure that your code and commit messages are of high quality, - clicking a few buttons in the GitHub interface, - assigning one or more reviewers who will look through your pull request. Let’s go into each of these points in more detail. Commit The Git Basics chapter in the Git online book covers most of the basic workflow during this stage. There are two things you should know here: - Commit messages are often the only way to understand the intentions of authors of code written a few years ago. Thus, writing a quality is of utmost importance. The more context you provide for the change you’ve introduced, the larger the chance that some future maintainer understand your intentions. Consult the pull request policies for more information about the desired style of your commits. - Keeping Scala’s git history clean is also important. Therefore we won’t accept pull requests for bug fixes that have more than one commit. For features, it is okay to have several commits, but all tests need to pass after every single commit. To clean up your commit structure, you want to rewrite history using git rebaseso that your commits are against the latest revision of master. Once you are satisfied with your work, synced with master and cleaned up your commits you are ready to submit a patch to the central Scala repository. Before proceeding make sure you have pushed all of your local changes to your fork on GitHub. 19:22 ~/Projects/scala/test (ticket/6725)$ git add ../src/compiler/scala/tools/reflect/MacroImplementations.scala 19:22 ~/Projects/scala/test (ticket/6725)$ git commit [ticket/6725 3c3098693b] SI-6725 `f` interpolator now supports %n tokens 1 file changed, 2 insertions(+), 1 deletion(-) 19:34 ~/Projects/scala/test (ticket/6725)$ git push origin ticket/6725 Username for '': xeno-by Password for '': Counting objects: 15, done. Delta compression using up to 8 threads. Compressing objects: 100% (8/8), done. Writing objects: 100% (8/8), 1.00 KiB, done. Total 8 (delta 5), reused 0 (delta 0) To * [new branch] ticket/6725 -> ticket/6725 Submit Now, we must simply submit our proposed patch. Navigate to your branch in GitHub (for me it was) and click the pull request button to submit your patch as a pull request to Scala. If you’ve never submitted patches to Scala, you will need to sign the contributor license agreement, which can be done online within a few minutes. Review After the pull request has been submitted, you need to pick a reviewer (usually the person you’ve contacted in the beginning of your workflow) and be ready to elaborate and adjust your patch if necessary. In this example, we picked Martin, because we had such a nice chat on the mailing list: Merge After your reviewer is happy with your code (usually signaled by a LGTM — “Looks good to me”), your job is done. Note that there can be a gap between a successful review and the merge, because not every reviewer has merge rights. In that case, someone else from the team will pick up your pull request and merge it. So don’t be confused if your reviewer says “LGTM”, but your code doesn’t get merged immediately.
https://www.scala-lang.org/contribute/hacker-guide.html
CC-MAIN-2020-24
refinedweb
4,018
55.84
Proper XML Output in Python November 13, 2002 I planned to conclude my exploration of 4Suite this time, but events since last month's article led me to discuss some fundamental techniques for Python-XML processing first. First, I consider ways of producing XML output in Python, which might make you wonder what's wrong with good old Minding the Law The main problem with simple. We have a variety of tools and a language which allows us to express our intent very clearly. All we need is to take a suitable amount of care. Consider the snippet in Listing 1. It defines a function, write_xml_log_entry, for writing log file entries as little XML documents, using the Listing 1: Simple script to write XML log entries import time LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR'] def write_xml_log_entry(level, msg): #Note: in a real application, I would use ISO 8601 for the date #asctime used here for simplicity now = time.asctime(time.localtime()) params = {'level': LOG_LEVELS[level], 'date': now, 'msg': msg} print '<entry level="%(level)s" date="%(date)s"> \ \n%(msg)s\n</entry>' % params return write_xml_log_entry(0, "'Twas brillig and the slithy toves") #sleep one second #Space out the log messages just for fun time.sleep(1) write_xml_log_entry(1, "And as in uffish thought he stood,") time.sleep(1) write_xml_log_entry(0, "The vorpal blade went snicker snack") Listing 1 also includes a few lines to exercise the write_xml_log_entry function. All in all, this script is straightforward enough. The output looks like $ python listing1.py <entry level="DEBUG" date="Mon Oct 21 22:11:01 2002"> 'Twas brillig and the slithy toves </entry> <entry level="WARNING" date="Mon Oct 21 22:11:03 2002"> And as in uffish thought he stood, </entry> <entry level="DEBUG" date="Mon Oct 21 22:11:07 2002"> The vorpal blade went snicker snack </entry> But what if someone uses this function thus: >>> write_xml_log_entry(2, "In any triangle, each interior angle < 90 degrees") <entry level="ERROR" date="Tue Oct 22 05:41:31 2002"> In any triangle, each interior angle < 90 degrees </entry> Now the result isn't well-formed XML. The character "<" should, of course, have been escaped to "<". And there's a policy issue to consider. Are messages passed into the logging function merely strings of unescaped character data, or are they structured, markup-containing XML fragments? The latter policy might be prudent if you want to allow people to mark up log entries by, say, italicizing a portion of the message: >>> write_xml_log_entry(2, "Came no church of cut stone signed: <i>Adamo me fecit.</i>") <entry level="ERROR" date="Tue Oct 22 05:41:31 2002"> Came no church of cut stone signed: <i>Adamo me fecit.</i> </entry> I've reused the write_xml_log_entry function because msg-as-markup is the policy implied by the function as currently written. There are further policy issues to consider. In particular, to what XML vocabularies do you constrain output, if any? Allowing the user to pass markup often entails that they have the responsibility for passing in well-formed markup. The other approach, where the msg parameter is merely character data, usually entails that the write_xml_log_entry function will perform the escaping required to produce well-formed XML in the end. For this purpose I can use the escape utility function in the xml.sax.saxutils module. Listing 2 defines a function, write_xml_cdata_log_entry, which performs such escaping. Listing 2: Simple script to write XML log entries, with the policy that messages passed in are considered character data '<entry level="%(level)s" date="%(date)s"> \ \n%(msg)s\n</entry>' % params return This function is now a bit safer to use for arbitrary text. $ python -i listing2.py >>> write_xml_cdata_log_entry(2, "In any triangle, each interior angle < 90\260") <entry level="ERROR" date="Tue Oct 22 06:33:51 2002"> In any triangle, each interior angle < 90° </entry> >>> And it enforces the policy of no embedded markup in messages. >>> write_xml_cdata_log_entry(2, "Came no church of cut stone signed: <i>Adamo me fecit.</i>") <entry level="ERROR" date="Tue Oct 22 06:41:31 2002"> Came no church of cut stone signed: <i>Adamo me fecit.</i> </entry> >>> Notice that escape also escapes ">" characters, which is not required by XML in character data but is often preferred by users for congruity. Minding Your Character Python's regular strings are byte arrays. Characters are represented as one or more bytes each, depending on the encoding, but the string does not indicate which encoding was used. If it surprises you to hear that characters might be represented using more than one byte, consider Asian writing systems, where there are far more characters available than could be squeezed into the 255 a byte can represent. For this reason, some character encodings, such as UTF-8, use more than one byte to encode a single character. Other encodings, such as UTF-16 and UTF-32, effectively organize the byte sequence into groups of two or four bytes, each of which is the basic unit of the character encoding. Because most single-byte encodings, such as as ISO-8859-1, are identical in the ASCII byte range ( 0x00 to 0x7F), it's generally safe to use Python's strings if they contain only ASCII characters and you're using a single-byte encoding (other than the old IBM mainframe standard, EBCDIC, which is different from ASCII throughout its range). But in any case, especially if you put non-ASCII characters in one of these regular strings, both the sender and receiver of these bytes need to be in agreement about what encoding was used. The problems associated with encoded strings are easy to demonstrate. Consider one of the earlier examples, with a slight change -- the word "degrees" has been replaced with the byte B0 (octal 260), which is the degree symbol in the popular ISO-8859-1 and Windows-1252 character encodings: $ python -i listing2.py >>> write_xml_cdata_log_entry(2, "In any triangle, each interior angle < 90\260") <entry level="ERROR" date="Tue Oct 22 06:33:51 2002"> In any triangle, each interior angle < 90° </entry> >>> The \260 is an octal escape for characters in Python. It represents a byte of octal value 260 (B0 hex, 176 decimal). As for the output produced by write_xml_cdata_log_entry, the characters seem properly escaped, but there may still be a problem. If this output is to stand alone as an XML document, it's not be well-formed. The problem is that there is no XML declaration, so the character encoding is assumed by XML processors to be UTF-8. But the degree symbol at the end of the string makes it illegal UTF-8; an XML parser would signal an error. This is one of the most common symptoms of bad XML I have seen: documents encoded in ISO-8859-1 or some other encoding which are not marked as such in an XML declaration. Just adding an XML declaration is not necessarily a solution. If I have the function add "<?xml version="1.0" encoding="ISO-8859-1"?>" then the previous function invocation produces problem-free XML. But nothing prevents write_xml_cdata_log_entry from being passed a message in an encoding other than ISO-8859-1. Almost any sequence of bytes can be interpreted ISO-8859-1, so no error would be detected. But this is merely masking a deeper, more insidious problem: the text would be completely misinterpreted. To illustrate this specious fix, Listing 3 forces an ISO-8859-1 XML declaration. Listing 3: a variation on write_xml_cdata_log_entry which always puts out an ISO-8859-1 XML declaration '<?xml version="1.0" encoding="ISO-8859-1"?>' print '<entry level="%(level)s" date="%(date)s"> \ \n%(msg)s\n</entry>' % params return To understand the nastiness that lurks within this seeming fix, take the case where a user passes in a string with a UTF-8 sequence with a Japanese message, which translates to "Welcome" in English. $ python -i listing2.py >>> write_xml_cdata_log_entry(2, "\343\202\210\343\201\206\343\201\223\343\201\235") <?xml version="1.0" encoding="ISO-8859-1"?> <entry level="ERROR" date="Tue Oct 22 15:54:36 2002"> よãfl†ãfl“ãfl? </entry> >>> An XML parser would accept this with no complaint. The problem is that any processing tools looking at this XML would read the individual sequences of the UTF-8 encoding as separate ISO-8859-1 characters. Which means they would see twelve characters, rather than the four which our imaginary Japanese user thought she had specified. Even worse, unless this text is displayed in a system localized for Japanese, it will come out as a mess of accented "a"s and other strange characters, rather than the dignified Japanese welcome intended by the user, illustrated in Figure 1. Figure 1: A Japanese Welcome Character encoding issues are a very tricky business, and you should always defer to the tools that your language and operating environment provide for such magic, if for no other reason than to pass the buck when something goes wrong. In Python's case, this means using the Unicode facilities available in Python 1.6 and 2.x (although I still highly recommend Python 2.2 or more recent for XML processing). In fact, I use and strongly encourage the following rule for XML processing in Python: In all public APIs for XML processing, character data should be passed in strictly as Python Unicode objects. In fact, I encourage that all use of strings in programs that process XML should be in the form of Unicode objects, but following the above rule alone will prevent a lot of problems. Listing 4 updates write_xml_cdata_log_entry to follow this rule. Listing 4: a variation on write_xml_cdata_log_entry which strictly accepts Python Unicode objects for message text. import time, types from xml.sax import saxutils LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR'] def write_xml_cdata_log_entry(level, msg): if not isinstance(msg, types.UnicodeType): raise TypeError("XML character data must be passed in as a unicode object") now = time.asctime(time.localtime()) encoded_msg = saxutils.escape(msg).encode('UTF-8') params = {'level': LOG_LEVELS[level], 'date': now, 'msg': encoded_msg} print '<entry level="%(level)s" date="%(date)s"> \ \n%(msg)s\n</entry>' % params return Pay particular attention to the line encoded_msg = saxutils.escape(msg).encode('UTF-8') Not only does this line escape characters that are illegal in XML character data, but it also encodes the Unicode object as a UTF-8 byte string. This is needed because most output, including printing to consoles and writing to files on most operating systems, requires conversion to byte streams. This means using an 8-bit encoding for strings that were originally in Unicode (because of my suggested rule). The write_xml_cdata_log_entry function always uses UTF-8 for this output encoding, which means that it doesn't have to put out an XML declaration that specifies an encoding. I should point out that in general it's considered good practice to always use an XML declaration which specifies an encoding, but I wrote the function this way as an illustration. This version of the write_xml_cdata_log_entry function is safe as far as character encodings are concerned. It doesn't care whether the character data came from an ISO-8859-1 string, a UTF-8 string, or any other form of string, as long as it is passed in as a Unicode object. $ python -i listing4.py >>> write_xml_cdata_log_entry(2, "In any triangle, each interior angle < 90\260") Traceback (most recent call last): File "<stdin>", line 1, in ? File "listing4.py", line 8, in write_xml_cdata_log_entry raise TypeError("XML character data must be passed in as a unicode object") TypeError: XML character data must be passed in as a unicode object This exception is as expected. We passed in a plain byte string rather than a Unicode object and the function is enforcing policy. >>> write_xml_cdata_log_entry(2, u"In any triangle, each interior angle < 90\u00B0") <entry level="ERROR" date="Tue Oct 22 17:58:08 2002"> In any triangle, each interior angle < 90° </entry> The log message unicode object includes a character, \u00B0 in the Python notation for explicitly representing a Unicode code point. A code point is a number that uniquely identifies one of the many characters Unicode defines. Here, of course, the code point represents the degree symbol. In this case, it would also be correct to use the regular octal escape character \260, but I recommend using the "\u" form of escape in Python Unicode objects. Be wary of using the position of the character you want in your local encoding as the Unicode code point. For example, on Macs predating OS X, the 176th character is the infinity symbol ( "\u221E"/), rather than the degree symbol. The function outputs the single degree character as a two-byte UTF-8 sequence. Since my console thinks it is displaying ISO-8859-1, the bytes appear to be separate characters, but an XML processor would properly read the sequence as a single character. >>> #The following two lines are equivalent >>> msg = unicode("\343\202\210\343\201\206\343\201\223\343\201\235", "UTF-8") >>> よãfl†ãfl“ãfl? </entry> First, I create a Unicode object from the UTF-8-encoded string, and then pass it to the function, which outputs it as UTF-8. This is no longer a problem because the parser will recognize the encoding as UTF-8, rather than confusing it as ISO-8859-1, as before. Not Quite There Yet But this function is still not failsafe. A remaining problem is that XML only allows a limited set of characters to be present in markup. For example, the form feed character is illegal. There is nothing in our function to prevent a user from inserting a form feed character, which would result in malformed XML. There are other subtleties to consider. Users of 4Suite have handy functions that take care of most of the concerns surrounding the output of XML character data. The one of most interest in this discussion is Ft.Xml.Lib.String.TranslateCdata. Listing 5 is a version of write_xml_cdata_log_entry that uses TranslateCdata to render character data as well-formed XML. Listing 5: a variation on write_xml_cdata_log_entry which uses Ft.Xml.Lib.String.TranslateCdata from 4Suite for safer XML outout. import time, types from xml.sax import saxutils from Ft.Xml.Lib.String import TranslateCdata LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR'] def write_xml_cdata_log_entry(level, msg): if not isinstance(msg, types.UnicodeType): raise TypeError("XML character data must be passed in as a unicode object") #Note: in a real application, I would use ISO 8601 for the date #asctime used here for simplicity now = time.asctime(time.localtime()) encoded_msg = TranslateCdata(msg) params = {'level': LOG_LEVELS[level], 'date': now, 'msg': encoded_msg} print '<entry level="%(level)s" date="%(date)s"> \ \n%(msg)s\n</entry>'% params return The key bit is now encoded_msg = TranslateCdata(msg). Which uses the 4Suite function. This takes care of the escaping, the character encoding, trapping illegal XML characters, and more. 4Suite also provides functions that prepare character data to be output inside an XML attribute or for HTML output. But just to put another twist on the matter, even now the 4Suite developers are refining these functions for better design, and the signatures may change in future releases. Since in many cases you have a special task to fulfill, and don't want to bear all the burden of XML correctness, this reinforces the importance of relying on third-party tools. Conclusion So much for the notion that XML output is nothing more than an exercise for the Python Thanks to Mike Brown,an expert on the intersection of XML and character set arcana. He reviewed this article for technical correctness and suggested important clarifications. Python-XML Happenings Here is a brief on significant new happenings relevant to Python-XML development, including significant software releases. Not much to report this month. Walter Dörwald announced version 2.0 of XIST, an XML-based extensible HTML generator written in Python. The announcement also led to sime discussion of the use of namespaces in XIST, leading to this clarification. Henry Thompson appears to have responded to my teasing about the lack of distutils in XSV with a new release.
http://www.xml.com/pub/a/2002/11/13/py-xml.html
CC-MAIN-2017-43
refinedweb
2,702
51.99
Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also #include <unistd.h> int truncate(const char *path, off_t length); int ftruncate(int fildes, off_t. The application must ensure that the process has write permission for the file. This function does not modify the file offset for any open file descriptions associated with the file. The ftruncate() function causes the regular file referenced by fildes to be truncated to length. If the size of the file previously exceeded length, the extra data is no longer available to reads on the file. If the file previously was smaller than this size, ftruncate() increases the size of the file with the extended area appearing as if it were zero-filled. The value of the seek pointer is not modified by a call to ftruncate(). The ftruncate() function works only with regular files and shared memory. If fildes refers to a shared memory object, ftruncate() sets the size of the shared memory object to length. If fildes refers to a directory or is not a valid file descriptor open for writing, ftruncate() fails. If the effect of ftruncate() is to decrease the size of a shared memory object or memory mapped file and whole pages beyond the new end were previously mapped, then the whole pages beyond the new end shall be discarded. If the effect of ftruncate() is to increase the size of a shared memory object, it is unspecified if the contents of any mapped pages between the old end-of-file and the new are flushed to the underlying object. are left unchanged. If the request would cause the file size to exceed the soft file size limit for the process, the request will fail and a SIGXFSZ signal will be generated for the process. Upon successful completion, ftruncate() and truncate() return 0. Otherwise, -1 is returned and errno is set to indicate the error. The ftruncate() and truncate() functions will fail if: A signal was caught during execution. The length argument was less than 0. The length argument was greater than the maximum file size. An I/O error occurred while reading from or writing to a file system. The named file resides on a read-only file system. The truncate() function will fail if: A component of the path prefix denies search permission, or write permission is denied on the file. The path argument points outside the process' allocated address space. The path argument is not an ordinary file. The named file is a directory. Too many symbolic links were encountered in resolving path. The maximum number of file descriptors available to the process has been reached. The length of the specified pathname exceeds {PATH_MAX} bytes, or the length of a component of the pathname exceeds {NAME_MAX} bytes. A component of path does not name an existing file or path is an empty string. Additional space could not be allocated for the system file table. A component of the path prefix of path is not a directory. The path argument points to a remote machine and the link to that machine is no longer active. The ftruncate() function will fail if: The file exists, mandatory file/record locking is set, and there are outstanding record locks on the file (see chmod(2)). The fildes argument is not a file descriptor open for writing. The file is a regular file and length is greater than the offset maximum established in the open file description associated with fildes. The fildes argument references a file that was opened without write permission. The fildes argument does not correspond to an ordinary file. The fildes argument points to a remote machine and the link to that machine is no longer active. The truncate() function may fail if: Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. The truncate() and ftruncate() functions have transitional interfaces for 64-bit file offsets. See lf64(5). See attributes(5) for descriptions of the following attributes: chmod(2), fcntl(2), open(2), attributes(5), lf64(5), standards(5) Name | Synopsis | Description | Return Values | Errors | Usage | Attributes | See Also
http://docs.oracle.com/cd/E19253-01/816-5168/ftruncate-3c/index.html
CC-MAIN-2014-35
refinedweb
685
63.8
There is always that moment a user ends up on a page that doesn't exist. So let's see how we can make these pages stand out more by adding our pages for each error page. Creating a 404 page in Next.js Let's start with the most common one, the 404 page. This one often occurs if the users end up on a page that no longer exists or make a typo in the URL. Let's try to find a random page called /does-not-exist and see what happens: So we get the above error because we said fallback is true for the getStaticPaths function. That means it should always try to resolve the page even if it can't find the static props. To fix this, we can set the fallback to false like this, which will redirect to a 404 if it can't resolve. export async function getStaticPaths() { const pagesWithSlugs = await getAllPagesWithSlugs(); return { paths: pagesWithSlugs.edges.map(({node}) => `/${node.slug}`) || [], fallback: false, }; } To create the 404 page we can create a page called 404.js in our pages directory. export default function Custom404() { return ( <div className="flex items-center justify-center h-screen mx-2 my-2 overflow-hidden "> <div className="px-6 py-4 rounded shadow-lg"> <div className="mb-2 text-xl font-bold"> 404 - Sorry could not find this page 😅 </div> </div> </div> ); } And now, when reloading the page, we should see the following page. 500 error page in Next.js Sometimes there might be something else wrong, and our website might throw a 500 error. We can create a custom error page for those pages as well. Create a file called 500.js in your pages directory. export default function Custom500() { return ( <div className="flex items-center justify-center h-screen mx-2 my-2 overflow-hidden "> <div className="px-6 py-4 rounded shadow-lg"> <div className="mb-2 text-xl font-bold">500 - Server error 😭</div> </div> </div> ); } This is the basic approach to having custom error pages in Next.js. As always, you can find the complete code on GitHub. Thank you for reading, and let's connect! Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/dailydevtips1/custom-error-pages-in-next-js-31ga
CC-MAIN-2021-49
refinedweb
385
72.87
General Information Submitted and accepted application: GCTuningApplication Student: LaurynasBiveinis Mentor: Daniel Berlin Status Reports Please make corrections if you see mistakes here! How to Add New Garbage Collector to GCC Add new case to the gcc/configure.ac. For example, Index: gcc/configure.ac =================================================================== --- gcc/configure.ac (revision 113493) +++ gcc/configure.ac (working copy) @@ -3213,9 +3213,12 @@ # Find out what GC implementation we want, or may, use. AC_ARG_WITH(gc, -[ --with-gc={page,zone} choose the garbage collection mechanism to use +[ --with-gc={boehm,page,zone} choose the garbage collection mechanism to use with the compiler], [case "$withval" in + boehm) + GGC=ggc-$withval + ;; page) GGC=ggc-$withval ;; Create a new file in gcc subdirectory named after the configure option, in this case ggc-boehm.c. Implement at least following functions (currently the parameter names might be not enough descriptive): void * ggc_alloc_stat (size_t size MEM_STAT_DECL) - Allocate a chunk of memory of SIZE bytes. Its contents are undefined. void ggc_collect (void) - Invoke the collector. Garbage collection occurs only when this function is called, not during allocations. void ggc_free (void * block) size_t ggc_get_size (const void * block) - Return the number of bytes allocated at the indicated address. int ggc_marked_p (const void * d) char * ggc_pch_alloc_object (struct ggc_pch_data * d, void * p, size_t s, bool b, enum gt_types_enum t) void ggc_pch_count_object (struct ggc_pch_data * d, void * p, size_t s, bool b, enum gt_types_enum t) void ggc_pch_finish (struct ggc_pch_data * d, FILE * f) void ggc_pch_read (FILE * f, void * p) void ggc_pch_this_base (struct ggc_pch_data * d, void * p) void ggc_pch_prepare_write (struct ggc_pch_data * d, FILE * f) size_t ggc_pch_total_size (struct ggc_pch_data * d) void ggc_pch_write_object (struct ggc_pch_data * d, FILE * f, void * p1, void * p2, size_t s, bool b) void ggc_print_statistics (void) int ggc_set_mark (const void * block) void init_ggc (void) - initialize the garbage collector. struct ggc_pch_data * init_ggc_pch (void) Add rules for building the new file to gcc/Makefile.in. When to collect? void init_ggc_heuristics (void) { #if !defined ENABLE_GC_CHECKING && !defined ENABLE_GC_ALWAYS_COLLECT set_param_value ("ggc-min-expand", ggc_min_expand_heuristic()); set_param_value ("ggc-min-heapsize", ggc_min_heapsize_heuristic()); #endif } So any time both "gc" and "gcac" checking are turned off we alter the heuristic so that GCC probes the system's RAM and uses more memory before collecting. When either of those checking styles are turned on (as is the case on mainline where "gc" is on) then we default to smaller values that simulate a machine with less RAM (32MB IIRC) and collect more often. In practice this has uncovered collection bugs more reliably. Developers often have boxes with lots of RAM and their patches would get tested in situations where no collection was done. Then when the patch was installed on mainline someone would see a problem on a small RAM machine. With everyone pretending they have small RAM boxes, developers more often catch GC errors before installing anything. Anyway, the lower parameters are set with checking on to: GGC heuristics: --param ggc-min-expand=30 --param ggc-min-heapsize=4096 You can see this by compiling an actual file with -v. By that I mean you have to invoke cc1, not just run "gcc -v" without an input file. You can add these --params flags to a --disable-checking bootstrap to restore collection behavior to that found in a checking compiler. With checking turned off then the parameters depend on the machine's configuration. For example on my box with --disable-checking I see: GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 - -Kaveh R. Ghazi GTY Documentation Notes Following if_marked arguments are actually used in GCC sources: ggc_marked_p() - checks if given object is already marked. tree_map_marked_p(), tree_int_map_marked_p(), type_hash_marked_p() - these all contain optimizations for special cases. PCH Notes All you should need to do to support PCH is implement the ggc_pch_* routines, specified and declared in ggc.h, for your garbage collector. Only ggc_pch_write_object actually requires you to do something, everything else is to help your implementation know what's going on. For performance, it is necessary that you don't write too many objects in the PCH file (and so freeing and re-using them is a bad idea). You need to be able to mark the pointers placed in objects read from a PCH as they may refer to newly-allocated memory. - - Geoffrey Keating Random GGC (short for GCC GC) Notes - Previous experiments with copying collector: The existing collectors (and pseudocollectors) are: ggc-none, used by GCC build-time generators, provides no GC at all; ggc-page is the default bag-of-pages collector; and ggc-zone, that is a bag-of-pages collector with allocations segregated into separate zones - If we do a copying collector, then it's impossible to have a conservative collector. Everything is either a pointer or not with 100% confidence, as we must adjust pointer values when we move objects around. This might be possible to do with current PCH annotation for data structures. - Boehm's GC, although has generational features, is not a copying collector. - Preference of copying vs. non-copying collector is unclear without performance measurements. To debug prematurely collected GCC objects use The registered roots from non-managed heap memory are marked by ggc_mark_roots() in ggc-common.c. Roots are registered by gengtype during build. A header file for each frontend is generated containing the master array of roots, e.g. gtype-c.h. Roots are grouped by per-file basis, e.g. the generated gt-varasm.h root information from varasm.c. Every variable with a GTY marker is considered to be a GC root. - There are several additional GC root lists: gt_ggc_rtab - list of ordinary roots gt_ggc_deletable_rtab - list of pointers that can be cleared on every collection. TODO: how this is different from gt_ggc_cache_rtab ? gt_ggc_cache_rtab - list of pointers in cache hash tables. These should be treated as weak pointers for marking purposes. gt_pch_cache_rtab - TODO: PCH, not interesting for now? gt_pch_scalar_rtab - TODO PCH, not interesting for now list of roots pointing to scalar values? At least one exception to the scheme above is the identifier table. Marking of the trees that are associated with identifiers is started by hand, not by GTY stuff, see gcc_mark_stringpool in stringpool.c. Collection is possible only on gc_collect() calls and not possible on allocation. Some parts of the compiler allocate objects with GC that do not path from root to them and expect them to stay alive until the next gc_collect() call.
http://gcc.gnu.org/wiki/Garbage_collection_tuning%3Faction=show&redirect=Garbage+collection+tuning
crawl-002
refinedweb
1,051
53.81
Hi all, This is a very simple program I wrote to test joystick responses but for some reason it won't work. The error message I get is: Assertion failed: sysdrv, file allegro-git\src\joynu.c, line 49. Any thoughts? Here's the code: (also attached for your convenience) #include<allegro5/allegro.h>#include<allegro5/allegro_primitives.h>#include<iostream>using namespace std;ALLEGRO_EVENT_QUEUE* event_queue; void render(){ cout << endl;} int main(){ if(!(al_install_joystick())) cout << "Couldn't install joystick." << endl; event_queue = al_create_event_queue(); if(!event_queue) cout << "al_create_event_queue failed." << endl; al_register_event_source(event_queue, al_get_joystick_event_source()); ALLEGRO_JOYSTICK* joy = al_get_joystick(0); ALLEGRO_JOYSTICK_STATE jst; ALLEGRO_EVENT event; while(true) { if (al_is_event_queue_empty(event_queue)) render(); al_wait_for_event(event_queue, &event); switch (event.type) { case ALLEGRO_EVENT_JOYSTICK_AXIS: al_get_joystick_state(joy, &jst); if(jst.stick[0].axis[0]) cout << jst.stick[0].axis[0] << endl; if(jst.stick[0].axis[1]) cout << jst.stick[0].axis[1] << endl; break; case ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN: al_get_joystick_state(joy, &jst); if (jst.button[0]) cout << "Button 0 pressed" << endl; if (jst.button[1]) cout << "Button 1 pressed" << endl; if (jst.button[9]) cout << "Button 9 pressed" << endl; break; case ALLEGRO_EVENT_JOYSTICK_BUTTON_UP: cout << endl; break; } } return 0;} You must call al_init before initializing anything else. And you can use <code>code goes here...</code> tags for_init(), of course. Duh. I'll give 'er a shot. Thank you! Another helpful tip is that generally you don't want to use the joystick state if you are using events. The event will tell you which axis and which stick and the state of the buttons depending on the event. Otherwise you can assume the state didn't change if you didn't get any events. So it might make sense to get it once when it is at neutral to calibrate the joystick. Getting the following error message (though it compiles fine): Unhandled exception at 0x77764c16 in shell.exe: 0xC0000005: Access violation reading location 0x00000000. The compiler is pointing to the line timer = al_create_timer(1.0/60).Any thoughts?Could it be possible that I'm getting this error because I'm running Allegro 5.0.10 and VC++2010 on Windows 8.1 64-bit edition? It is null (0x00000000) because you called al_create_timer before you called al_init. You can't create a timer until you initialize allegro. Now I'm getting this: Assertion failed: queue, file allegro-git\src\events.c, line 333 Debug Error! Program: C:\MyPrograms\shell\Debug\shell.exe] R6010-abort() has been called In line 36 you declare local ALLEGRO_EVENT_QUEUE *event_queue = NULL; which overrides global event_queue, and all further code tries to use that one. Of course, it's not initialized, and everything crashes on the first attempt to access it (in al_wait_for_event(event_queue, &ev), most probably). Thanks for your help guys! My code is working now and I am happy. :-)
https://www.allegro.cc/forums/thread/615211/1011548
CC-MAIN-2018-34
refinedweb
460
61.43
Introduction The turtle module is a part of the standard Python installation which provides a drawing board so that we can draw all over it using turtle methods. It is a popular way of introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert, and Cynthia Solomon in 1967. Python’s turtle module lets us control a small image shaped like a turtle, just like a video game character. We need to give precise instructions to direct the turtle around the screen. Because the turtle leaves a trail wherever it goes, we can use it to write a program that draws different shapes. Python Turtle Methods Let us begin to understand turtle methods with the following examples. import turtle module import turtle as tt For convenience, I have imported the turtle module as ‘tt’ throughout the examples. Example 1: Moving turtle # importing turtle module import turtle as tt tt.forward(100) Above we use the forward function to move the turtle 100px forward while leaving a trail behind it. When we run the program we will see something like this output. Output We will be noticing that the window screen automatically fades out as it drew a 100px arrow sign. To run the program until we exit we have to update the above code as. Updated code # importing turtle module import turtle as tt tt.forward(100) # to keep screen holding tt.getscreen()._root.mainloop() Example 2: Creating a square shape import turtle as tt # change the shape of the default # arrow to turtle shape('turtle') for i in range(4): tt.forward(100) # change turtle direction # at angle 90 clockwise tt.right(90) tt.getscreen()._root.mainloop() In the above example, we have used the loop in the range of 4 to move the turtle 4 times in four different directions at 90º clockwise. As we already know forward functions move the turtle, we have to use the right function to change directions. right(): turns the turtle clockwise left(): turns the turtle counterclockwise shape(): changes the shape of the default arrow. Initially, there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic” Output Example 3: Creating a circle of squares # import turtle import turtle as tt def make_circle(sidelength): """ Draw circle from 30 consecutive squares each bent at 10° in clockwise directions. """ for i in range(30): for j in range(4): tt.forward(sidelength) tt.right(90) tt.right(10) # calling function make_circle(100) tt.getscreen()._root.mainloop() Output Example 4: Creating a red flower Before beginning with the code, let us review some functions. setheading(to_angle): This function sets the orientation of the turtle pointer to to_angle. Shortly we can call this function seth(to_angel) like seth(15), seth(50). color(color_name): Changes the color of the turtle’s pen circle(radius, extent=None, steps=None): Draw a circle with a given radius. Other parameters extend and steps we can use from modification of circle. # import turtle module import turtle as tt tt.shape('turtle') # Changes turtle’s pen to # color 'red' tt.color("red") for angle in range(0, 360, 15): tt.seth(angle) tt.circle(50) tt.getscreen()._root.mainloop() Output Example 5: Creating star import turtle as tt for i in range(5): tt.forward(100) tt.right(144) tt.getscreen()._root.mainloop() Output
https://pythonsansar.com/understanding-python-turtle-methods-examples/
CC-MAIN-2022-27
refinedweb
561
55.54
Reviving an old thread about the following construct. foo = mumble if COND foo = blurgle endif Tom> I've long thought that we should, eventually, support the Tom> latter use. It seems to have a clearly defined meaning. Tom> And it is even useful in some situations. For instance, Tom> suppose in a very large project you want to `include' some Tom> boilerplate. Then you might conditionally override some Tom> value or another in a particular Makefile.am. I think we have three choices: 1. Like with "standard" Makefile assignments, the second definition of `foo' overrides the first one. So `foo' is undefined when COND is false. 2. The second definition of `foo' _partially_ overrides the first one. Yielding a definition equivalent to if COND foo = blurgle else foo = mumble endif 3. This construct is ill-formed and should be diagnosed. #3 is what Automake 1.7 assumes; it seems you want #2; and #1 doesn't make any sense (just consider if COND a = A else a = B endif ). Let's consider another snippet. if COND1 foo = mumble else foo = mumble endif if COND2 foo = blurgle endif At a first glance, this looks equivalent to the previous construct. However Automake 1.7 isn't aware of this and produces the following Makefile fragment, without the slightest warning: @address@hidden = blurgle @address@hidden = mumble @address@hidden = mumble (The order of definitions in the output doesn't match the order of definitions in the input, because Automake doesn't keep track of this sort of things.) IMO this is a bug. Either we should diagnose an error (#3), or we should produce something sensible (#2). If we take road #2, then the third `foo' definition should partially override previous definitions of `foo', in the COND2 condition; as if the user had written if COND2 foo = blurgle else if COND1 foo = mumble else foo = mumble endif endif This seems to suggest a way to implement #2 easily. When defining a variable in condition `COND', append `!COND' to all previous definitions' conditions. This also works for things like foo = mumble foo = blurgle which would be interpreted as foo = blurgle if FALSE foo = mumble endif Something that I don't know how to handle is the tracking of location for variables whose conditions have been changed as a side effect of a redefinition. It will be confusing if Automake diagnoses something about a variable `defined in condition COND1_TRUE COND2_FALSE' and then point the user to the place where the variable was simply defined in COND1_TRUE (should we explain that COND2_FALSE was added because the variable was later redefined in COND2_TRUE? how?) Another question is when should this construct be allowed? I agree #2 is useful when the definitions and redefinitions are in different files. IMO #3 would be helpful when the (re)definitions are in the same file. I can't think of any reason why a variable would be redefined in the same file, except user's inattention. Opinions? -- Alexandre Duret-Lutz
http://lists.gnu.org/archive/html/automake/2002-10/msg00018.html
CC-MAIN-2016-18
refinedweb
498
63.09
Do you know how i make my own "Provision" Mission like: 1. changing the planes from C-130 to AN-2 for example. 2. changing sides from UN to Russia for example and hostiles. Do you know how i make my own "Provision" Mission like: 1. changing the planes from C-130 to AN-2 for example. 2. changing sides from UN to Russia for example and hostiles. Whats a Provision" mission ?! Have I been out of the loop for too long not to know, lol I have searched the forums, Google, MSN, garage, shed, car, pockets, kitchen draws, pants, socks, down the sofa, under the bed, behind the Monitor, ashtray, belly button, cupboards, under cups, down the toilet, under the carpet, behind curtains, in Duvet cover, Wardrobe, inside the DVD player, searched the dog basket, "don't have a dog basket but I would have if I'd had one, and cannot find the answer to my question. So here I am, on my hands and knees, begging for someone to have the answer to the question I may have posed above. KonI™ I think he means cargo drop? You using the Simple Support Module (SSM) in the editor? I think you put this in the init: missionnamespace setvariable ["BIS_SSM_AmmoDrop_VEHICLE_EAST","An2_TK_EP1"]; missionnamespace setvariable ["BIS_SSM_AmmoDrop_BOX_EAST",["RUBasicAmmunitionBox","RUBasicWeaponsBox"]]; changes aircraft and ammo for East forces Last edited by PELHAM; Mar 20 2012 at 01:43. In the PMC single missions and tample mission editor, there's a mission called P03:"Provision". You Start as C-130 Pilot and drop the supllies and then when you RTB, the player changes to UN officer with his soldiers to take those supllies to thier truck. I want to change the C-130 to IL-76 or AN-2 for example and change the UN group to Russian Group and UN ural to Russian truck. The paradrop/cargo drop you spawn objects/ammo boxes below the aircraft with a script run from an addAction then attach parachutes to them. You can put a trigger on the ground to check if they land in the right place. Look at these for examples, they are AI pilots but it's essentially the same thing; Your trigger condition to check if all the objects land in the right place would be something like this (untested): Or you could just check 'vehicle player' is in the trigger area and the drop script is activated, variable set true in script.Or you could just check 'vehicle player' is in the trigger area and the drop script is activated, variable set true in script.Code:{getpos _x select 2} count [obj1,obj2,obj3,obj4] <= 1 I think they would switch to a different character with Team Switch or if the pilot is already a UN officer they addition squad members would be added with: Last edited by PELHAM; Mar 20 2012 at 13:51.
http://forums.bistudio.com/showthread.php?132604-custom-quot-Provision-quot-Mission
CC-MAIN-2013-20
refinedweb
483
65.15
site enables you to point to a single terminal server or to a single terminal server farm to populate the list of RemoteApp programs that appear on the site. If you have multiple terminal servers or multiple terminal server farms, you can use Windows® SharePoint® Services to create a single Web access point for RemoteApp programs and full terminal server desktop connections that are available on different terminal servers. You can customize a Windows SharePoint Services site by adding multiple console tree, right-click Features, and then click Add Features. On the Select Features page, expand .NET Framework 3.0 Features. Select the .Net Framework 3.0 check box, and then click Next. Click Install. On the Installation Results page, verify that the installation succeeded, and then click Close. Close Správce serveru. To install Windows SharePoint Services on a Windows Server 2008-based computer, the required version is Windows SharePoint Services 3.0 with Service Pack 1 (SP1). You cannot install Windows SharePoint Services 3.0 without SP1 on a Windows Server 2008-based computer. Download Windows SharePoint Services 3.0 with SP1. To download the software, visit either of the following Web sites, depending on your operating system version: On the Download Center page, click Download. In the File Download - Security Warning dialog box, click Run to start the installation, or click Save to run the installation later. In the Internet Explorer - Security Warning dialog box, click Run to continue with the installation. On the Read the Microsoft Software License Terms page, review the terms of the agreement. If you accept the terms, select the I accept the terms of this agreement check box, and then click Continue. On the Choose the installation you want page, click Basic to install to the default location. (To install to a different location, click Advanced, specify the location that you want to install to on the Data Location tab, and then click Install Now.) When Setup finishes, a dialog box prompts you to complete the configuration of your server. Ensure that the Run the SharePoint Products and Technologies Configuration Wizard now check box is selected, and then click Close to continue. The SharePoint Products and Technologies Configuration Wizard starts.. As a security measure, Windows SharePoint Services requires that you register the Webový přístup k TS Web Part's assembly and namespace as a Safe Control in the Web.config file of the server. The following procedure shows how to register the Web Part's assembly as a Safe Control for Windows SharePoint Services sites that use the default port 80. Open an elevated command prompt. To do this, click Start, right-click Command Prompt, and then click Run as administrator. In the User Account Control dialog box, click Continue. At the command prompt, type the following command (where C:\ represents the drive where you installed Internet Information Services), and then press ENTER: notepad C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config In the <SafeControls> section of the Web.config file, add the following line under the other SafeControl Assembly entries (as a single line): On the File menu, click Save, and then close the file. (Optional) To make the Web Part available to the SharePoint 3.0 Central Administration site, repeat this procedure for the Web.config file that is located in the following folder, where C:\ represents the drive where you installed Internet Information Services: C:\inetpub\wwwroot\wss\VirtualDirectories\ port_number \web.config You must create a folder path to store the images for the Web Part to a Windows SharePoint Services site, you must first add the Web Part to the Web Part Gallery for the site. Then, you can add the Web Part and configure it to point to a specific terminal server or terminal server farm. If you have multiple terminal servers, you can add multiple Web Parts to the page, each pointing to a different terminal server or terminal server farm. In the following procedure, the default Windows SharePoint Services site (on port 80) is used as an example. In Internet Explorer, open the default Windows SharePoint Services site at the following location: When you are prompted, enter your account credentials to log on to the site, and then click OK. If you are prompted that the content is being blocked by Internet Explorer, do one of the following. If there is an Add button, follow these steps: -. To configure the Web Part, click edit in the upper-right corner of the Web Part, and then click Modify Shared Web Part. In the configuration pane that appears, you can configure settings such as the terminal server or terminal server farm from which to populate the Web Part, the title, and other appearance settings. When you are finished configuring the Web Part, click OK. When you are finished editing the site, in the upper-right corner, click Exit Edit Mode. To add other users who can access the site, click the Site Actions tab, and then click Site Settings. You can configure permissions by clicking one or more of the options under Users and Permissions. For more information, see the "About managing SharePoint groups and users" topic and the "Manage SharePoint groups" topic in Windows SharePoint Services Help. (Optional) If you want to add the.
http://technet.microsoft.com/cs-cz/library/cc771354(d=printer,v=ws.10).aspx
CC-MAIN-2013-48
refinedweb
877
54.93
Tweet-a-watt - How to make a twittering power meter... Step 1: Make It!! Make a tweet-a-watt To make the tweet-a-watt setup, we will have to go through a few steps 1. Prepare by making sure we have everything we need and know the skills necessary to build the project 2. Build the receiver setup by soldering up one of the adapter kits 3. Configure the XBee wireless modems 4. Build the transmitter setup by modifying a Kill-a-Watt to transmit via the XBee 5. Run the software, which will retrieve data and save it to a file, upload it to a database and/or twitter Step 2: Prep Tutorials wherever is most convenient/inexpensive. Many of these parts are available in a place like Radio Shack or other (higher quality) DIY electronics stores. I recommend a "basic" electronics tool set for this kit, which I describe here. Soldering iron. One with temperature control and a stand is best. A conical or small 'screwdriver' tip is good, almost all irons come with one of these. A low quality (ahem, $10 model from radioshack) iron may cause more problems than its worth! Do not use a "ColdHeat" soldering iron, they are not suitable for delicate electronics work and can damage the kit (see here) Solder. Rosin core, 60/40. Good solder is a good thing. Bad solder leads to bridging and cold solder joints which can be tough to find. Dont buy a tiny amount, you'll run out when you least expect it. A half pound spool is a minimum. Multimeter/Oscilloscope. A meter is helpful to check voltages and continuity. Flush/diagonal cutters. Essential for cutting leads close to the PCB. Desoldering tool. If you are prone to incorrectly soldering parts. 'Handy Hands' with Magnifying Glass. Not absolutely necessary but will make things go much much faster. Good light. More important than you think. Step 3: Make the Receiver Overview We'll start with the receiver hardware, that's the thing that plugs into the computer and receives data from the wireless power plug. The receiver hardware does 'double duty', it also is used to update the XBee's modems' firmware (which, unfortunately, is necessary because they come from the factory with really old firmware) and configure the modems. What you'll need The receiver is essentially, an XBee, with a USB connection to allow a computer to talk to it the XBee. Name FTDI cable Description A USB-to-serial converter. Plugs in neatly into the Adafruit XBee adapter to allow a computer to talk to the XBee. Datasheet TTL-232R 3.3V or 5.0V Distributor Mouser Qty 1 Name Adafruit XBee Adapter kit Description I'll be using my own design for the XBee breakout/carrier board but you can use nearly any kind as long as you replicate any missing parts such as the3.3V supply and LEDs You will have 2 adapter kits but you should only assemble one for this part! The other one needs different instructions so just hold off!! Datasheet Distributor Adafruit Qty 1 Solder the adapter together! This step is pretty easy, just go over to the XBee adapter webpage and solder it together according to the instructions! Remember: You will have 2 adapter kits but you should only solder one of them at this point! The other one needs different instructions so just hold off! Connect to the XBee Now its time to connect to the XBees Find your. You'll need to figure out which serial port (COM) you are using. Plug in the FTDI cable, USB adapter, Arduino, etc. Under Windows, check the device manager, look for "USB Serial Port" Digi/Maxstream wrote a little program to help configure XBees, its also the only way I know of to upgrade them to the latest firmware. Unfortunately it only runs on Windows. Download X-CTU from Digi and install it on your computer After installing and starting the program, select the COM port (COM4 here) and baud rate (9600 is default). No flow control, 8N1. Make sure the connection box looks just like the image (other than the com port which may be different) To verify, click Test / Query Hopefully the test will succeed. If you are having problems: check that the XBee is powered, the green LED on the adapter board should be blinking, the right COM port & baud rate is selected, etc. Now unplug the adapter from the FTDI cable, carefully replace the first XBee with the other one and make sure that one is talking fine too. Once you know both XBees are working with the adapter, its time to upgrade and configure them, the next step! Step 4: Configure OK so far you have assembled one of the XBee adapter boards and connected it to your computer using the FTDI cable. (The other adapter is for later so don't do anything with it yet!) The XBees respond to the X-CTU software and are blinking just fine. Next we will update the firmware Upgrading the firmware There's a good chance your XBees are not running the latest firmware & there's a lot of features added, some of which we need to get this project running. So next up is upgrading! Go to the Modem Configuration tab. This is where the modem is configured and updated Click Download new versions... and select to download the latest firmwares from the Web Once you have downloaded the newest firmware, its time to upgrade! Click on Modem Parameters -> "Read" to read in the current version and settings Now you will know for sure what function set, version and settings are stored in the modem Select from the Version dropdown the latest version available Check the Always update firmware checkbox And click Write to initialize and program the new firmware in! That's it, now you have the most recent firmware for your modem. You should now uncheck the Always update firmware checkbox. If you have problems, like for example timing out or not being able to communicate, make sure the RTS pin is wired up correctly as this pin is necessary for upgrading. FTDI cables are already set up for this so you shouldn't have a problem Rinse & Repeat Upgrade the firmware on both of the XBees so they are both up to date At this point it might be wise to label the two XBees in a way that lets you tell them apart. You can use a sharpie, a sticker or similar to indicate which one is the receiver and which is the transmitter Configure the transmitter XBee Both XBee's need to be upgraded with the latest firmware but only the transmitter (which is going to be put inside a Kill-a-Watt) needs to be configured. The configure process tells the XBee what pins we want to read the sensor data off of. It also tells the XBee how often to send us data, and how much. Plug the transmitter XBee into the USB connection (put the receiver XBee away) and start up X-CTU or a Terminal program. Connect at 9600 baud, 8N1 parity.Then configure each one as follows: 1. Set the MY address (the identifier for the XBee) to 1 (increment this for each transmitter so you can tell them apart, we'll assume you only have one for now) 2. Set the Sleep Mode SM to 4 (Cyclic sleep) 3. Set the Sleep Time ST to 3 (3 milliseconds after wakeup to go back to sleep) 4. Set the Sleep Period SP to C8 (0xC8 hexadecimal = 200 x 10 milliseconds = 2 seconds between transmits) 5. Set ADC 4 D4 to 2 (analog/digital sensor enable pin AD4) 6. Set ADC 0 D0 to 2 (analog/digital sensor enable pin AD0) 7. Set Samples to TX IT to 13 (0x13 = 19 A/D samples per packet) 8. Set Sample Rate IR to 1 (1 ms between A/D samples) if you think there will be more XBee's in the area that could conflict with your setup you may also want to 1. Set the PAN ID to a 4-digit hex number (its 3332 by default) You can do this with X-CTU or with a terminal program such as hyperterm, minicom, zterm, etc. with the command string ATMY=1,SM=4,ST=3,SP=C8,D4=2,D0=2,IT=13,IR=1 You'll need to start by getting the modem's attention by waiting 10 seconds, then typing in +++ quickly, then pausing for another 5 seconds. Then use AT Basically what this means is that we'll have all the XBees on a single PAN network, each XBee will have a unique identifier, they'll stay in sleep mode most of the time, then wake up every 2 seconds to take 19 samples from ADC 0 and 4, 1ms apart. If you're having difficulty, make sure you upgraded the firmware! Make sure to WRITE the configuration to the XBee's permanent storage once you've done it. If you're using X-CTU click the "Write" button in the top left. If you're using a terminal, use the command ATWR ! Note that once the XBee is told to go into sleep mode, you'll have to reset it to talk to it because otherwise it will not respond and X-CTU will complain. You can simply unplug the adapter from the FTDI cable to reset or touch a wire between the RST and GND pins on the bottom edge of the adapter. Now that the transmitters are all setup with unique MY number ID's, make sure that while they are powered from USB the green LED blinks once every 2 seconds (indicating wakeup and data transmit) Configure the receiver XBee Plug the receiver XBee into the USB connection (put the receiver XBee away) and start up X-CTU. If you set the PAN ID in the previous step, you will have to do the same here - Set the PAN ID to the same hex number as above Now that the XBees are configured and ready, its time to go to the next step where we make the Kill-a-Watt hardware Step 5: Solder the Transmitter - Parts List! Transmitter partslist For each outlet you want to monitor, you'll need: Name: Kill-a-Watt Description: "Off the shelf" model P4400 power monitor Datasheet: P3 Kill-a-watt Distributor: Lots! Also check hardware/electronics stores Qty: 1 Name: Adafruit XBee Adapter Description: I'll be using my own design for the XBee breakout/carrier board but you can use nearly any kind as long as you replicate any missing parts such as the3.3V supply and LEDs! Distributor: Adafruit Qty: 1 Name: D3 Description: 1N4001 diode. Any power diode should work fine. Heck, even a 1n4148 or 1n914 should be OK. But 1N4001 is suggested and is in the kit. Datasheet: Generic 1N4001 Distributor: DigikeyMouser Qty: 1 Name: D2 Description: Large diffused LED, for easy viewing. The kit comes with green. Qty: 1 Name: C3 Description: 220uF, 4V or higher (photo shows 100uF) Datasheet: Generic Distributor: DigikeyMouser Qty: 1 Name: C4 Description: 10,000uF capacitor (wow!) / 6.3V (photo shows a mere 2200uF) Try to get 16mm diameter, 25mm long Datasheet: Generic Distributor: Digikey [Mouser] Qty: 1 Name: R4 R6 Description: 10K 1/4W 1% resistor (brown black black red gold) or 10K 1/4W 5% resistor (brown black orange gold). 1% is preferred but 5% is OK Datasheet: Generic Distributor: MouserDigikey Qty: 2 Name: R3 R5 Description: 4.7K 1/4W 1% resistor (yellow violet black brown gold) or 4.7K 1/4W 5% resistor (yellow violet red gold). 1% is preferred but 5% is OK. Datasheet: Generic Distributor: MouserDigikey Qty: 2 Name: Ribbon cable Description: Ribbon cable, or other flexible wire, at least 6 conductors, about 6" long Datasheet: Generic Ribbon Distributor: Digikey Qty: 6" Name: Heat shrink Description: Heat shrink! A couple inches of 1/8" and 1/16" each Datasheet: Generic It will run you about $50-$60 for each outlet Step 6: Transmitter Schematic: 1. We want to run the XBee off the Kill-a-Watt's internal power supply. However its current limited and wont provide 50mA in a burst when the XBee transmits. We solve this by adding a simple 'rechargeable battery' in the form of a really large capacitor C4. 2. The Kill-a-Watt runs at 5V but XBees can only run at 3.3V so we have a voltage regulator IC1 and two capacitors two stabilize the 3.3V supply, C1 and C2. 3.. 4. The XBee analog sensors run at 3.3V but the Kill-a-Watt sensors run at 5V. We use simple voltage dividers R3/R4 and R5/R6 to reduce the analog signal down to a reasonable level Step 7: Assemble and Create the Transmitter - 1 Open up your kit and get out the parts for the transmitter. Remember that we'll be using most of but not all of an XBee adapter kit. The two small LEDs, the 74HC125N chip, a 10K and 1K resistor are not used and you should put them aside for a future project so you don't accidentally use them here. Check to make sure you've got everything you need. The only thing not shown here is the XBee radio and Kill-a-Watt. Place the PCB of adapter kit and get ready to solder by heating up your soldering iron, and preparing your hand tools We'll start by soldering in the 3.3V regulator, which is identical to the standard XBee Adapter kit you made in the receiver instructions. Don't forget to check the polarity of C2 and that IC1 is in the right way. Then solder and clip the three components. Now we will veer from the standard XBee adapter instructions and add a much larger LED on the ASC line so that we can easily see it blinking when its in the Kill-a-Watt. Make sure to watch for the LED polarity, because a backwards LED will make debugging very difficult. The longer lead goes in the + marked solder hole. Give the LED about half an inch of space beyond the end of the PCB as shown. Also solder in the matching 1K resistor R2 Solder in the two 2mm 10pin female headers in the adapter kit. Be careful with the solder so that you don't accidentally fill the female header. Use a sparing amount to make sure there's a connection but its not overflowing Step 8: Assemble and Create the Transmitter - 2 Now its time to prepare the wires we need for the next few stops. Use your diagonal cutters to notch off the brown, red, orange and yellow wires from the end of the rainbow ribbon cable in the kit. Then tear off the four wires from the rest of the cable. Do the same for the black and white wires and the single green wire. Then cut the green wire so its only about 1.5" long. You should now have 3 strips of wire, one 6" with 4 conductors, one 6" with 2 conductors and one 1.5" with 1 conductor Use wirestrippers to strip the ends of the green wire, 1/4" from the ends Then tin the green wire by heating the ends of the wire and applying a little solder to bind together the stranded wire. Use the green wire to create a jumper between the VREF pin, 7th from the top on the right and the VCC pin on the top left. Double check to make sure you get this right! Then solder it in place. This will set the reference point of the analog converter to 3.3V Go back to the 4-piece ribbon cable. Split the ends with the diagonal cutter, then strip and tin all 8 ends. Put a 4.7K resistor in a vise or holder, then clip one end off and tin it just like the wires. Cut a 1/2" piece of 1/16" heat shrink and slip it onto the yellow wire, making sure there's clearance between the heatshrink and the end of the wire. Then solder the yellow wire to the 4.7k resistor. Do the same for the orange wire and the other 4.7K resistor. Use a heat source (a heat gun or hair drier is perfect) to shrink the heatshrink over the soldered wire/resistor joint.Then bend the resistor 90degrees and clip the other end of the 4.7k resistors Step 9: Assemble and Create the Transmitter - 3 Now we will build the voltage divider. Take the two 10K resistors and connect them as shown. One goes from AD0 and one from AD4. Both then connect to ground. Conveniently, the chip we are not using had grounded pins so we can 'reuse' those pins. Now comes the tricky part. We want to connect the other end of the 4.7K resistor to the AD0 pin but the 10K resistor is already there. Use your soldering iron to melt a blob of solder onto the top of the 10K resistor and then piggyback the 4.7K resistor by soldering to the top of the 10K resistor. Solder the orange wire to the AD0 pin, the yellow to the AD4 The other two wires are for carrying power. The red wire should be soldered to the +5V pin on the bottom of the adapter PCB. The brown wire to the GND pin. We're nearly done with the adapter soldering. Lastly is the 220uF reset capacitor. We'll connect this to the RST pin, 5th from the top on the left. Make sure the long lead is connected to the RST pin and the shorter lead goes to the 4th pin of where the chip would go. Check the photo on the left to make sure you've got it in right. The capacitor wont fit underneath the XBee module so give it some lead length so that the cylindrical bulk is next to the 3.3V regulator. For reference, the images below show what the back should look like. ... and what it should look like with the XBee modem installed. Make sure the pins on the XBee line up with the header. Step 10: Assemble and Create the Transmitter - 4 Now replace the PCB with the huge capacitor. Clip the long leads down. You'll need to use the "-" stripe to keep track of which pin is negative and which is positive. Tin both leads with solder. Solder the other end of the red ribbon wire (that goes to +5V on the XBee adapter) to the positive pin of the capacitor. Then solder the brown wire (that goes to GND on the XBee adapter) to the negative pin. Clip the cathode lead down of the 1N4001 diode, that's the end with the white stripe. on it. Solder the diode so that the white-stripe side is connected to the positive pin of the big capacitor. Take the black and white ribbon from earlier. Split, strip and tin the four ends. Cut a 1" piece of 1/8" heatshrink and slip it onto the white wire. Slip a 1/2" piece of 1/16" heat shrink onto the black wire. Clip the other end of the diode (the side without a white stripe) and solder the white wire to it. Solder the black wire to the negative pin of the big capacitor. Now shrink the heatshrink so that the capacitor leads and diode are covered. All right, here is what you should have, an adapter with two sensor lines (orange and yellow) hanging off and two power lines (red and brown) that are connected to the big capacitor. Then there are two black&white wires connected to the capacitor, the white one through a diode. Step 11: Assemble and Create the Transmitter - 5 Now its time to open the Kill-a-Watt! There are only 3 screws that hold it together, and they are found on the back. Now its time to open the Kill-a-Watt! There are only 3 screws that hold it together, and they are found on the back. Use a 3/8 drill bit to make a hole near the right corner of the case back. This is what the LED will stick out of. (Ignore the white tape and #4, this is a recycled kill-a-watt :) Now find the LM2902N chip. This is a quad op-amp that senses the power line usage. We're going to piggy-back right on top of it, and borrow the ground, 5V power and 2 sensor outputs! With your soldering iron, melt a bit of solder on pin 1, 4, 11 and 14 of the chip. Make sure you have the chip oriented correctly, the notch indicates where pins 1 and 14 are Solder the white wire (5V to the XBee) to pin 4. Solder the black wire (ground) to pin 11 directly across. Now solder the yellow wire to pin 1 and the orange wire to pin 14. Use two small pieces of sticky foam and stick them onto the back of the case. Then place the XBee adapter and capacitor on the tape so that the LED sticks out of the hole drilled earlier Tuck the excess ribbon cable out of the way so that they are not near the 120V connections which could make them go poof. Close it up and plug it in. You'll notice its a bit finicky for a few seconds as the big capacitor charges up. The display may not come up for 15-30 seconds, and it may fade in and out at first. The numbers may also be wrong for a bit as it powers up. Within about 30 seconds, you should see the display stabilize and the indicator LED blinking every 2 seconds! Go back to your computer, plug the receiver XBee into the USB adapter and make sure it has the latest firmware uploaded and set it to the same PAN ID as the transmitters. You will see the RSSI LED (red LED) light up. That means you have a good link! Open up the Terminal in X-CTU (or another terminal program) and connect at 9600 baud 8N1 parity and you'll see a lot of nonsense. Whats important is that a new chunk of nonsense gets printed out once every 2 seconds, indicating a packet of data has been received. The hardware is done. Good work! Step 12: Software Introduction Now that the hardware is complete, we come to the exciting part: running the software that retrieves the data from our receiver XBee and saves it to our computer or uploads it to a database or updates our twitter feed or....whatever you'd like! Here is how it works, the XBee inside the Kill-a-Watt is hooked up to two analog signals. One is the voltage signal which indicates the AC voltage read. In general this is a sine wave that is 120VAC. One tricky thing to remember is that 120V is the 'RMS' voltage, and the 'true voltage' is +-170VDC. (You can read more about RMS voltage at wikipedia basically its a way to indicate how much 'average' voltage there is.) The second reading is the AC current read. This is how much current is being drawn through the Kill-a-Watt. If you multiply the current by the voltage, you'll get the power (in Watts) used! The XBee's Analog/Digital converter is set up to take a 'snapshot' of one sine-cycle at a time. Each double-sample (voltage and current) is taken 1ms apart and it takes 17 of them. That translates to a 17ms long train of samples. One cycle of power-usage is 1/60Hz long which is 16.6ms. So it works pretty well! Lets look at some examples of voltage and current waveforms as the XBee sees them.. That's because a lightbulb is just a resistor! Finally, lets try sticking the meter on a dimmable switch. You'll see that the voltage is 'chopped' up, no longer sinusoidal. And although the current follows the voltage, its still matching pretty well. The XBee sends the raw data to the computer which, in a python script, figures out what the (calibrated) voltage and amperage is at each sample and multiplies each point together to get the Watts used in that cycle. Since there's almost no device that changes the power-usages from cycle-to-cycle, the snapshot is a good indicator of the overall power usage that second. Then once every 2 seconds, a single snapshot is sent to the receiver XBee Install python & friends The software that talks to the XBee is written in python. I used python because its quick to develop in, has multi-OS support and is pretty popular with software and hardware hackers. The XBees talk over the serial port so literally any programming language can/could be used here. If you're a software geek and want to use perl, C, C#, tcl/tk, processing, java, etc. go for it! You'll have to read the serial data and parse out the packet but its not particularly hard. However, most people just want to get on with it and so for you we'll go through the process of installing python and the libraries we need. 1. Download and install python 2.5 from I suggest 2.5 because that seems to be stable and well supported at this time. If you use another version there may be issues 2. Download and install pyserial from the package repository (this will let us talk to the XBee thru the serial port) 3. If you're running windows download and install win32file for python 2.5 (this will add file support) 4. Download and install the simplejson python library (this is how the twitter api likes to be spoken to) Now you can finally download the Wattcher script we will demonstrate here! We're going to download it into the C:\wattcher directory, for other OS's you can of course change this directory Basic configure We'll have to do a little bit of setup to start, open up the wattcher.py script with a text editor and find the line SERIALPORT = "COM4" # the com/serial port the XBee is connected to change COM4 into whatever the serial port you will be connecting to the XBee with is called. Under windows its some COMx port, under linux and mac its something like /dev/cu.usbserial-xxxx check the /dev/ directory and/or dmesg Save the script with the new serial port name Test it out Once you have installed python and extracted the scripts to your working directory, start up a terminal (under linux this is just rxvt or xterm, under mac its Terminal, under windows, its a cmd window) I'm going to assume you're running windows from now on, it shouldn't be tough to adapt the instructions to linux/mac once the terminal window is open. Run the command cd C:\wattcher to get to the place where you uncompressed the files. By running the dir command you can see that you have the files in the directory Make sure your transmitter (Kill-a-Watt + Xbee) is plugged in, and blinking once every 2 seconds. Remember it takes a while for the transmitter to charge up power and start transmitting. The LCD display should be clear, not fuzzy. Make sure that there's nothing plugged into the Kill-a-Watt, too. The RSSI (red) LED on the receiver connected to the computer should be lit indicating data is being received. Don't continue until that is all good to go. Now run python by running the command C:\python25\python.exe wattcher.py You should get a steady print out of data. The first number is the XBee address from which it received data, following is the estimated current draw, wattage used and the Watt-hours consumed since the last data came in. Hooray! We have wireless data! Calibrating Now that we have good data being received, its time to tweak it. For example, its very likely that even without an appliance or light plugged into the Kill-a-Watt, the script thinks that there is power being used. We need to calibrate the sensor so that we know where 'zero' is. In the Kill-a-Watt there is an autocalibration system but unfortunately the XBee is not smart enough to do it on its own. So, we do it in the python script. Quit the script by typing in Control-C and run it again this time as C:\python25\python.exe wattcher.py -d note the -d which tells the script to print out debugging information Now you can see the script printing out a whole mess of data. The first chunk with lots of -1's in it is the raw packet. While its interesting we want to look at the line that starts with ampdata: ampdata: [498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 498, 497, 498, 498, 498] Now you'll notice that the numbers are pretty much all the same. That's because there's nothing plugged into the tweetawatt and so each 1/60 Hz cycle has a flat line at 'zero'. The A/D in the XBee is 10 bits, and will return values between 0 and 1023. So, in theory, if the system is perfect the value at 'zero' should be 512. However, there are a bunch of little things that make the system imperfect and so zero is only close to 512. In this case the 'zero' calibration point is really 498. When its off there is a 'DC offset' to the Amp readings, as this graph shows: See how the Amp line (green) is steady but its not at zero, its at 0.4 amps? There is a 'DC offset' of 0.4 amps OK, open up the wattcher.py script in a text editor. vrefcalibration = [492, # Calibration for sensor #0] 492, # Calibration for sensor #1 489, # Calibration for sensor #2 492, # Calibration for sensor #3 501, # Calibration for sensor #4 493] # etc... approx ((2.4v * (10Ko/14.7Ko)) / 3 See the line that says # Calibration for sensor #1? Change that to 498 vrefcalibration = [492, # Calibration for sensor #0] 498, # Calibration for sensor #1 489, # Calibration for sensor #2 492, # Calibration for sensor #3 501, # Calibration for sensor #4 493] # etc... approx ((2.4v * (10Ko/14.7Ko)) / 3 Save the file and start up the script again, this time without the -d Now you'll see that the Watt draw is 2W or less, instead of 40W (which was way off!) The reason its not 0W is that, first off, there's a little noise that we're reading in the A/D lines, secondly there's power draw by the Kill-a-Watt itself and finally, the XBee doesn't have a lot of samples to work with. However <2W is pretty good considering that the full sensing range is 0-1500W Note the graph with the calibrated sensor: See how the Amps line is now at 0 steady, there is no DC offset Logging data Its nice to have this data but it would be even nicer if we could store it for use. Well, thats automatically done for you! You can set the name of the log file in the wattcher.py script. By default it's powerdatalog.csv. The script collects data and every 5 minutes writes a single line in the format Year Month Day, Time, Sensor#, Watts for each sensor.As you can see, this is an example of a 40W incandescent lightbulb plugged in for a few hours. Because of the low sample rate, you'll see some minor variations in the Watts recorded. This data can be easily imported directly into any spreadsheet program Tweeting Finally we get to the tweeting part of the tweet-a-watt. First open up the wattcher.py script and set # Twitter username & password twitterusername = "username" twitterpassword = "password" to your username and password on twitter. You can make an account on twitter.com if you don't have one. Then run the script as usual. Every 8 hours (midnight, 8am and 4pm) the script will sent a twitter using the Twitter API Then check it out at your account: Step 13: Expand Overview Once you've got your base system up and running here are some ideas for how to extend, improve or expand it! Add more outlets So you can track more rooms, of course Graphing If you'd like to play some more with the script, there's some extras built in. For example, you can graph the data as it comes in from the XBee, both Watts used and the actual 'power line' waveform. Simply set GRAPHIT = True you'll need to install a mess of python libraries though, including wxpython, numpy and pylab Remove the computer It took a few hours, but I hacked my Asus wifi router to also log data for me. There'll be more documentation soon but here's some hints: Do basically everything in [Do basically everything in Step 14: Design - Overview Design overview For those interested in how to build a sensor node system with a Google Appengine backend, here is the process by which I created it. Of course, you should have the hardware part done first! 1. Listen - designing the parser for the computer that grabs XBee packets, and extracts the useful data 2. Store - how to use GAE to store the data in 'the cloud' 3. Graph - using Google Visualizations to make pretty graphs Step 15: Design - Listen Data listening & parsing In this section we will work on the receiver software, that will talk to a receiver XBee and figure out what the sensor data means. I'll be writing the code in python which is a fairly-easy to use scripting language. It runs on all OS's and has tons of tutorials online. Also, Google AppEngine uses it so its a good time to learn! This whole section assumes that you only have 1 transmitter and 1 receiver, mostly to make graphing easier to cope with. In the next section we'll tie in more sensors when we get to the datalogging part! Raw analog input We'll start by just getting raw data from the XBee and checking it out. The packet format for XBees is published but instead of rooting around in it, I'll just use the handy XBee library written for python. With it, I can focus on the data instead of counting bytes and calculating checksums. To use the library, first use the pyserial module to open up a serial port (ie COM4 under windows, /dev/ttyUSB0 under mac/linux/etc) You can look at the XBee project page for information on how to figure out which COM port you're looking for. We connect at the standard default baudrate for XBees, which is 9600 and look for packets Running this code, you'll get the following output: ]]}> which we will reformat to make a little more legible ]] }> OK now its clear whats going on here. First off, we get some data like the transmitter ID (address_16) and signal strength (RSSI). The packet also tells us how many sample are available (19). Now, the digital samples are all -1 because we didn't request any to be sent. The library still fills them in tho so thats why the non-data is there. The second chunk is 19 sets of analog data, ranging from 0 to 1023. As you can see, the first sample (#0) and fifth sample (#4) contain real data, the rest are -1. That corresponds to the hardware section where we setup AD0 and AD4 to be our voltage and current sensors. We'll tweak our code so that we can extract this data only and ignore the rest of the packet. This code creates two arrays, voltagedata and ampdata where we will stick the data. We throw out the first sample because usually ADCs are a bit wonky on the first sample and then are good to go after that. It may not be necessary tho #!] print voltagedata print ampdata Now our data is easier to see: Voltage: [672, 801, 864, 860, 755, 607, 419, 242, 143, 108, 143, 253, 433, 623, 760, 848, 871, 811] Current: [492, 492, 510, 491, 492, 491, 491, 491, 492, 480, 492, 492, 492, 492, 492, 492, 497, 492] Note that the voltage swings from about 100 to 900, sinusoidally. Normalizing the data Next up we will 'normalize' the data. The voltage should go from -170 to +170 which is the actual voltage on the line, instead of 100 to 900 which is just what the ADC reads. To do that we will get the average value of the largest and smallest reading and subtract it from all the samples. After that, we'll normalize the Current measurements as well, to get the numbers to equal the current draw in Amperes. #!] # get max and min voltage and normalize the curve to '0' # to make the graph 'AC coupled' / signed min_v = 1024 # XBee ADC is 10 bits, so max value is 1023 max_v = 0 for i in range(len(voltagedata)): if (min_v > voltagedata[i]): min_v = voltagedata[i] if (max_v < voltagedata[i]): max_v = voltagedata[i] # figure out the 'average' of the max and min readings avgv = (max_v + min_v) / 2 # also calculate the peak to peak measurements vpp = max_v-min_v for i in range(len(voltagedata)): #remove 'dc bias', which we call the average read voltagedata[i] -= avgv # We know that the mains voltage is 120Vrms = +-170Vpp voltagedata[i] = (voltagedata[i] * MAINSVPP) / vpp # normalize current readings to amperes for i in range(len(ampdata)): # VREF is the hardcoded 'DC bias' value, its # about 492 but would be nice if we could somehow # get this data once in a while maybe using xbeeAPI ampdata[i] -= VREF # the CURRENTNORM is our normalizing constant # that converts the ADC reading to Amperes ampdata[i] /= CURRENTNORM print "Voltage, in volts: ", voltagedata print "Current, in amps: ", ampdata We'll run this now to get this data, which looks pretty good, there's the sinusoidal voltage we are expecting and the current is mostly at 0 and then peaks up and down once in a while. Note that the current is sometimes negative but that's OK because we multiply it by the voltage and if both are negative it still comes out as a positive power draw Voltage, in volts: [-125, -164, -170, -128, -64, 11, 93, 148, 170, 161, 114, 46, -39, -115, -157, -170, -150, -99] Current, in amps: [0.064516129032258063, -1.096774193548387, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.096774193548387,] 0.0, 0.0, 0.0, -0.064516129032258063, 0.0, 0.0, -0.70967741935483875, 0.0, 0.0] Basic data graphing Finally, I'm going to add a whole bunch more code that will use the numpy graphing modules to make a nice graph of our data. Note that you'll need to install wxpython as well as numpy, and matplotlib! At this point, the code is getting waaay to big to paste here so grab "wattcher.py Mains graph" from the download page! Run it and you should see a graph window pop up with a nice sinusoidal voltage graph and various amperage data.. Thats because a lightbulb is just a resistor! Finally, lets try sticking the meter on a dimmable switch. You'll see that the voltage is 'chopped' up, no longer sinusoidal. And although the current follows the voltage, its still matching pretty well. Graphing wattage! OK neat, its all fun to watch waveforms but what we -really want- is the Watts used. Remember, P = VI otherwise known as Watts = Voltage * Current. We can calculate total Watts used by multiplying the voltages and currents at each sample point, then summing them up over a cycle & averaging to get the power used per cycle. Once we have Watts, its easy to just multiply that by 'time' to get Watt-hours! Download and run the wattcher.py - watt grapher script from the download page Now you can watch the last hour's worth of watt history (3600 seconds divided by 2 seconds per sample = 1800 samples) In the image above you can see as I dim a 40-watt lightbulb. The data is very 'scattered' looking because we have not done any low-pass filtering. If we had a better analog sampling rate, this may not be as big a deal but with only 17 samples to work with, precision is a little difficult Done! OK great! We have managed to read data, parse out the analog sensor payload and process it in a way that gives us meaningful graphs. Of course, this is great for instantaneous knowledge but it -would- be nice if we could have longer term storage, and also keep track of multiple sensors. In the next step we will do that by taking advantage of some free 'cloud computing' services! Step 16: Design - Store Introduction OK we are getting good data from our sensors, lets corral it into more useful chunks and store it in a database. We could make a database on the computer, but since we'd like to share this data, it makes more sense to put it online. There are custom services that are specifically designed to do this sort of thing like Pachube but I'm going to reinvent the wheel and design my own web-app that stores and displays energy data. (Mostly I want to play around with Google App Engine!) You have 5 minutes! We get data every few seconds from the XBee modem inside the kill-a-watt. We could, in theory, put data into our database every 2 seconds but that would quickly balloon the amount of storage necessary. It would also make sorting through the data difficult. So instead lets add up all the sensor data for 5 minutes and then take the average. We'll do this by keeping two timers and one tally. One timer will track how long its been since the last sensor signal was sent, and the other will track if its been 5 minutes. The tally will store up all the Watt-hours (Watt measurements * time since last sensor data). Then at the end we can average by the 5 minutes This chunk of code goes near the beginning, it creates the timers and tally and initializes them ... fiveminutetimer = lasttime = time.time() # get the current time cumulativewatthr = 0 ... Then later on, after we get our data we can put in this chunk of code: # add up the delta-watthr used since last reading # Figure out how many watt hours were used since last reading elapsedseconds = time.time() - lasttime dwatthr = (avgwatt * elapsedseconds) / (60.0 * 60.0) # 60 seconds in 60 minutes = 1 hr lasttime = time.time() print "\t\tWh used in last ",elapsedseconds," seconds: ",dwatthr cumulativewatthr += dwatthr # Determine the minute of the hour (ie 6:42 -> '42') currminute = (int(time.time())/60) % 10 # Figure out if its been five minutes since our last save if (((time.time() - fiveminutetimer) >= 60.0) and (currminute % 5 == 0)): # Print out debug data, Wh used in last 5 minutes avgwattsused = cumulativewatthr * (60.0*60.0 / (time.time() - fiveminutetimer)) print time.strftime("%Y %m %d, %H:%M"),", ",cumulativewatthr,"Wh = ",avgwattsused," W average") # Reset our 5 minute timer fiveminutetimer = time.time() cumulativewatthr = 0 Note that we calculate delta-watthours, the small amount of power used every few seconds. Then we can get the average watts used by dividing the watthours by the number of hours that have passed (about 1/12th). Instead of going by exact 5 minutes, I decided to only report on the 5's of the hour (:05, :10, etc) so that its easier to send all the data at once if theres multiple sensors that started up at different times. Download wattcher-5minreporter.py from the Download page. If you run this, you'll get a steady stream Near the end you can see the timestamp, the Watthrs used in the last few minutes and the average Wattage Multisensor! We have good data but so far it only works with one sensor. Multiple sensors will mess it up! Time to add support for more than one XBee so that I can track a few rooms. I'll do that by creating an object class in python, and using the XBee address (remember that from part 1?) to track. I'll replace the code we just wrote with the following: At the top, instead of the timer variables, I'll have a full class declaration, and create an array to store them: ####### store sensor data and array of histories per sensor class Fiveminutehistory: def init(self, sensornum): self.sensornum = sensornum self.fiveminutetimer = time.time() # track data over 5 minutes self.lasttime = time.time() self.cumulativewatthr = 0 def addwatthr(self, deltawatthr): self.cumulativewatthr += float(deltawatthr) def reset5mintimer(self): self.cumulativewatthr = 0 self.fiveminutetimer = time.time() def avgwattover5min(self): return self.cumulativewatthr * (60.0*60.0 / (time.time() - self.fiveminutetimer)) def str(self): return "[id#: %d, 5mintimer: %f, lasttime; %f, cumulativewatthr: %f]" % (self.sensornum, self.fiveminutetimer, self.lasttime, self.cumulativewatthr) ######### an array of histories sensorhistories = [] When the object is initialized with the sensor ID number, it also sets up the two timers and cumulative Watthrs tracked. I also created a few helper functions that will make the code cleaner Right below that I'll create a little function to help me create and retrieve these objects. Given an XBee ID number it either makes a new one or gets the reference to it ####### retriever def findsensorhistory(sensornum): for history in sensorhistories: if history.sensornum == sensornum: return history # none found, create it! history = Fiveminutehistory(sensornum) sensorhistories.append(history) return history Finally, instead of the average Watt calculation code written up above, we'll replace it with the following chunk, which retreives the object and tracks power usage with the object timers # retreive the history for this sensor sensorhistory = findsensorhistory(xb.address_16) #print sensorhistory # ",elapsedseconds," seconds: ",dwatthr sensorhistory.addwatthr(dwatthr) # Determine the minute of the hour (ie 6:42 -> '42') currminute = (int(time.time())/60) % 10 # Figure out if its been five minutes since our last save if (((time.time() - sensorhistory.fiveminutetimer) >= 60.0) and (currminute % 5 == 0)): # Print out debug data, Wh used in last 5 minutes avgwattsused = sensorhistory.avgwattover5min() print time.strftime("%Y %m %d, %H:%M"),", ",sensorhistory.cumulativewatthr,"Wh = ",avgwattsused," W average" # Reset our 5 minute timer sensorhistory.reset5mintimer() The code basically acts the same except now it wont choke on multiple sensor data! Below, my two Kill-a-Watts, one with a computer attached (100W) and another with a lamp (40W) Onto the database! The App Engine So we want to have an networked computer to store this data so we can share the data, but we really don't want to have to run a server from home! What to do? Well as mentioned before, you can use Pachube or similar, but I will show how to roll-your-own with Google App Engine (GAE). GAE is basically a free mini-webserver hosted by Google, that will run basic webapps without the hassle of administrating a database server. Each webapp has storage, some frameworks and can use Google accounts for authentication. To get started I suggest checking out the GAE website, documentation, etc. I'll assume you've gone through the tutorials and jump right into designing my power data storage app called Wattcher (a little confusing I know) First, the app.yaml file which defines my app looks like this: application: wattcher version: 1 runtime: python api_version: 1 handlers: - url: /.* script: wattcherapp.py Pretty simple, just says that the app uses wattcherapp.py as the source file Next, we'll dive into the python code for our webapp. First, the includes and database index. To create a database, we actually define it -in the python file-, GAE then figures out what kind of database to create for you by following those directions (very different than MySQL where you'd create the DB separately) import cgi, datetime from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db class Powerusage(db.Model): author = db.UserProperty() # the user sensornum = db.IntegerProperty() # can have multiple sensors watt = db.FloatProperty() # each sending us latest Watt measurement date = db.DateTimeProperty(auto_now_add=True) # timestamp We use the default includes. We have a single database table called Powerusage, and it has 4 entries: one for the user, one for the sensor number, one for the last reported Watts used and one for a datestamp Each 'page' or function of our webapp needs its own class. Lets start with the function that allows us to store data in the DB. I'll call it PowerUpdate. class PowerUpdate(webapp.RequestHandler): def get(self): # make the user log in if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) powerusage = Powerusage() if users.get_current_user(): powerusage.author = users.get_current_user() #print self.request if self.request.get('watt'): powerusage.watt = float(self.request.get('watt')) else: self.response.out.write('Couldnt find \'watt\' GET property!') return if self.request.get('sensornum'): powerusage.sensornum = int(self.request.get('sensornum')) else: powerusage.sensornum = 0 # assume theres just one or something powerusage.put() self.response.out.write('OK!') When we send a request to do that with a GET call (ie requesting the webpage), we'll first make sure the user is authenticated and logged in so we know their name. Then we'll create a new database entry by initializing a new instantiation of Powerusage. Then we'll look the GET request for the watt data, which would be in the format watt=39.2 or similar. That's parsed for us, thankfully and we can also get the sensor number which is passed in the format sensornum=3. Finally we can store the data into the permanent database Next is a useful debugging function, it will simply print out all the data it has received for your account! class DumpData(webapp.RequestHandler): def get(self): # make the user log in if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) self.response.out.write('<html><body>Here is all the data you have sent us:<p>') powerusages = db.GqlQuery("SELECT * FROM Powerusage WHERE author = :1 ORDER BY date", users.get_current_user())>") This function simply SELECT's (retrieves) all the entries, sorts them by date and prints out each one at a time Finally we'll make a basic 'front page' that will show the last couple of datapoints sent class MainPage(webapp.RequestHandler): def get(self): self.response.out.write('<html><body>Welcome to Wattcher!<p>Here are the last 10 datapoints:<p>') powerusages = db.GqlQuery("SELECT * FROM Powerusage ORDER BY date DESC LIMIT 10")>") Its very similar to the DataDump function but its only 10 points of data and from all users, nice to use when you just want to 'check it out' but don't want to log in Finally, we have a little initializer structure that tells GAE what pages link to what functions application = webapp.WSGIApplication( [('/', MainPage),] ('/report', PowerUpdate), ('/dump', DumpData)], debug=True) def main(): run_wsgi_app(application) if name == "main": main() Test! OK lets try it out, first lets visit Remember we made it a requirement to supply -some- data. Lets try again Yay we got an OK! Lets check out the data stored by visiting There's two entries because I did a little testing beforehand but you can see that there are 2 entries. Nice! We can also visit the GAE control panel and browse the data 'by hand' Anyways, now that that's working, lets go back and add the reporting technology to our sensor-reader script Getting the report out Only a little more hacking on the computer script and we're done. We want to add support for sending data to GAE. Unfortunately right now our authentication is done through Google accounts so its not easy to run on an Arduino. To adapt it you'd have to send the username in the Report GET and hope nobody else uses the same one (unless you also add a basic password system) Anyhow, I totally ripped off how to do this from some nice people on the Internet Download appengineauth.py from the download page, and change the first few lines if necessary. We hardcode the URL we're going to and the account/password as well as the GAE app name users_email_address = "myaccount@gmail.com" users_password = "mypassword" my_app_name = "wattcher" target_authenticated_google_app_engine_uri = '' The real work happens at this function sendreport where it connects and sends the Watt data to the GAE site def sendreport(sensornum, watt): # this is where I actually want to go to serv_uri = target_authenticated_google_app_engine_uri + "?watt="+str(watt)+"&sensornum="+str(sensornum) serv_args = {} serv_args['continue'] = serv_uri serv_args['auth'] = authtoken full_serv_uri = "" % (urllib.urlencode(serv_args)) serv_req = urllib2.Request(full_serv_uri) serv_resp = urllib2.urlopen(serv_req) serv_resp_body = serv_resp.read() # serv_resp_body should contain the contents of the # target_authenticated_google_app_engine_uri page - as we will have been # redirected to that page automatically # # to prove this, I'm just gonna print it out print serv_resp_body Finally, we wrap up by adding the following lines to our computer script, which will send the data nicely over to GAE! # Also, send it to the app engine appengineauth.sendreport(xb.address_16, avgwattsused) You can download the final script wattcher.py - final from the download page! Don't forget to visit wattcher.appspot.com to check out the lastest readings Step 17: Design - Graph Making pretty pictures Data is great, but visualizations are better. In this step we'll manipulate our stored history so that we can make really nice graphs! First we'll start by making our sensors named, so that its easier for us to keep track of which is what. Then we'll look at our graph options and data formats. Finally we'll reformat our data to make it ready for graphing Configuring the sensor names Its no fun to have data marked as "sensor #1" so I added a 'config' page where the app engine code looks at what sensor numbers have sent data to the database and then allows you to name them. Of course, you need to have the sensor on and sending data -first- before this will work The configure screen looks something like the image below. This code uses GET when it should really use POST. I'm kinda old and dont like debugging with POST so...yeah. class Configure('<html><body>Set up your sensornode names here:<p>') # find all the sensors up to #10 sensorset = [] for i in range(10): c = db.GqlQuery("SELECT * FROM Powerusage WHERE author = :1 and sensornum = :2", users.get_current_user(), i) if c.get(): sensorset.append(i) self.response.out.write('<form action="/config" method="get">') for sensor in sensorset: name = "" currnamequery = db.GqlQuery("SELECT * FROM Sensorname WHERE author = :1 AND sensornum = :2", users.get_current_user(), sensor) currname = currnamequery.get() # first see if we're setting it! if self.request.get('sensornum'+str(sensor)): name = self.request.get('sensornum'+str(sensor)) if not currname: currname = Sensorname() # create a new entry currname.sensornum = sensor currname.author = users.get_current_user() currname.sensorname = name currname.put() else: # we're not setting it so fetch current entry if currname: name = currname.sensorname self.response.out.write('Sensor #'+str(sensor)+': <input type="text" name="sensornum'+str(sensor)+'" value="'+name+'"></text><p>') self.response.out.write("""<div><input type="submit" value="Change names"></div> </form> </body> </html>""") Now we can have more useful data in the history dump Now we can see that Phil is mostly to blame for our power bill! Google Visualizer So we have data and we'd like to see our power usage history. Graphing data is a lot of work, and I'm lazy. So I look online and find that Google -also- has a visualization API! This means I don't have to write a bunch of graphical code, and can just plug into their system. Sweet! OK checking out the gallery of available visualizations, I'm fond of this one, the Annotated Time Line Note how you can easily see the graphs, scroll around, zoom in and out and each plot is labeled. Perfect for plotting power data! Data formatting Theres a few restrictions to how we get the data to the visualization api and our best option is JSon data. As far as I can tell, JSON is what happened when everyone said "wow, XML is really bulky and wasteful". Anyhow, theres like 4 layers of framework and interpretive data structions and in the end there was a pretty easy to use library written by the Google Visualizations team that let me 'just do it' with a single call by putting the data into a python 'dictionary' in a certain format. Lets go through the code in sections, since the function is quite long class JSON() # assume we want 24 hours of data historytimebegin = 24 if self.request.get('bhours'): historytimebegin = int(self.request.get('bhours')) # assume we want data starting from 0 hours ago historytimeend = 0 if self.request.get('ehours'): historytimeend = int(self.request.get('ehours')) # data format for JSON happiness datastore = [] columnnames = ["date"] columnset = set(columnnames) description ={"date": ("datetime", "Date")} # the names of each sensor, if configured sensornames = [None] * 10 First up we get the user we're going to be looking up the data for. Then we have two variables for defining the amount of data to grab. One is "ehours" (end hours) and the other is "bhours". So if you wanted the last 5 hours, bhours would be 5 and ehours would be 0. If you wanted 5 hours from one day ago, bhours would be 29 and ehours would be 24. datastore is where we will corall all the data. columnnames and description are the 'names' of each column. We always have a date column, then another column for each sensor stream. We also have a seperate array to cache the special sensor names. onto the next section! Here is where we actually grab data from the database. Now app engine has this annoying restriction, you can only get 1000 points of data at once so what I do is go through it 12 hours at a time. The final datastore has all the points but its easier on the database, I guess. One thing that's confusing perhaps is each column has a name and a description. The name is short, say "watts3" for sensor #3, but the description might be "Limor's workbench". I don't even remember writing this code so maybe you can figure it out on your own? # we cant grab more than 1000 datapoints, thanks to free-app-engine restriction # thats about 3 sensors's worth in one day # so we will restrict to only grabbing 12 hours of data at a time, about 7 sensors worth while (historytimebegin > historytimeend): if (historytimebegin - historytimeend) > 12: timebegin = datetime.timedelta(hours = -historytimebegin) timeend = datetime.timedelta(hours = -(historytimebegin-12)) historytimebegin -= 12 else: timebegin = datetime.timedelta(hours = -historytimebegin) historytimebegin = 0 timeend = datetime.timedelta(hours = -historytimeend) # grab all the sensor data for that time chunk powerusages = db.GqlQuery("SELECT * FROM Powerusage WHERE date > :1 AND date < :2 AND author = :3 ORDER BY date", datetime.datetime.now()+timebegin, datetime.datetime.now()+timeend, account) # sort them into the proper format and add sensor names from that DB if not done yet for powerused in powerusages: coln = "watts" + str(powerused.sensornum) entry = {"date": powerused.date.replace(tzinfo=utc).astimezone(est), coln: powerused.watt} if not (coln in columnset): columnnames.append(coln) columnset = set(columnnames) # find the sensor name, if we can if (len(sensornames) < powerused.sensornum) or (not sensornames[powerused.sensornum]): currnamequery = db.GqlQuery("SELECT * FROM Sensorname WHERE author = :1 AND sensornum = :2", account, powerused.sensornum) name = currnamequery.get() if not name: sensornames[powerused.sensornum] = "sensor #"+str(powerused.sensornum) else: sensornames[powerused.sensornum] = name.sensorname description[coln] = ("number", sensornames[powerused.sensornum]) #self.response.out.write(sensornames) # add one entry at a time datastore.append(entry) Finally at the end of all the looping, we call the magic function that turns the dictionary into JSON, wrap it in the proper Google Visualization package, then spit it out! # OK all the data is ready to go, print it out in JSON format! data_table = gviz_api.DataTable(description) data_table.LoadData(datastore) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(data_table.ToJSonResponse(columns_order=(columnnames), order_by="date")) If you were to visit it would output something like this: google.visualization.Query.setResponse({'version':'0.5', 'reqId':'0', 'status':'OK', 'table': {cols: [{id:'date',label:'Date',type:'datetime'},{id:'watts1',label:'Limor',type:'number'},{id:'watts5',label:'Workbench',type:'number'},{id:'watts2',label:'Adafruit',type:'number'},{id:'watts4',label:'Phil2',type:'number'}],rows: [{c:[{v:new Date(2009,1,25,21,20,2)},{v:64.8332291619},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,20,3)},,{v:230.122099757},,{v:null}]},{c:[{v:new Date(2009,1,25,21,20,3)},,,{v:65.4923925044},{v:null}]},{c:[{v:new Date(2009,1,25,21,20,4)},,,,{v:48.6947643311}]},{c:[{v:new Date(2009,1,25,21,25,3)},,{v:228.409810208},,{v:null}]},{c:[{v:new Date(2009,1,25,21,25,3)},{v:67.3574917331},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,25,3)},,,{v:66.0046383897},{v:null}]},{c:[{v:new Date(2009,1,25,21,25,4)},,,,{v:47.3892235642}]},{c:[{v:new Date(2009,1,25,21,30,2)},{v:84.9379517795},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,30,3)},,,,{v:99.7553490071}]},{c:[{v:new Date(2009,1,25,21,30,5)},,{v:229.73642288},,{v:null}]},{c:[{v:new Date(2009,1,25,21,30,6)},,,{v:66.6556291818},{v:null}]},{c:[{v:new Date(2009,1,25,21,35,2)},,,{v:67.3146052998},{v:null}]},{c:[{v:new Date(2009,1,25,21,35,3)},{v:96.2322216676},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,35,3)},,{v:226.678267688},,{v:null}]},{c:[{v:new Date(2009,1,25,21,35,4)},,,,{v:158.428422765}]},{c:[{v:new Date(2009,1,25,21,40,3)},,{v:232.644574879},,{v:null}]},{c:[{v:new Date(2009,1,25,21,40,4)},,,,{v:153.666193493}]},{c:[{v:new Date(2009,1,25,21,40,6)},,,{v:66.7874343225},{v:null}]},{c:[{v:new Date(2009,1,25,21,40,12)},{v:95.0019590395},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,40,21)},{v:95.0144043571},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,40,23)},,,{v:66.8060307611},{v:null}]},{c:[{v:new Date(2009,1,25,21,45,2)},,,{v:66.9814723201},{v:null}]},{c:[{v:new Date(2009,1,25,21,45,3)},,{v:226.036818816},,{v:null}]},{c:[{v:new Date(2009,1,25,21,45,3)},{v:99.2775581827},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,45,4)},,,,{v:154.261889366}]},{c:[{v:new Date(2009,1,25,21,50,4)},{v:102.104642018},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,50,4)},,,,{v:155.441084531}]},{c:[{v:new Date(2009,1,25,21,50,5)},,,{v:67.0087146687},{v:null}]},{c:[{v:new Date(2009,1,25,21,50,5)},,{v:230.678636915},,{v:null}]},{c:[{v:new Date(2009,1,25,21,55,3)},{v:103.493297176},,,{v:null}]},{c:[{v:new Date(2009,1,25,21,55,3)},,,,{v:151.309223916}]},{c:[{v:new Date(2009,1,25,21,55,4)},,,{v:66.9174858741},{v:null}]},{c:[{v:new Date(2009,1,25,21,55,4)},,{v:227.765325835},,{v:null}]},{c:[{v:new Date(2009,1,25,22,0,3)},,,{v:67.0004310254},{v:null}]},{c:[{v:new Date(2009,1,25,22,0,3)},,,,{v:150.389989112}]},{c:[{v:new Date(2009,1,25,22,0,3)},,{v:230.892049553},,{v:null}]},{c:[{v:new Date(2009,1,25,22,0,4)},{v:92.2432771363},,,{v:null}]},{c:[{v:new Date(2009,1,25,22,15,3)},{v:97.5910440774},,,{v:null}]},{c:[{v:new Date(2009,1,25,22,15,3)},,,,{v:143.722595861}]},{c:[{v:new Date(2009,1,25,22,15,4)},,,{v:64.4898008851},{v:null}]},{c:[{v:new Date(2009,1,25,22,15,4)},,{v:222.357617868},,{v:null}]}]}}); Anyways, you can kinda see the data, also note its actually a function call, this stuff is really kinky! Now go to the Google Visualizations Playground and enter in that URL into the sandbox And you can see the visualization itself pop out! (this is just a screen shot so go do it yerself if you want to mess around) OK go mess around, adding and changing bhours and ehours Wrapping up the visualization OK we're nearly done. Now we just need to basically grab the code from the sandbox and make it a subpage in our app engine...like so: class Visualize() historytimebegin = 24 # assume 24 hours if self.request.get('bhours'): historytimebegin = int(self.request.get('bhours')) historytimeend = 0 # assume 0 hours ago if self.request.get('ehours'): historytimeend = int(self.request.get('ehours')) # get the first part, headers, out self.response.out.write( <.load("visualization", "1", {packages: ["annotatedtimeline"]}); function drawVisualizations() { ) # create our visualization self.response.out.write(new google.visualization.Query(" account.email()+&bhours=+str(historytimebegin)+").send( function(response) { new google.visualization.AnnotatedTimeLine( document.getElementById("visualization")). draw(response.getDataTable(), {"displayAnnotations": true}); }); ) self.response.out.write(} google.setOnLoadCallback(drawVisualizations); </script> </head> <body style="font-family: Arial;border: 0 none;"> <div id="visualization" style="width: 800px; height: 250px;"></div> </body> </html>) The first part is pretty straight forward, get the user name or login. Then we will assume the user wants 1 last day of data, so set bhours and ehours. Then we literally just print out the code we copied from Google's Visualization sandbox, done! Viz Viz Viz The only thing I couldn't figure out is how to get 3 visualizations going on at once (last hour, day and week) with the above code. It just kinda broke. So for the triple view I had to use iframes :( class Visualize( <h2>Power usage over the last hour:</h2> <iframe src ="graph?user=adawattz@gmail.com&bhours=1" frameborder="0" width="100%" height="300px"> <p>Your browser does not support iframes.</p> </iframe> <h2>Power usage over the last day:</h2> <iframe src ="graph?user=adawattz@gmail.com&bhours=24" frameborder="0" width="100%" height="300px"> <p>Your browser does not support iframes.</p> </iframe> <h2>Power usage over the last week:</h2> <iframe src ="graph?user=adawattz@gmail.com&bhours=168" frameborder="0" width="300%" height="500px"> <p>Your browser does not support iframes.</p> </iframe> ) Anyhow, it works just fine. Timecodes! The final thing that wont be reviewed here is how I got the date and times to be EST instead of UTC. As far as I can tell, its kind of broken and mysterious. Check the code if you want to figure it out. Step 18: Resources Get) Step 19: Download - Zip file of the most recent python scripts this is what you want if you've built a tweet-a-watt and you want to get your project running - Receiver, connected to computer - Transmitter, embedded in the Kill-a-Watt. Change the unique ID if you have more than one! 21 Discussions 6 years ago on Introduction Cool hacking... I just want to inform you that we also posted your project on our Arduino facebook page...Feel free to join us and answer community questions. Sincerely, Faceuino team 9 years ago on Step 11 My Kill A Watt has its bits behind the LCD screen. (AAARRRRRGGGHHH!!) Apparently its gone thru some kind of revision :( Step 11 My P4400 kill a Watt serial no. YBJA2077 which I purchased a few months back does not have the LM2902 chip any place that I can see it ... so it looks like this project is now a no-go !!! Introduction We built four of these after seeing in MAKE magazine and on Adafruit. Lots of fun. We put one on our office coffee pot to tweet my cell phone when the coffee is ready. See 8 years ago on Introduction Sweet I was unaware I could get a KaW locally, thanks for the heads up! Great 'structable btw ;) 9 years ago on Introduction Hi, very nice and really comprehensive instructable. Is it possible to use this to tweak consumption reading from electric companies? I know aroun here (argentina) thew tweak the turning weel on the meter. Obviously iligal. but just for imformation purpouses. 9 years ago on Introduction Hey, this is a great project, all the instructions are very well explained. I made for only one transmitter, but now I am planning to build several in order to get a better control of my electricity consumption. congratulations 9 years ago on Introduction This is without a single doubt in my mind the best, most creative, and most extensive instructable I have ever seen since first discovering instructables.com! 5 Stars right off the bat and cheers to your hard work, Ladyada! Also like the additional router section (compared to the MAKE article which didn't have it). 9 years ago on Introduction hey, you should make a CD with all the software and coding on it, it might help you sell kits! Reply 9 years ago on Introduction Ha Yeah,He Would Probably Need DVDs To contain all that Data/Programs/Coding/EXT 9 years ago on Introduction This must have taken awhile to write, good job.... 9 years ago on Introduction Very Very good excellent your details your pictures perfect. Congratulations 9 years ago on Introduction Is there a way to wire it (phone line/ethernet) to cut down costs? 9 years ago on Introduction this is still great but have i seen it somewhere before? (this is the original right?) 9 years ago on Introduction awesome. i was totally thinking of doing something like this but i wasent at all sure how with the wireless info to the laptop. but now....... i am informed. and will start this project most likley in the next few weeks. thanks for all your hard work. 9 years ago on Introduction well thats cool 9 years ago on Introduction instead of tweet a watt call it a twat...JOKING..calm down. nice ible 9 years ago on Introduction Great Instructable , I hope i could do things like you : ) Congrats
https://www.instructables.com/id/Tweet-a-watt-How-to-make-a-twittering-power-mete/
CC-MAIN-2018-51
refinedweb
11,884
71.24
source code Python 3 compatibility tools (PRIVATE). We used to have lines like this under Python 2 in order to use iterator based zip, map and filter (in Python 3 these functions are all iterator based): from future_builtins import zip There is no similar option for range yet, other than: range = xrange input = raw_input or: from __builtin__ import xrange as range from __builtin__ import raw_input as input Under Python 3 these imports need to be removed. Also, deliberate importing of built in functions like open changes from Python 2: from __builtin__ import open To do this under Python 3: from builtins import open Instead, we can do this under either Python 2 or 3: from Bio._py3k import open from Bio._py3k import zip Once we drop support for Python 2, the whole of Bio._py3k will go away.
http://biopython.org/DIST/docs/api/Bio._py3k-module.html
CC-MAIN-2018-09
refinedweb
139
65.35
C# Compiler Error Message CS0027 Keyword ‘this’ is not available in the current context Reason for the Error You will receive this error if you use this keyword outside of a property , function or constructor. For example, try compiling the below code snippet. using System; public class DeveloperPublish { public int result = this.Function1(); public int Function1() { return 1; } public static void Main() { Console.WriteLine("Main"); } } You will receive the error “CS0027 Keyword ‘this’ is not available in the current context” because this.Function1() is used in a wrong place. Solution To resolve this error, you’ll need to modify your code so that use of this keyword is moved inside a property, function or even a constructor.
https://developerpublish.com/c-error-cs0027-keyword-this-is-not-available-in-the-current-context/
CC-MAIN-2022-05
refinedweb
117
55.24
gemath: A Python Package for "Good Enough" Array Manipulation and Mathematics This package contains methods and function to conduct some array manipulation, numerical analysis and mathematical calculations that are commonly encountered in the atmospheric sciences. This package can be thought of as a limited API of numerical analysis routines written in Python as well as other packages utilizing compiled code. The current version is. Although there are many packages for using Python for array manipulation and numerical analysis, some problems that arise in using those packages include: (1) not being able to find exactly the routine you want, (2) adequate documentation that tells you how to use the routine, (3) the hassles associated when what you need is spread-out over many different packages that you don't have installed on your system, (4) some of those packages aren't very stable, and so you're not sure if you write code using them whether your code will be usable later on, and (5) some of the packages do not handle missing values. To deal with this situation I've compiled this package of array manipulation and basic numerical analysis tools that have algorithms that are "good enough" to get the job done. This means that they only depend on other packages (there is no called C or Fortran code), that they work, but they are not optimized or tested as rigorously as in a standard library like LAPACK. These routines also enable me write more "portable" code: if I find another module that uses a substantially better algorithm than I've implemented, I can just import and call that module in the code of my gemath routine, without having to change the code of programs that call the gemath routine. Other modules and packages I've written use gemath, which enables those modules to be more stable than might otherwise be the case. This package is meant to be a supplement to existing Python numerics packages, including: FFT, LinearAlgebra, MLab, and RandomArray (all in Numerical Python), and transcendental. Note that I do not access or reference SciPy routines at this time because I've had problems installing them on my machine. "Key" functions can be imported in a few ways. For instance: from gemath import * a = findgen(5). import gemath as G Gto the function name, e.g. a = G.findgen(5). The rest of the functions should be imported explicitly. For instance, to make can_use_sphere, available, use: from gemath.can_use_sphere import can_use_sphere Then can_use_sphere is available without qualifiers, e.g.: Because I've written the package so that each module (besidesBecause I've written the package so that each module (besidesa = can_use_sphere(longitude, latitude) __init__and gemath_version) contains a single public function of the same name as the module, the module listing provides a comprehensive listing of which functions are and are not "key". The package's functions input and output are, in general, Numeric floating point or integer arrays. Most routines allow "missing values" to be included in function input/output, by specifying the argument missing in the calling line. Some, though few, gemath functions will also allow the missing argument to be set to None, and will interpret such a setting as meaning the input does not have missing values. In general, missing should be set to a floating or integer type. algorithm, which allows you to select which algorithm you wish to use. Of course, different algorithms have different names; however, all routines with this option have one algorithm named 'default', which is the default value of the algorithmkeyword. A summary list of bugs and fixes, updates to the package, and a summary of the version history (with links to gzipped tar files of previous releases of the package) is found here. [Back up top to the Introduction.] Here is a list of all key (those which are readily available via a from gemath import * statement) package public functions sorted by function type. See the module listing for an alphabetical sort by name: Numericarray of floating point type. [Back up top to the Introduction.] The module listing section below includes pydoc generated documentation of the modules in the package. The Python interactive help method provides similar functionality: help(gemath): Help for the package. A list of all modules in this package is found in the "Package Contents" section of the help output. help(gemath.M): Details of each module "M", where "M" is the module's name. Example web pages of using gemath functions: The manual has additional details regarding how the classes and functions in this package are structured. Topics include: module unit testing, future work, etc. [Back up top to the Introduction.] All modules in the package are listed below. Each module (besides __init__ and gemath_version) contains a single public function of the same name as the module. The columns contain the following: from gemath import *statement). gemathmodules; if the module has no such dependencies, the column is filled with "None". For a detailed description of the entire package, see the pydoc generated documentation for __init__.py. 1This dependency is required by a subset of options for the module. Default actions of the module will still work without this dependency. [Back up top to the Introduction.] I've only tested gem section above. Python: gemath has been tested on and works on v2.2.2 and 2.3.3. Full functionality of gemath requires the following packages and modules be installed on your system and findable via your sys.path: MA: Masked arrays operations package (v11.2.1 or higher) Numeric: Array operations package (v22.1 or higher) sphere: Python module accessing SPHEREPACK sphere is a contributed package to the Climate Data Analysis Tools (CDAT) suite. Numeric and MA are part of the Numerical Python (Numpy) package. Installation of Numpy is trivial. Installation of CDAT contributed packages, on the other hand, is more difficult (see their web site for details). However, almost all of gemath's functionality only requires Numpy. See the module list for information regarding dependencies for each module. Package gemath itself is written entirely in the Python language. First, get the following file: Expansion of the tar file will create the directory gemath-0.1.1. This directory contains the source code, the full documentation (HTML as well as images), a copy of the license, and example scripts. To unzip and expand the tar file, execute at the command line: gunzip gemath-0.1.1.tar.gz tar xvf gemath-0.1.1.tar There are a few ways you can install the package. For all these methods, first go into the gemath-0.1.1 directory: This will install the packageThis will install the package python setup.py install gemathin the default site-packages directory in your default Python. You'll probably need administrator privileges, however, in order to do this install. This will install the packageThis will install the package python setup.py install --home=~ gemathin the directory ~/lib/python/gemath (where ~ means your home directory). However, you'll need to make sure ~/lib/python is on your path. import gemathcommand only looks for a directory named gemath on your Python path and executes the __init__.py file in it. Of course, you'll have to make sure the directory gemath is in is on your path. WhereWhere import sys sys.path.append('newpath') 'newpath'is the full path of the location you're appending to your Python path. Thus, if the directory gemath is in a directory /home/jlin/lib/python, 'newpath'is '/home/jlin/lib/python'. You can automate this by making the proper settings in a user customized .pythonrc.py file. That's it! The gemath-0.1.1 directory contains a complete copy of the documentation for the package, including images. Keep this directory around (you can rename it) if you'd like to have a local copy of the documentation. The front page for all documentation is the doc/index.html file in gemath-0.1 the LGPL disclaimers of warranty supercede and replace any implied or explicit warranties or claims found in the text of the routine source code.A copy of the GNU LGPL can be found here. Please note that the LGPL disclaimers of warranty supercede and replace any implied or explicit warranties or claims found in the text of the routine source gem.]
http://www.johnny-lin.com/py_pkgs/gemath/doc/
crawl-002
refinedweb
1,393
55.24
H&R Block Ch 27 Final Exam Review What income reporting form should an independent contractor sometimes receive from the person who paid him for his services? Form 1099-MISC (15.6) Schedule C, Line F asks for the accounting method used in the business. What is the difference between the cash method and the accrual method of accounting? • Under the accrual method, total sales and total charges for services are included in income even though payment may be received in another tax year. • Under the cash method, only income actually received or expenses actually paid during the year are included. (15.5) What does it mean if a proprietor "materially participates" in the business? He is active in running the business in a substantial way on a day-to-day basis. (15.5) Why is it important to know whether or not the proprietor materially participates? If the proprietor does not materially participate, any loss from the business is a passive loss and generally may be currently deducted only against passive income. (15.6) What are returns and allowances? • Amounts that were refunded to customers who returned merchandise for refund or partial refund. • These amounts are subtracted from gross receipts. (15.6) How is cost of goods sold determined? Beginning inventory plus purchases, plus labor, supplies, depreciation, etc. attributable to product manufacture or preparation for sale, minus ending inventory. (15.7) If the client has contract labor, what should you remind the client that they should do? • Provide a Form 1099-MISC to any independent contractor who worked and earned $600 or more. (15.9) What amounts does a proprietor have "at risk"? Amounts invested in the business plus any business debts for which the proprietor is personally liable. (15.16) What difference does it make if the proprietor is "at risk" or not? Only amounts at risk may be used to determine the actual loss on Schedule C. (15.16) How does a Tax Professional meet due diligence requirements? • Tax Professionals fulfill due diligence requirements by making every effort to prepare accurate and complete returns. • Tax Professionals must have knowledge of tax law, and apply a reasonability check to the information provided by their clients. (26.1) What is a thorough interview? A thorough interview consists of asking general information questions, then asking additional questions whenever information is incomplete or seems inaccurate or inconsistent. (26.2) What is a conflict of interest? A conflict of interest is when one's situation might benefit at the expense of another's situation. (26.3) What actions can resolve a conflict of interest? A conflict of interest is resolved when it is acknowledged, disclosed to all parties, and the parties have consented to waiving the conflict. (26.3) What client information is confidential? Any information that could potentially identify the client is confidential. Information includes (but is not limited to): • Name • Address and phone number • Social security numbers • Place of employment • Any information from a tax return (26.4) Is it acceptable for a Tax Professional to leave a detailed phone message for a client, letting them know their tax return is complete? • Tax Professionals must have prior consent from the client to leave phone messages related to their tax return. • The fact that a taxpayer is the client of a Tax Professional or tax preparation business is confidential information that must not be disclosed. (26.5) What is a Tax Professional's responsibility upon finding out that a client has not complied with any tax law? A Tax Professional must advise the client of the noncompliance and the consequences for not correcting the situation. (26.7) What action should a Tax Professional take if a client insists on reporting information that is inaccurate? A Tax Professional should never prepare a return that contains inaccurate information. (26.7) If the employee thinks his Form W-2 is not correct, what should he do? • If the name or social security number is incorrect, the taxpayer may change it himself and need not obtain a corrected W-2 before filing his tax return. • The employer should be notified of the error and asked to update his records. • Furthermore, the employee's social security number and earnings records should be verified with the Social Security Administration to ensure that the earnings were properly credited. (2.17) Where can the regular standard deduction amounts be found? • In the left-hand margin at the top of page 2 of Forms 1040 and 1040A. • They are: S, MFS $5,700; MFJ, QW $11,400; HH $8,400. • The amounts differ for taxpayers age 65 or older or blind and those who may be claimed as dependents by other taxpayers. [2010] What is the exemption amount for 2009? $3,650 with a reduction for higher-income taxpayers of 2% for each $2,500 ($1,250 MFS) the AGI exceeds amounts: $166,800 S $250,200 MFJ QW $125,100 MFS $208,500 HH (3.7,8) Are early distributions from qualified retirement plans always penalized? No. • Does not apply to qualified disaster recovery assistance distributions. • Does not apply to any recovery of cost or any amount rolled over in a timely manner. (22.12,13) How does a Tax Professional know if a distribution exception applies? • He can determine that by using thorough interview questions when discussing the distribution with the client. • The distribution code on the 1099-R can also be helpful to the Tax Professional. (22.12) Is there a time limit for filing amended returns? Yes. Three years from the date the return was filed or within two years the tax was Any refund will be limited to $280 (the tax paid within the two years preceding the date the amended return was filed). (23.3) What are the rules for changing filing status after the due date of the return? Married couples may not change their filing status from MFJ to MFS after the due date. (23.4) A taxpayer's employer paid $500 of a taxpayer's $2,000 child care expenses for him. How will the employer's assistance affect the child-care credit? Total child care expenses must be reduced by any amounts paid by the employer. (8.11) Where does the employer report the amount of child care expense assistance to the taxpayer? Form W-2 Box 10 (8.11) What is the maximum amount of contributions on which the Saver's Credit may be based? $2,000 per individual or spouse (21.19) What are the rates for the Saver's Credit? The rates are 10%, 20%, or 50%, depending upon filing status and modified AGI. (21.17) A taxpayer is building a new home and had a solar water heater installed in 2009, but the home was not ready to be occupied until early 2010. Can they take the residential energy credit? Yes, they can take the credit on their 2010 tax return. (8.21) How much may an eligible educator deduct for qualified classroom expenses as an adjustment to income? Up to $250 (11.4) Who may not claim a student loan interest deduction? Someone who is claimed as a dependent may not claim the deduction in the current tax year, nor may someone who uses the married filing separately filing status.(11.8) What is a qualified student loan? • Any type of loan used to pay qualified expenses. Credit card debt may be included, provided the card was used exclusively to pay for qualified expenses. • Money borrowed from a related person is not a qualified student loan. (11.5) What are qualified medical expenses with regards to an HSA? Unreimbursed medical expenses that would normally be deductible on Schedule A (11.16) What form is used to report HSA contributions and determine any allowable deduction? Form 8889. Reported on Form 1040 Line 25. What is a qualified retirement plan? A plan which is eligible for favorable tax treatment because it meets the requirements of IRC §401(a) and the Employment Retirement Income Security Act of 1974 (ERISA) (21.2) What is the 2009 contribution limit to 401(k) plans? • The maximum contribution for 2009 is $16,500 (and 2010). • Taxpayers age 50 and above are allowed a $5,500 annual "catch-up" contribution. (21.4) What is it called if a taxpayer takes money out of one IRA and puts it into another (and all requirements are met)? Roll-over. What is the last date on which a contribution may be made and qualify as a contribution for a given year? The due date (not including extensions) of the return for that year. Why is it important to distinguish between taxpayers who are active participants in an employer-maintained retirement plan and those who are not? • Those who are not active participants and whose spouses are not active participants may deduct the full amount they contribute to a traditional IRA, assuming they stay within the contribution limits. • Those who are active participants or whose spouses are active participants may still contribute within the limits but may find their allowable deduction reduced or eliminated. (21.13) What are the main differences between traditional IRAs and Roth IRAs? • Contributions to a Roth IRA are never deductible, but qualified distributions are exempt from tax. • Participation in an employer-maintained retirement plan has no effect on Roth IRA contributions, and contributions can be made after the taxpayer has reached age 70½. • As long as they have compensation, contributions to Roth IRAs are not reported on the tax return. (21.15) Under what circumstances do you need to determine whether a taxpayer paid over half of the cost of maintaining his home? If you are determining if the taxpayer may be considered unmarried, a qualifying widow(er), or head of household. (5.2) What are some of the costs of maintaining a home? • Rent • Mortgage interest • Real Estate Taxes • Homeowners Insurance • Property Taxes • Repairs • Utilities • Food eaten in the home (5.3) What requirements must be met for a taxpayer to use the qualifying widow(er) status? • The death of the taxpayer's spouse must have occurred during one of the two preceding tax years; • The taxpayer must not have remarried and must have been entitled to file a joint return for the year of death. • The taxpayer must have paid over half the cost of maintaining the home which, for the entire year, was the main home of their dependent son, daughter, stepson, or stepdaughter. In general, which parent gets to claim the qualifying child in a divorce? The custodial parent. (5.7) What is the exception to the custodial parent qualifying child rule? • If a decree of divorce or separate maintenance or written separation agreement that became effective after October 4, 2004, states that the noncustodial parent is entitled to claim the child's dependency exemption, or if the custodial parent executes a written declaration that they will not claim the child as a dependent for that year, the noncustodial parent may claim the qualifying child. • For divorces granted after December 31, 2008, Form 8332 must be filed if parents are separating tax benefits. (5.7) What's the difference between a withholding allowance and an exemption? • A withholding allowance is reported on Form W-4 and is used to accurately calculate the amount of tax to be withheld from an employee's wages. • An exemption is claimed on the tax return for the taxpayer, spouse, and each dependent. (24.) Under what circumstances may an employee claim exemption from withholding? Only if the employee had no federal income tax liability for the prior year and he expects to have no tax liability for the current year. (24.) A single self-employed taxpayer estimates that his 2009 tax will be $7,500. His 2008 tax was $7,000. How much must he prepay for 2009 in order to avoid an underpayment penalty? $6,750; the lesser of 90% of his 2009 tax [$7,500 X 90% = $6,750] or 100% of his 2008 tax ($7,000). (24.) What information do you need to know to determine whether a return is required? • Marital Status • Age & Student Status • Gross Income • Over 65 and Blindness • Dependent Status (3.2) For tax purposes, when is a person's marital status determined? On the last day of the tax year. (3.2) What two amounts combine to make up the gross income filing requirement for most taxpayers? The Standard Deduction and the Personal Exemption amounts. (3.7) How much is added to the standard deduction if the taxpayer (or spouse) is age 65 or older or blind? $1,400 per condition for S and HH $1,100 per condition for MFS, MFJ and QW (3.6) If one spouse refuses to file a joint return, can the other spouse do anything about it? No Both will have to file using the married filing separately status unless one or both qualifies to be considered unmarried. What kinds of property may be expensed using the Section 179 deduction? New or used tangible personal property (usually equipment or office furniture) purchased for use in a trade or business. (17.2) How is the MACRS deduction computed in the year of disposition for property being depreciated using the half-year convention? HALF of the normal depreciation is allowed. (17.9) How is the MACRS deduction for the year of disposition computed if the property is being depreciated using the mid-quarter convention? Depreciation for the entire year, multiplied by a PERCENTAGE for quarter of disposition: 12.5% First 37.5% Second 62.5% Third 87.5% Fourth (17.9) What special treatment is available to self-employed taxpayers with regard to health insurance premiums they pay? They may deduct their premiums as an adjustment to income, if they qualify. (17.17) Carol has a home office. When she is not using the office, she lets her children play video games on an old television she keeps there. Can Carol deduct home-office expenses? No. The space must be used exclusively for the business. (17.21) An employee has an office where he works, but his work load demands that he bring home work on evenings and weekends. He uses a room of his home regularly and exclusively for his work. May he deduct home-office expenses? No, the employer provides a work office. (17.23) What activities are considered farming activities? • Cultivating land, operating dairy farms, fruit farms, nurseries, orchards, poultry farms, fish farms, plantations, ranches, stock farms, truck farms;breeding and raising fur-bearing animals or laboratory animals. • Does NOT include breeding, raising dogs, cats or pets. (17.28) Matthew breeds Cocker Spaniels for sale as pets. What schedule will Matthew use to determine his profit or loss? Schedule C (17.28) What are some general types of itemized deductions that are subject to the 2%-of-AGI floor? • Transportation Expenses • Education Expenses • Job-Seeking Expenses • Tax Preparation Fees • Investment Expenses • Hobby Expenses (13.9) What are some miscellaneous itemized deductions that are not subject to the 2%-of-AGI limitation? • Gambling Losses • Impairment-Related Work Expenses • Federal Estate Tax • Unrecovered cost of a decedent's Pension or Annuity • Repayments of certain income more than $3,000 • Casualty and theft losses from income-producing property • Amortizable bond premiums (13.18) At what amount must interest income be reported on Form 1040, Schedule B? When the total taxable interest exceeds $1,500 (6.2) Is interest received on U.S. Treasury Obligations taxable on state and /or local returns? No. Interest on U.S. Treasury Obligations is exempt from state and local tax by federal law. (6.8) What types of taxpayers will require the Qualified Dividends and Capital Gain Tax Worksheet - Line 44? • Taxpayers who receive Form 1099-DIV showing that they received qualified dividends must use the Qualified Dividend and Capital Gain Tax Worksheet—Line 44. • Also, those taxpayers who have capital gain distributions shown in box 2a of Form 1099-DIV will use the worksheet. (6.14) What form is used to request a six-month extension to file? Form 4868 Application for Automatic Extension of Time to File US Individual Income Tax Return (25.2) If a taxpayer is anxious to e-file their return in January, can they do so without Form W-2, as long as they have their last paystub? • No, they must wait until February 15. • The IRS will not accept returns with substitute W-2s prior to February 15. (2.23) What is the basis of purchased property? Cash paid plus the fair market value of services rendered plus the fair market value of property traded. Certain closing costs are added to the basis. (20.4) What is the maximum net capital loss that a taxpayer may deduct in one year? $3,000 ($1,500 MFS) (20.11) The top marginal tax rate for 2009 is 35%. For most capital assets sold during 2009, what is the maximum tax rate for long-term capital gains? 15% or 0% for taxpayers in the 10% and 15% brackets. Some long-term capital gains are taxed at other rates. (20.9) When is the American Opportunity Credit (AOC) available? Under current law, the AOC is available only for tax years 2009 and 2010. (9.8) What effect do tax-free funds (such as grants) have on qualifying expenses for the AOC? Expenses must be reduced by those amounts. (9.6) How is the lifetime learning credit calculated? 20% of the first $10,000 of qualifying expenses per return, per year. (9.17) What is the maximum tuition and fees deduction? $4,000 for taxpayers with modified AGIs up to $65,000 ($130,000 MFJ), or $2,000 for taxpayers with modified AGIs between $65,001 and $80,000 ($130,001 and $160,000 MFJ). (9.18) What are the six tests for a qualifying child? • Relationship • Age • Residency • Support • Joint Return • Special Test (4.2) How can a married individual meet the joint return test to remain a qualifying child? They can meet this test by not filing a joint return with their spouse, or they can file a joint return with their spouse if they are filing only to claim a refund of any taxes withheld. (4.4) How can you determine who paid more than half of the person's support? Total support is determined and reduced by the funds received by and for the person from all sources other than the taxpayer. The remaining support is considered to be provided by the taxpayer. (4.9) What additional requirements must be met by a qualifying child for purposes of the Child Tax Credit? • Must be under age 17 • Must be claimed on taxpayer's return • Must be a US citizen, US national or resident of the US. (4.15) What is the purpose of the alternative minimum tax (AMT)? The purpose of the alternative minimum tax is to make sure that taxpayers with higher incomes cannot entirely avoid taxes through the use of certain deductions and credits. (22.2) In what way is a clergy member's compensation treated differently from compensation of other employees? Compensation of clergy members is subject to self-employment tax instead of social security and medicare tax withholding. (22.5) Under what circumstances are tips not subject to social security and medicare taxes? Tips totaling less than $20 in a calendar month are not subject to these taxes. Also, if the taxpayer has already paid the maximum social security tax for the year, further tips are not subject to social security tax. (22.11) Under what circumstances is Form 4137 prepared? Only if the taxpayer did not report tips to his employer as required, or if he is reporting allocated tips. (22.9) What form is used to report household employment taxes? Schedule H, Household Employment Taxes is filed to report household employment taxes paid. The calculated amount is then carried to Form 1040, line 59. (22.17) Who may qualify for the Additional Child Tax Credit? • Taxpayers with earned income in excess of $3,000 for 2009. • Those with three or more qualifying children for child tax credit purposes, whose child tax credit was limited by their tax liabilities.. (7.3) Kris (26) has an earned income and AGI of $9,256. He has no other income. He lived in the United States all year and is no one's dependent. He has a valid SSN and is filing as single. He is a U.S. citizen. Does Kris qualify for EIC? Yes. His Earned Income is under $13,440 (7.5) What is the possible penalty for failing to comply with the EIC due diligence rules? $100 fine for each occurrence (7.15) What happens if an individual is a qualifying child for more than one taxpayer? The taxpayers may decide among themselves who will claim the credit. (7.9) What happens when more than one taxpayer claims the same qualifying child? The IRS will decide based on the tiebreaker rules. (7.9) How does one determine the taxable income of the taxpayers who itemize deductions? Adjusted gross income (AGI) minus total itemized deductions and total exemptions. (12.2) What types of taxes are deductible? • State and local taxes • Real property taxes • Personal property taxes • Foreign income taxes (12.12) A taxpayer makes his final 2008 state estimated tax payment on January 15, 2009. Where should he report this item? It is included on his 2009 Schedule A, line 5. This payment also should have been included on the estimated payments line of his 2008 state return. Why is it important to distinguish qualified home mortgage interest from personal interest? Mortgage Interest is deductible, Personal Interest is not. (12.20) Is the cost of items purchased to benefit a charitable organization deductible, for example, ballet tickets to raise money for a non-profit hospital? Only the amount paid in excess of the value of the item is deductible. (12.27) A taxpayer wrote a check for a $500 donation to his mosque. Is his cancelled check sufficient documentation to support his deduction? No. Donations of $250 or more must have written substantiation from the donee. (12.29) Are scholarships and fellowships taxable? • If a W-2 is received it is FULLY taxable. • Amounts to Non-degree candidates are FULLY taxable and reported on Line 7 marked "SCH" • Amounts to Degree candidates spent for qualified expenses are NOT taxable. (18.5) Under what circumstances are gross gambling winnings taxable? Always. Gambling losses may be deductible up to the amount of winnings. (13.18) What document will the taxpayer receive from their employer reporting their disability pension? 1099-R (18.8) How can a disability pension qualify as earned income for the EIC? We've learned pensions are not earned income. Before the taxpayer reaches minimum retirement age, it's considered earned income (18.11) What pensions are fully taxable? Those to which the taxpayer DID NOT make after-tax contributions or from which all pre-tax amounts have been recovered in previous years. (10.8) Under what circumstances would a pension be partly taxable? When it's funded through employer plans to which the employee contributed some after-tax money. (10.9) When would a traditional IRA distribution be partly taxable? If nondeductible contributions had been made, Form 8606 is used to compute the taxable portion. (10.16) Where is income tax withheld from a pension or IRA distribution reported on the tax return? Form 1040 Line 61 (10.10) What does it mean to depreciate an asset? To reduce the basis of a business asset allowing for the reasonable wearing out over a period of years. (16.1) What kind of property is depreciable? Business-use property with a useful life of more than one year. (16.2) Ho do we determine the MACRS recovery period of a piece of personal property? By using the Table of Asset Class Lives and Recovery Periods (16.3) For MACRS purposes, we need to divide real property into two categories. What are they? Residential and Nonresidential (16.7) How is residential real property, such as a rental house or apartment building, depreciated under MACRS? Using a straight-line method over 27½ years. What are some examples of listed property? • Most passenger automobiles under 6,000 pounds and any property used for transportation. • Property used for entertainment, recreation or amusement. • Computers and related equipment unless used exclusively at a business. • Cellular phones. (16.17)
http://quizlet.com/2823131/hrb-27-final-exam-review-flash-cards/
CC-MAIN-2015-11
refinedweb
4,086
57.27
CodePlexProject Hosting for Open Source Software Hey! I have used UI Spy work myself down in the client im working with, buried deep within panels and other controls rests an EDIT control, I have checked the mapping and it's a textbox so thats cool. Is there anyway I can work myself down through this structure... using White? Or how should i tackle this problem? AutomationID is same for all four textboxes, there is a localized controltype, name is empty though I now the name from debugging in runtime. How should i go about to let white enter data into the textbox? Hi in general it is an good idea to get all visible elements in the tree starting from the top (the window in most cases). has all Textboxes the same parent? Throndorin Okay I think I grasped everything now. We have a very complex tree structure buidling up our surface. Thing is that on the lowest lvl our dynamicly created textbxoes have the same automationID, so in order to get the correct one I have to grab the correct textbox by going backwards in the tree structure. IUIItem item8 = win2.Get(SearchCriteria.ByAutomationId("BRANCHWITHCORRECTTEXTBOXIN")); So far so good then I perform a and here's the return type AutomationElement?? Which in turn does not have the functions fo enter(), click(). How should I go about to enter data into the textbox? AutomationElement correcttextbox = item8.GetElement(SearchCriteria.ByAutomationId("Txt_TextBox")); some possible solutions/ideas: if the application under test is WPF: using White.Core.UIItems.WPFUIItems; using White.Core.UIItems.WPFUIItems; now Get<> and Get is available on each White Item you can also create a TextBox (or other White elements) AutomationElement correcttextbox = item8.GetElement(SearchCriteria.ByAutomationId("Txt_TextBox")); Textbox box = new TextBox(correcttextbox, item8.ActionListener); Hope that helps. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://white.codeplex.com/discussions/362096
CC-MAIN-2017-34
refinedweb
334
67.35
The official source of information on Managed Providers, DataSet & Entity Framework from Microsoft The information in this post is out of date. Visit msdn.com/data/ef for the latest information on current and past releases of EF. For Code First Migrations see We have released the first preview of our migrations story for Code First development; Code First Migrations August 2011 CTP. This release includes an early preview of the developer experience for incrementally evolving a database as your Code First model evolves over time. Please be sure to read the ‘Issues & Limitations’ section of the announcement post before using migr. public class Person { public int PersonId { get; set; } public string Name { get; set; } public string Email { get; set; } }. What Changes Can Migrations Detect Automatically? In this section we looked at adding a property, here is the full list of changes that migrations can take care of automatically: So far we have looked at changes that migrations can infer without any additional information, now let’s take a look at renaming properties and classes. public class Person { public int PersonId { get; set; } public string Name { get; set; } public string EmailAddress { get; set; } } The renames parameter is a comma separated list of renames and can include class and property renames. Class renames use the same format as property renames i.e. –Renames:”Person=>Customer”. Up until now we’ve let migrations take care of working out what SQL to execute. Now let’s take a look at how we can take control when we need to do something more complex.. public class Person { public int PersonId { get; set; } public string EmailAddress { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } ; ) NULL; )) ; GO Run the ‘Update-Database’ command to bring the database up to date With our custom script complete we can go back to using the automatic upgrade functionality, until we find the need to take control again. Migrations allows you to swap between automatic upgrade and custom scripts as needed. The Source.xml file associated with each custom script allows migrations to reproduce the same migration steps we have performed against other databases. So far we have only made changes that avoid data loss but let’s take a look at how we can let an automatic migration execute even when it detects that data loss will occur. public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } In this walkthrough we saw an overview of the functionality included in the first preview of Code First Migrations. We saw automatic migrations, including property and class renames as well as migrating with data loss. We also saw how to use custom scripts to take control of parts of the migration process. We really want your feedback on what we have so far so please try it out and let us know what you like and what needs improving. Rowan Miller Program Manager ADO.NET Entity Framework
http://blogs.msdn.com/b/adonet/archive/2011/07/27/code-first-migrations-walkthrough-of-august-2011-ctp.aspx
CC-MAIN-2016-07
refinedweb
497
57.61
Hi everyone First post but I have been browsing as a guest for help with my university python project for a while now. There some really great help on here, Thank you! Right I'm doing a beginners python programming unit as part of my uni course, and as part of that unit I have to do a project. This project being to create a pyramid consisting of 2 different "Patches" if you like, if you take a look below you can see on of the "patches" is finished (nestedCircles()), but as for the other "patch" (Diamonds()) I just cant work out how to do it, this is an example of the patch I have to do:-[IMG][/IMG] from graphics import * def nestedCircles(): win = GraphWin("Circles", 100,100) yValue = 51 centre = Point(51.47,yValue) radius = 50 circle1 = Circle(centre, radius) circle1.draw(win) for i in range(10): radius = radius - 5 yValue = yValue + 5 centre = Point(50,yValue) circle1 = Circle(centre, radius) circle1.draw(win) nestedCircles() def diamonds(): win = GraphWin("Lines", 100,100) yValue = 20 line1 = Line(Point(200,200), Point(900,900)) line1.draw(win) for i in range(9): line1 = Line(Point(90,10), Point(5,3)) line1.draw(win) Any help with this would be soo gratefully received, don't forget I have only been doing python for 2 months now! :) Regards Joe
https://www.daniweb.com/programming/software-development/threads/277715/using-python-graphics-module
CC-MAIN-2018-47
refinedweb
228
66.67
Created on 2011-09-24 22:07 by zbysz, last changed 2018-07-25 15:24 by berker.peksag. This issue is now closed. COLUMNS is a shell variable (updated whenever the window size changes), that usually isn't exported to programs. Therefore checking for COLUMNS in sys.environ will not work in the majority of cases. The proper check is to use the TIOCGWINSZ ioctl on stdout. Why COLUMNS is not exported? Because it can change during the lifetime of a program. Therefore it is better to use the dynamic ioctl. I see that adding a separate module was proposed in issue #8408, which was rejected/closed. I don't have the rights to reopen, so I'll continue here. #8408 was proposing a new module, which seems a bit overkill, since the implementation for unix and windows is about 20 lines. I'm attaching a second version of the patch which works on windows (tested with python3.2.2 on XP). Thanks to techtonik for pointing to a windows imlementation. > #8408 was proposing a new module, which seems a bit overkill If a module seems overkill, then maybe add this useful function to os module. Don't leave it private to argparse module. Maybe something along these lines: >>> import os >>> print(os.get_terminal_size()) (80, 25) Why do I believe a module could be better? Because I'd also like some way to detect when the terminal size has changed (without probing it all the time). I'd feel more comfortable with the argparse fix if it were simply calling "os.get_terminal_size()". I recommend that you: * Create a new issue called, say "add os.get_terminal_size()" proposing just the single method. * Add that issue to the Dependencies of this issue. Once that is fixed, then the argparse fix should be simple. Issue #13609 created, but I don't have permission to edit the dependencies. New version to use after #13609 is implemented: patch2.diff OK, I guess that this could now be closed, since 13609 has been commited. (It is currently reopened, but the proposed tweaks wouldn't influence the usage in argparse, even if accepted). I'm attaching a patch which updates the tests to the new $COLUMNS logic. Previously, unsetting COLUMNS would fix the width on 80, now setting COLUMNS=80 is the proper way to do this. @Paul the attached patch is extremely simple and follows the work on #13609. Is it okay with you if the patch was committed? The latest patch, using _shutil.get_terminal_size(), looks fine. It lets environ['COLUMNS'] have priority over the end user's terminal width, as demonstrated by the change to test_argparse. test_argparse doesn't test changing the actual terminal size, but I imagine that would be a pain to implement. For now the user could add this to his module: import os, shutil os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns) What's holding up the merging of this patch? New changeset 74102c9a5f2327c4fc47feefa072854a53551d1f by Berker Peksag in branch 'master': bpo-13041: Use shutil.get_terminal_size() in argparse.HelpFormatter (GH-8459)
https://bugs.python.org/issue13041
CC-MAIN-2020-45
refinedweb
508
68.36
Subject: Re: [boost] [next gen future-promise] What to call the monadic return type? From: Rob Stewart (rob.stewart_at_[hidden]) Date: 2015-05-25 08:27:27 On May 25, 2015 5:37:26 AM EDT, Niall Douglas <s_sourceforge_at_[hidden]> wrote: > > My final design is > therefore ridiculously simple: a future<T> can return only these > options: > > * A T. > * An error_code (i.e. non-type erased error, optimally lightweight) > * An exception_ptr (i.e. type erased exception type, allocates > memory, you should avoid this if you want performance) > > In other words, it's a fixed function monad where the expected return > is T, and the unexpected return can be either exception_ptr or > error_code. The next gen future provides Haskell type monadic > operations similar to Boost.Thread + Boost.Expected, and thanks to > the constexpr collapse this: > > future<int> test() { > future<int> f(5); > return f; > } > test().get(); > > ... turns into a "mov $5, %eax", so future<T> is now also a > lightweight monadic return transport capable of being directly > constructed. > > In case you might want to know why a monadic return transport might > be so useful as to be a whole new design idiom for C++ 11, try > reading >. Make the examples in that correct WRT shared_ptr. As written, the shared_ptrs will delete file handles rather than close them. > However, future<T> doesn't seem named very "monadic", so I am > inclined to turn future<T> into a subclass of a type better named. > Options are: > > * result<T> > * maybe<T> > > Or anything else you guys can think of? future<T> is then a very > simple subclass of the monadic implementation type, and is simply > some type sugar for promise<T> to use to construct a future<T>. The idea has merit, but I have some concerns. The best practice you've linked states that there are problems with Boost.Threads' expected type, but you only mention compile times specifically. I'd like to better understand why expected cannot be improved for your case. That is, can't expected be specialized to be lighter for cases like yours? Put another way, I'd rather one type be smart enough to handle common use cases with aplomb than to have many specialized types. I realize that doesn't solve your immediate need, but you have your own namespace so you can just create your own "expected" type until the other is improved. Then, if improvement isn't possible, you can explore another name for your expected type. ___ Rob (Sent from my portable computation engine) Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2015/05/222627.php
CC-MAIN-2019-47
refinedweb
441
65.01
So many times as a web app developer I've been curious about the desktop landscape. My day-to-day work is completely reliant on desktop apps on MacOS. It would be great to be able to quickly make high quality desktop apps. Unfortunately, at least in my experience, every time I try to get a feel for the technologies in desktop app development I'm left frustrated. There are some solid technologies like Java and C# that offer a pretty nice setup, but good luck making something engaging for the user. MacOS offers Cocoa/Objective C and Swift which is nice. But now you are mostly stuck with an interface builder and constantly jumping back and forth tying UI code to app code. Also, all this is fine but what if you want to build once but deploy to all major OS's? It is just... frustrating. Maybe it is my personal expectations on what coding something should feel like but the options are kind of a let-down. This all led me back to electron. I say "back" because it isn't completely new. And I'm sure you have heard the debates on electron based apps. But in 2021 being able to pair something like Vue or React with Tailwind CSS gives me something to get excited about. Hot module replacement, lightning fast dev builds, familiar technologies... Now I can put more energy into the app's code instead of some clunky work-flow. Let's dive in. installation We are going to do this in a few parts. At its heart this setup is just a web app. By now I'm sure that you have heard the debates on making desktop apps with web technologies. Honestly, this post isn't trying to answer to that. There is no right answer. If you clicked through to read this then you have some interest in the stack, so let's build something cool. Vue via Vite We'll start by using Vite to install Vue as the base of our app. ➜ yarn create @vitejs/app Run through the prompts and pick vue as the template to use and name it vvte-qs. This will create the template to start the project with. After that is done make your project the working directory, run yarn to install all dependencies and run the "dev" script to run the project in dev mode: cd vvte-qs && yarn && yarn dev You should end up seeing something either identical or very similar to this: If we go the browser and go to localhost:3000 we should see: Perfect! That was easy. A Tailwind UI Now that we have base for our app, let's bring in Tailwind CSS to build the UI. I personally am always underwhelmed with UI offerings for native app development. It is so hard to find a package that you are going to want to invest in that won't result with a UI that looks like a CS 101 project. Ultimately what I want in a UI framework/library is a programatic approach with the ability to make something that looks really cool. Having a separate piece of software to build out the UI and then stitch things together with code is a real bummer to me. For something like game development, I get it. How else would you do that. But for application development, it is just too much. Say what you will about CSS/HTML but it is actually pretty great at making it easy to build out a UI. Enter Tailwind CSS. What I love about Tailwind is it leverages the component based UI architecture we will be building in Vue. You can build out some really engaging work by just putting Tailwind classes directly in your HTML. It will really encourage you to keep things DRY by reusing entire components instead of CSS classes. It is great. To add Tailwind as a dependency: ➜ yarn add --dev tailwindcss@latest postcss@latest autoprefixer@latest @tailwindcss/jit Next, generate your tailwind.config.js and postcss.config.js files: ➜ npx tailwindcss init -p We'll need to add the following to the postcss.config.js to get all the Tailwind JIT benefits: // postcss.config.js module.exports = { plugins: { '@tailwindcss/jit': {}, autoprefixer: {}, } } And then the following to the purge property in the tailwind.config.js config to purged what is unused from the build: // tailwind.config.js module.exports = { purge: [ './public/**/*.html', './src/**/*.{js,vue}', ], theme: { // ... } // ... } We are going to need a place to import tailwind into our app: ➜ touch src/assets/index.css Then open the file and add: @tailwind base; @tailwind components; @tailwind utilities; Save that and include your css in your main entry point for main.js. import { createApp } from 'vue' import App from './App.vue' import './assets/index.css' createApp(App).mount('#app') Now if you we run: ➜ yarn dev we get: Pretty underwhelming? Ha, well you are right. Tailwind is a utility UI tool so we are going to have to utilize its classes to see all it can do. Summary Now we have a great base to start our app. Nothing really custom yet, but we'll get to that. Discussion (0)
https://dev.to/douggrubba/desktop-development-for-the-web-developer-part-1-48an
CC-MAIN-2021-31
refinedweb
870
73.68
How to Listen to a Keyboard in Java "Key listeners" in the Java programming language are triggered when you press or release a keyboard key. Keyloggers use key listeners to store the input each time the user presses a key. Programmers use key listener events to detect when a user types an incorrect character, such as by typing a letter in a text box that requires the user's phone number. Using the key listener you can alert the user to the incorrect character before he submits the form. Instructions - 1 Right-click the Java file you want to edit and select Open With. Click the Java compiler in the list of programs to load the code in the editor. - 2 Include the listening class libraries available in Java. Copy and paste the following code to the top of your Java source code file: import java.awt.*; import java.awt.event.*; - 3 Create the function that takes action when the user presses a key. In this example a message is sent to the Java form to display feedback for the user: public mylistener(String key ) { l1 = new Label ("Key Pressed!" ) ; } - 4 Link the key listener function to the Java form. Type the following code to add the listener to key events on your form: addKeyListener ( this.mylistener ) ;
http://www.ehow.com/how_10054085_listen-keyboard-java.html
crawl-003
refinedweb
217
62.17
Thanks Lucas, this makes sense. There is something that this patch is fixing and I'm not sure why. Maybe someone can shed some light: Advertising Using datapath from OVS master, and a setup where we have a physical interface connected to an OVS bridge (br-ex) connected to another OVS bridge (br-int) through a patch port, there's a lot of retransmissions of TCP packets when connecting from the host to a VM connected to br-int. The retransmissions seem to be due to a wrong checksum from the VM to the host and only after a few attempts, the checksum is correct and the host sends the ACK back. The packets I am sending using netcat are very small so there shouldn't be a problem with the MTU. However, could it be a side effect of this patch that the checksum gets now correctly received at the host? As a side not: if instead from connecting to the VM from the host I do it from a namespace where I have an OVS internal port connected to br-ex, then I don't see the checksum problems. Acked-by: Daniel Alvarez <dalva...@redhat.com> Tested-by: Daniel Alvarez <dalva...@redhat.com> On Thu, May 17, 2018 at 1:27 PM, <lucasago...@gmail.com> wrote: > From: Lucas Alvares Gomes <lucasago...@gmail.com> > > The commit [0] partially fixed the problem but in RHEL 7.5 neither > .{min, max}_mtu or 'ndo_change_mtu' were being set/implemented for > vport-internal_dev.c. > > As pointed out by commit [0], the ndo_change_mtu function pointer has been > moved from 'struct net_device_ops' to 'struct net_device_ops_extended' > on RHEL 7.5. > > So this patch fixes the backport issue by setting the > .extended.ndo_change_mtu when necessary. > > [0] 39ca338374abe367e28a2247bac9159695f19710 > --- > datapath/vport-internal_dev.c | 4 +++- > 1 file changed, 3 insertions(+), 1 deletion(-) > > diff --git a/datapath/vport-internal_dev.c b/datapath/vport-internal_dev.c > index 3cb8d06b2..16f4aaeee 100644 > --- a/datapath/vport-internal_dev.c > +++ b/datapath/vport-internal_dev.c > @@ -88,7 +88,7 @@ static const struct ethtool_ops internal_dev_ethtool_ops > = { > .get_link = ethtool_op_get_link, > }; > > -#if !defined(HAVE_NET_DEVICE_WITH_MAX_MTU) && > !defined(HAVE_RHEL7_MAX_MTU) > +#ifndef HAVE_NET_DEVICE_WITH_MAX_MTU > static int internal_dev_change_mtu(struct net_device *dev, int new_mtu) > { > if (new_mtu < ETH_MIN_MTU) { > @@ -155,6 +155,8 @@ static const struct net_device_ops > internal_dev_netdev_ops = { > .ndo_set_mac_address = eth_mac_addr, > #if !defined(HAVE_NET_DEVICE_WITH_MAX_MTU) && > !defined(HAVE_RHEL7_MAX_MTU) > .ndo_change_mtu = internal_dev_change_mtu, > +#elif !defined(HAVE_NET_DEVICE_WITH_MAX_MTU) && > defined(HAVE_RHEL7_MAX_MTU) > + .extended.ndo_change_mtu = internal_dev_change_mtu, > #endif > .ndo_get_stats64 = (void *)internal_get_stats, > }; > -- > 2.17.0 > > _______________________________________________ > dev mailing list > d...@openvswitch.org > > _______________________________________________ dev mailing list d...@openvswitch.org
https://www.mail-archive.com/ovs-dev@openvswitch.org/msg21495.html
CC-MAIN-2018-22
refinedweb
404
51.14
One area in software development that appears to have suffered from the malaise of the Cargo Cult [Wikipedia-1] is the use of branching within the version control system. The decision to use, or avoid, branches during the development of a software product sometimes seems to be made based on what the ‘cool companies’ are doing rather than what is suitable for the project and team itself. What is often misunderstood about the whole affair is that it is not necessarily the branching strategy that allows these cool companies to deliver reliable software more frequently, but the other practices they use to support their entire process, such as automated testing, pair programming, code reviews, etc. These, along with a supportive organizational structure mean that less reliance needs to be made on the use of code branches to mitigate the risks that would otherwise exist. This article describes the three main types of branching strategy and the forces that commonly dictate their use. From there it should be possible to understand how the problems inherent with branches themselves might be avoided and what it takes to live without them in some circumstances. Codeline policies Branches are lines, in the genealogy sense, of product development that reflect an evolution of the codebase in a way that is consistent for a given set of constraints. In essence each branch has a policy [Berczuk02] associated with it that dictates what types of change (commit) are acceptable into that codeline. When there is an ‘impedance mismatch’ [c2-1] between the code change and the policy, a branch may then be created to form a new codeline with a compatible policy. All this talk of ‘forces’ and ‘policies’ is just posh speak for the various risks and mitigating techniques that we use when developing software. For example a common risk is making a change that breaks the product in a serious way thereby causing disruption to the entire team. One way of reducing the likelihood of that occurring is to ensure the code change is formally reviewed before being integrated. That in turn implies that the change must either be left hanging around in the developer’s working copy until that process occurs or committed to a separate branch for review later. In the former case the developer is then blocked, whilst in the latter you start accruing features that aren’t properly integrated. Neither of these options should sound very appealing and so perhaps it’s the development process that needs reviewing instead. Merging can be expensive Branching is generally cheap, both in terms of version control system (VCS) resources and time spent by the developer in its creation. This is due to the use of immutability within the VCS storage engine which allows it to model a branch as a set of deltas on top of a fixed baseline. Whilst the branch creation is easy, keeping it up-to-date (forward integration) and/or integrating our changes later (reverse integration) can be far more expensive. It’s somewhat ironic that we talk about ‘branching’ strategies and not ‘merging’ strategies because it’s the latter aspect we’re usually most interested in optimising. Merge Debt is a term that has sprung up in recent times to describe the ever increasing cost that can result from working in isolation on a branch without synchronising yourself with your surroundings. Improvements in tooling have certainly made merging two text-based files slightly easier and there are new tools that try and understand the ‘meaning’ of a code change at a language level to further reduce the need for manual intervention. Of course even these cannot help when there are semantic conflicts (syntactically correct changes that just do the wrong thing) [Fowler]. And sadly binary files are still a handful. Refactoring can also be a major source of merge headaches when the physical structure of the codebase changes underneath you; this is compounded by the common practice of giving the folders and files the same names as the namespaces and classes. As we shall see in the following sections, branches are essentially graded by their level of stability, or degree of risk. Consequently the preferable direction for any merging is from the more stable into the more volatile on the assumption that tried-and-tested is less risky. The reason ‘cherry pick’ merges [c2-2] get such a bad name is because they usually go against this advice – they are often used to pull a single feature ‘up’ from a more volatile branch. This carries with it the risk of having to drag in dependent changes or to try and divorce the desired change from its dependants without breaking anything else. Integration branches Before embarking on a full discussion of the main branching strategies we need to clear up some terminology differences that often come up as a result of the different naming conventions used by various VCS products. Although there are three basic strategies, there are only two real types of branch – integration and private. Either you share the branch with others and collaborate or you own the branch and are solely responsible for its upkeep. It’s when you share the branch with others that the sparks really start to fly and so these tend to be minimised. For small teams there is usually only a single major integration branch and this often goes by the name of main, trunk or master. Sometimes this is known as the development branch to distinguish it from one of the other more specialised kinds. Either way it’s expected that this will be the default branch where the majority of the integration will finally occur. In larger organisations with much bigger teams there might be many integration branches for the same product, with perhaps one integration branch per project. At this scale the integration branch provides a point of isolation for the entire project and may spin off its own child branches. Multiple integration branches come with additional overhead, but that may well be less than the contention generated by a large team trying to share a single integration branch. If the project itself carries a large degree of uncertainty or cannot be delivered piecemeal then this project-level isolation can be more beneficial in the long run. Release branch Back in the days before VCS products supported the ability to branch you essentially had only one branch where all change took place. As the development process reached a point where the product was readying itself for a formal release, a code freeze was often put in place to reduce the changes to only those directly required to get the product out of the door. For those developers not directly working on ‘finishing’ the product they had to find other work to do, or find other ways to manage any code changes destined for later releases. Once branching became available a common answer to this problem was to branch the codebase at a suitable moment so that work could continue on the next version of the product in parallel with the efforts to the stabilise the impending release. The codeline policy for a release branch is therefore based around making very few, well-reviewed, well-tested changes that should resolve outstanding issues without creating any further mess. As the release date approaches finding the time to continually test and re-test the entire product after every change can become much harder and therefore more time is often spent up front attempting to decide whether further change is even really desirable. The branch is often not ‘cut’ from the development line at an arbitrary point in time – there will probably have been a reduction in high-risk changes leading up to the branch point so as to minimise the need to try and revert a complex feature at the last minute. By the time the release branch is ready to be created it should be anticipated that future additional changes will be kept to a bare minimum. This implies that during project planning the high-risk items are front-loaded to ensure they are given the longest time to ‘bed in’, i.e. you don’t upgrade compilers the day before a release. The most extreme form of a product release is probably a patch, or hotfix. Time is usually the most critical aspect and so it demands that any change be completed in total isolation as this allows it to be done with the highest degree of confidence that there are no other untoward side-effects. This kind of release branch is usually created directly from a revision label as that should be the most direct way to identify the part of the product’s entire history that corresponds to the product version needing remediation. Whereas a branch is an evolving codeline, a label (or tag) is a snapshot that annotates a single set of revisions as a specific milestone. What should be apparent about this particular strategy is that it’s mostly about compensating for a lack of stability in the main development process. If you never have to worry about supporting multiple product versions, then in theory you can change your development process to avoid the need for formal release branches. By ensuring you have adequate automated feature and performance testing and a streamlined development pipeline you should be able to deliver directly from the main integration branch. However, despite the development team’s best efforts at working hard to minimise the delays in getting a feature into production, there can still be other organizational problems that get in the way of delivery. Maybe there needs to be formal sign-off of each release, e.g. for regulatory purposes, or the QA cycle is out of your hands. In these cases the release branch acts more like a quarantine zone while the corporate cogs slowly turn. From a merging perspective release branches are generally a low-maintenance affair. As already stated the most desirable merge direction is from the stable codebase and release branches changes should be about the most carefully crafted of them all. Due to each one usually being an isolated change with high importance they can be merged into any ongoing integration branches the moment it becomes practical instead of waiting until the end. Feature/task branch If you think of the main development branch as the equator then a feature branch is the polar opposite of a release branch. Where the codeline policy for a release branch is aimed at providing maximum stability through low-risk changes, a feature branch has a policy aimed at volatile, high-risk changes. Instead of protecting the release from unwanted side-effects we’re now protecting the main development pipeline from stalling for similar reasons. The definition of ‘feature’ could be as small as a simple bug fix made by a single developer right up to an entire project involving many developers (the aforementioned project-level integration branch). Other terms that are synonymous are ‘task branch’ and ‘private branch’. One suggests a narrower focus for the changes whilst the other promotes the notion of a single developer working in isolation. Either way the separation allows the contributor(s) to make changes in a more ad hoc fashion that suits their goal. As such they need not worry about breaking the build or even checking in code that doesn't compile, if that’s how they need to work to be effective. One common use for a feature branch is to investigate changes that are considered experimental in nature, sometimes called a spike [ExtremeProgramming]. This type of feature may well be discarded at the end of the investigation with the knowledge gained being the point of the exercise. Rather than pollute the integration branch with a load of code changes that have little value, it’s easier to just throw the feature branch away and then develop the feature again in a ‘cleaner’ manner. Many version control systems don’t handle file and folder renames very well and so this makes tracing the history across them hard. For example, during a period of heavy refactoring, files (i.e. classes) may get renamed and moved around which causes their history to become detached. Even if the changes are reverted and the files return to their original names the history can still remain divorced as the VCS just sees some files deleted and others added. In some cases the changes themselves may be inherently risky, but it may also be that the person making the changes might be the major source of risk. New team members always need some time getting up to speed with a new codebase no matter how experienced they are. However, junior programmers will likely carry more risk than their more senior counterparts, therefore it might be preferable to keep their work at arms length until the level of confidence in their abilities (or the process itself adapts) to empower them to decide for themselves how a change should best be made. Once again it should be fairly apparent that what can mitigate some uses of feature branches is having a better development process in the first place. With a good automated test suite, pair programming, code reviews, etc. the feedback loop that detects a change which could destabilise the team will be unearthed much quicker and so headed it off before it can escalate. What makes feature branches distasteful to many, though, is the continual need to refresh it by merging up from the main integration branch. The longer you leave it before refreshing, the more chance you have that the world has changed underneath you and you’ll have the merge from hell to attend to. If the team culture is to refactor relentlessly then this will likely have a significant bearing on how long you leave it before bringing your own branch back in sync. Frequently merging up from the main integration branch is not just about resolving the textual conflicts in the source code though. It’s also about ensuring that your modifications are tested within the context of any surrounding changes to avoid the semantic conflicts described earlier. Whilst it might technically be possible to integrate your changes by just fixing any compiler warnings that occur in the final merge, you need to run the full set of smoke tests too (at a minimum) so that when you publish you have a high degree of confidence that your changes are sound. Shelving There is a special term for the degenerate case of a single-commit feature branch – shelving. If there is a need to suddenly switch focus and there are already changes in flight that you aren’t ready to publish yet, some VCSs allow you to easily put them to one side until you’re ready to continue. This is usually implemented by creating a branch based on the revision of the working copy and then committing any outstanding changes. When it’s time to resume, the changes can be un-shelved by merging the temporary branch back into the working copy (assuming the ancestry allows it). One alternative to shelving is to have multiple working folders all pointing at different branches. If you constantly have to switch between the development, release and production codebases, for example, it can be easier (and perhaps faster) to just switch working folders than to switch branches, especially now that disk space is so cheap. Forking The introduction of the Distributed Version Control System (D-VCS) adds another dimension to the branching strategy because a developer’s machine no longer just holds a working set of changes, but an entire repository. Because it’s possible to make changes and commit them to a local repo, the developer’s machine becomes a feature branch in its own right. It is still subject to the same issues in that upstream changes must be integrated frequently, but it can provide far more flexibility in the way those changes are then published because of the flexibility modern D-VCSs provide. No branch/feature toggle Back in the days before version control systems were clever enough to support multiple threads of change through branches, there was just a single shared branch. This constraint in the tooling had an interesting side-effect that meant making changes had to be more carefully thought out. Publishing a change that broke the build had different effects on different people. For some it meant that they kept everything locally for as long as possible and only committed once their feature was complete. Naturally this starts to get scary once you consider how unreliable hardware can be or what can go wrong every time you’re forced to update your working folder, which would entail a merge. Corruption of uncommitted changes is entirely possible if you mess the merge up and have no backup to return to. The other effect was that some developers learnt to break their work down into much more fine-grained tasks. In contrast they tried to find a way to commit more frequently but without making changes that had a high chance of screwing over the team. For example new features often involve some refactoring work to bring things into shape, the addition of some new code and the updating or removing of other sections. Through careful planning, some of this work can often be done alongside other people’s changes without disturbing them, perhaps with some additional cost required to keep the world in check at all times. For instance, by definition, refactoring should not change the observable behaviour and so it must be possible to make those changes immediately (unanticipated performance problems notwithstanding). This then is the premise behind using a single branch for development along with feature toggles to hide the functionality until it is ready for prime time. The notion of ‘always be ready to ship’ [c2-3] engenders an attitude of very small incremental change that continually edges the product forward. The upshot of this is that ‘value’ can be delivered continually too because even the refactoring work has some value and that can go into production before the entire feature might be implemented. Feature toggles are a mechanism for managing delivery whereas branches are a mechanism for managing collaboration. The desire to increase collaboration and deliver more frequently will usually lead to the use feature toggles as a way of resolving the tension created by partially implemented stories. This method of development does not come easily though, it demands some serious discipline. Given that every change is published to the team and the build server straight away means that there must be plenty of good practices in place to minimise the likelihood of a bug or performance problem creeping in unnoticed. The practices will probably include a large, mostly automated test suite along with some form of reviewing/pairing to ensure there are many ‘eyes’ watching. The way that the feature is ‘toggled’ can vary depending on whether its activation will be static (compile time) or dynamic (run time). From a continuous-testing point of view it makes far more sense to ensure any new feature is enabled dynamically otherwise there are more hoops to jump through to introduce it into the test suite. Doing it at runtime also helps facilitate A/B testing [Wikipedia-2] which allows old and new features to run side-by-side for comparison. The nature of the toggle varies depending on what mechanisms are available, but either way the number of points in the code where the toggle appears should be kept to an absolute minimum. For example, instead of littering the code with #ifdef style pre-processor statements to elide the code from compilation it is preferable to have a single conditional statement that enables the relevant code path: if (isNewFeatureEnabled) DoNewFeature(); The toggle could take the form of a menu item in the UI, an entry in a configuration file, an #ifdef compilation directive, a data file, an extra parameter in an HTTP request, a property in a message, the use of REM to comment in/out a command in a batch file, etc. Whatever the choice its absence will generally imply the old behaviour, with the new behaviour being the exception until it goes live for good. At that point it will disappear once again. One side-effect of working with feature toggles is that there might be a clean-up exercise required at the end if it gets pulled or if it supplants another feature – this will happen after go live and so needs to be planned in. During development there will also be periods of time where ‘unused code’ exists in the production codebase because the feature hasn’t been fully implemented yet. Whilst it’s beneficial that others get early sight of the ongoing efforts they need to be sure not to delete what might seem to be ‘dead code’. The motivation for not branching is effectively to avoid merging at all. That won’t happen, simply because you need to continually refresh your working folder and any update could require a merge. However, the likelihood that any conflicts will crop up should be greatly diminished. In particular ‘noisy’ refactorings can be easier to co-ordinate because the changes can be made, pushed and pulled by others with the minimum of fuss. Hybrid approaches The three core branching strategies are not in any way mutually exclusive. It’s perfectly acceptable to do, say, the majority of development on the main integration branch with occasional feature branches for truly risky tasks and release branches to avoid getting stalled due to bureaucracy (e.g. waiting for the Change Review Board to process the paperwork). Example: Visual Studio upgrade Historically a tool like Visual C++ cannot be silently upgraded. Its project and solution data files are tied to a specific version and must match the version of the tool being used by the programmer. In the past this has created problems for larger teams where you all cannot just migrate at the same time without some serious groundwork. Aside from the project data file problems, in C++ at least, there is also the problem of the source code itself being compatible with the new toolchain. Visual C++ used to default to the non-standard scoping rules for a for loop meaning that the loop variable could leak outside the loop and into lower scopes. Bringing the codebase in line with the ISO standard also meant source code changes to be handled too. When I tackled this with a medium sized team that were working on separate projects on multiple integration branches I had to use a combination of branching approaches as a big bang switchover was never going to work. Although the build and deployment process was somewhat arcane, the fact that multiple streams already existed meant that the parallelisation aspect was going to be less painful. As part of an initial spike, I used a feature branch to investigate what I needed to upgrade the tooling and to see what the impact would be vis-à-vis source code changes. The end result of that were just some new build scripts to handle the tooling upgrade; everything else was ditched. The next step was to bring as much of the existing codebase up to scratch by fixing the for loop scoping manually (where necessary) by inducing an extra scope (you just enclose the existing loop with another pair of braces). On one integration branch I upgraded the toolchain locally, fixed all the compiler errors and warnings, then reverted the toolchain upgrade, re-compiled with the current toolchain to verify backwards compatibility and finally committed just the source code changes. An email also went out too educating the other developers for the kinds of issues that might crop up in the future so that any new code would stand a better chance of being compatible at the final upgrade time. Those code changes and the new upgrade scripts were then merged (cherry picked) into every integration branch so that each one could then be inspected and any new changes made since the original branch point occurred could made compatible too. At this point all the integration branches were in good shape and ready to migrate once we had ironed out the non-syntactic problems. The next step was to verify that a build with the new toolchain worked at runtime too and so a new feature branch was taken from one of the integration branches which could be used to build and deploy the product for system testing. This allowed me to iron out any bugs in the code that only showed up with the new compiler behaviour and runtime libraries. Once fixed these changes could also be pushed across to the other integration branches so that all of the projects are now in a position to make the final switch. My goal when doing this work was to avoid messing up any one project if at all possible. The uncertainty around the delivery schedule of each project meant that I didn’t know at the start which one was going to be the best to use to ‘bed in’ the upgrade, so I made sure they were all candidates. Whilst it felt wasteful to continuously throw changes away (i.e. the upgraded project files) during the migration process, the painless way the final switchover was done probably meant more time was saved by my teammates in the long run. Gatekeeper workflows In recent times one particular hybrid approach has sprung up that attempts to formalise the need to pass some review stage before the change can be accepted into the main codeline. This review process (the aforementioned gatekeeper) can either be done entirely automatically via a continuous integration server; or via some form of manual intervention after the build server has given the change the green light. This style of workflow is the opposite of the ‘no branching’ approach because it relies on not letting anyone commit directly to the integration branch. Instead each developer gets their own feature branch into which they make their changes. Any time a developer’s branch has changed the continuous integration server will attempt to merge it with the integration branch, then build and run the test suite. If that process succeeds and an automated gatekeeper is in play then the merge is accepted and the main branch is advanced. If a manual gatekeeper is involved, perhaps to review the change too, they can perform that knowing it has already passed all the tests which helps minimise wasting time on reviewing low quality changes. If the change fails at any stage, such as the merge, build or test run then the developer will need to resolve the issue before going around the loop again. Whilst this has the benefit of ensuring the main development branch is always in a consistent state, build-wise, it does suffer from the same afflictions as any other feature branch – a need to continuing merge up from the integration branch. That said, where the no branching approach relies heavily on diligence by the programmer these workflows look to leverage the tooling in the continuous integration server to try and minimise the overhead. For example, just as they can automatically merge a feature branch to the integration branch on a successful build, they can also merge any changes from the integration branch back out to any feature branches when updated by the rest of the team. The net effect is that programmers can spend less time worrying about ‘breaking the build’ because they never contribute to it unless their changes are already known to be coherent. This style of workflow could also be combined with feature toggles to aid in delivering functionality in a piecemeal fashion. Summary The goal of this article was to distil the folklore surrounding branching strategies down into the three key patterns – no branching, branching for a feature and branching for a release. We identified the policies that commonly drive the choice of strategy and the forces, often organisational in nature, that can push us in that direction. Finally we looked at how and when it might be suitable to combine them rather than blindly try to stick to the same strategy all the time, and how tooling is beginning to help reduce some of the overhead. Acknowledgements A big thumbs-up from me goes to Mike Long, Jez Higgins and the Overload review collective for their valuable input. And mostly to Fran, the Overload editor, for her patience as I made some significant last minute edits. References [Berczuk02] Software Configuration Management Patterns, Stephen P. Berczuk with Brad Appleton, 2002, Chapter 12: Codeline Policy [c2-1] [c2-2] [c2-3] [ExtremeProgramming] [Fowler] [Wikipedia-1] [Wikipedia-2]
https://accu.org/index.php/journals/1920
CC-MAIN-2018-30
refinedweb
4,815
52.83
Hi:-) ! hi!!:) how are you!? Happy Holidays! Happy Holidays! I am great...so nice to see you:-) you too :) My pinched nerves seemed to have finally worked out :) but i have a completely different thing tonight :-/ and im trying to keep myself level :( I am glad the pinched nerve resolved... what's going on tonight? I have a sinus infection, or what i think is a sinus infection. Saw a dr yesterday, and he gave me the Z-pac.. but im not sure that its working :( and my head is going through so many different directions right now.. i have two conflicting body temps, and im pretty sure my bp is normal but.. I am sorry to hear that. A sinus infection will take about 48 hours to begin to respond to antibiotics.... what you might be feeling is anxiety secondary to all the unpleasantness that comes with a sinus infection. def anxiety... Personally.... I don't do well with anything that makes it hard to breathe normally... so I can relate Try to breathe from your mouth more than your nose well, ive had a headache for most of the day and since then ive been thinking menentigits, heart attack because my sholder spazzed out.. and the headache and all that.. i just had my wisdom teeth out two weeks ago and im afraid its coming from that.. theres just a lot... i have a digital mouth thermometer that reads 99.6 while i have an ear thermometer that reads 97..9 What really helps is to sniff something that will help clear your nose... something mentholated.. like Vicks... or even a liniment rub like Ben Gay or icy hot hummmm..... I would disregard the ear thermometer, sounds like it's malfunctioning. Maybe get another oral thermometer to compare. Menningitis..... to do a little self test, bend your head down to your chest anything hurt? a little sore but not outstandingly painful good... with menningitis you would feel A LOT of pain in your neck with this movement so we can completely throw that out the window... no menningitis:-) not going to my chest no lol going sideways yes but thats due to the pinched nerve so yay! ok im glad i can rule that out any rash? nope! good... there is usually an accompanying rash with menningitis... as well as dilated pupils and a massive headache. haha my eyes are blue so their always dialated lol headache... ive had worse headaches... but it still annoying its been going on all day Did you take any ibuprofen? no ;( dont have any. But i think I have advil Ibuprofen will not only help with the headache it will also help with swelling in the nasal passages yes..advil IS ibuprofen OH it is??? ha! so take that according to package directions' i can take that with the Azithromycin? I would just about be you will feel MUCH better in an hour YES.. that is absolutely fine to take the both together brb! need to go get my glasses lol k 1 cap every 4-6hrs. if symptoms do not respond then two can be used errrr..... bet ( typo above) should reduce the mini fever right? I always take 2, one doesn't cut it for me... but you can try one, if it doesn't work, take another in an hour yes it will reduce fever and you will feel much better You can take 2 every 4 to 6 hours thank you.. ok next half.. when your sick, PB goes up or down? it can go up and what is better? wrist or manual? unfort both digital it's normal for blood pressure to rise with fever or when you don't feel good manual wrist is unreliable really?? yes most hospitals will not allow them and I have never met a Cardiologist who would allow a wrist cuff hahaha ok so then i dont really know what my bp is at the moment then, i was using the wrist one take it with the arm cuff and let me know ha! pretty normal 111/70 @95 the number it went up to was like 166 the counter thing.. is that normal? 166? the top number? no n ono the actual reading was 111/70 @ 95bpm but the pressure gauge on the device was like 166.. when it counts going up totally normal :-) The counter thing.... that's inflating... it keeps inflating until it detects your pulse...sometimes it goes way higher than it needs to oooh ok! because the manual says the standard is like 144 but i never see 144 lol it can go as high as 200 trying to locate the pulse so its probably just the sinus thing thats causing the headache then if my bp is normal LOL yes, I really think so try the ibuprofen and let me know... I really think you are going to feel so much better thank you cam.. i had so much going through my mind.. you eased a lot of it :) thank you so much <3 how long does it take for an anti-biotic to start working??? antibiotics will begin to help within 48 hours you are sooooo welcome:-) ok.. its only been 24.. it was making me nervous that it was getting worse lol or felt that way I should say you will feel the effects within 48 hrs, they do begin to help immediately well, i felt ok yesterday, but today its like i hit the wall.. headache.. sore throat.. now i sound stuffy and awful :( I was hoping i had caught it in time You should begin to feel better right away from the ibuprofen ( in an hour or so) and the antibiotics by tomorrow... sometimes a sinus infection can linger for several days... even after it's resolved sometimes there is still mucus to get rid of. Be sure to drink plenty of water to keep your secretions thin and easier to eliminate. lets say this did stem from my surgery to have wisdom teeth out... the z-pack would help w that right??? last question i promise LOL you know me and my mind ;) lol and for that im sorry! lol yes... that would resolve it :-D thank you :) You KNOW you are always welcome:-) Have a great night... and anytime you need me.. just post a question in my name.. if I am not here.. one of the other Experts will let me know and I will get to you as soon as possible and H A P P Y H O L I D A Y S! :-) thank you Cam :) Ive missed you :) You've always been there :) Happy Holidays!:) Ill leave you a note in a couple of days :) I Hope you have a great Christmas!:) Thank you! You too!
http://www.justanswer.com/health/5zseg-hi-camille-while-availible-couple.html
CC-MAIN-2014-52
refinedweb
1,142
82.04
Inserts a character or a character string.. s. CharTmatches the type of ch), exactly traits::length(s)characters are inserted. std::char_traits<char>::length(s)characters are inserted.. The behavior is undefined if s is a null pointer. os << value). This function template does not participate in overload resolution unless the expression os << valueis well-formed. (since C++17) os. Overload (3) in LLVM libc++ implements LWG#1203 and returns a stream of the same type as the argument, so that code such as (std::ostringstream() << 1.2).str() compiles. #include <iostream> #include <fstream> int main() { std::cout << "Hello, world" // the const char* overload << '\n'; // the char overload std::ofstream("test.txt") << 1.2; // rvalue overload } Output: Hello, world © cppreference.com Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://docs.w3cub.com/cpp/io/basic_ostream/operator_ltlt2
CC-MAIN-2021-21
refinedweb
132
51.85
I've compiled and recompiled subversion again and again and I still get the following error: when i run import libsvn._core ImportError: /usr/local/lib/libsvn_ra_dav-1.so.0: undefined symbol: SSL_load_error_strings Does this mean anything to anyone? Russ Ruslan Sivak wrote: > I'm trying to get the latest version of trac working with subversion > 1.4 on rhel3 with python 2.4. I compiled everything several times, > and trac keeps complaining. I was told that I don't have the > python-subversion bindings installed properly. As far as I know, it's > all installed properly. How do I check whether or not they're > properly installed? > > R 22 01:16:39 2006 This is an archived mail posted to the Subversion Users mailing list.
https://svn.haxx.se/users/archive-2006-09/1149.shtml
CC-MAIN-2016-44
refinedweb
126
60.41
Creating a Module with a Simple Text Editor In this tutorial, you will learn how to develop a simple commerce module using only a text editor. If you do not have the Web Platform Installer on your computer, download it before beginning this tutorial. This guide has been marked for review. If you are just getting started with Orchard module development you should read the Getting Started with Modules course first. It will introduce you to building modules with Orchard using Visual Studio Community, a free edition of Visual Studio. Setting Up the Orchard Site First, you will set up a new Orchard website. If you already have a site set up, you can skip this section and jump directly to the code generation section. To start the setup, open IIS Manager, right-click Sites, and click Add Web Site. In the Add Web Site dialog box, fill in the fields to point the new website to a folder, such as \inetpub\wwwroot\Orchard. Name the new site Orchard and give it an unused port, such as 90. Use the default application pool (.NET 4.0 integrated pipeline). Click OK. From the Windows Start menu, launch Web Platform Installer, select Orchard CMS, click Add, and then click Install. After you accept the license terms, Orchard is installed. Open a command window and change the current directory to point to the root of the site. Then run bin\orchard.exe. Type help commands to get the list of available commands. For now, only the help and setup commands are available. However, as Orchard is developed and modules are activated, new commands will become available. (The Orchard command-line executable actually discovers the commands from the modules inside of the application.) To set up the site, enter the following command: setup /SiteName:Orchard /AdminUsername:admin /AdminPassword:123456 /DatabaseProvider:SqlCe This is equivalent to setting up the site from the web interface. Leave the command window open. (In fact, don't close it until you have finished this tutorial.) Generating Code for the Module Now you are ready to start developing the commerce module. Orchard provides a code generation feature that sets up the structure of an empty module to help you get started. By default, code generation is disabled. So you must first install and enable the feature. The easiest way to do this is to go to Modules in the admin UI and then click the "Gallery" tab. Do a search for "code generation" and then install the module. To enable code generation, if you didn't do so right after install, you may enter the following command in the command window: feature enable Orchard.CodeGeneration You will use a code-generation command to create a commerce module. Enter the following command: codegen module SimpleCommerce Open a Windows Explorer window and browse to the newly created \inetpub\wwwroot\Orchard\Modules\SimpleCommerce folder. Open the Module.txt file using a text editor. Change the description to "A simple commerce module". Change the description of the feature to be "A simple product part". Save the file and close it. The following example shows the complete Module.txt file after the changes. Name: SimpleCommerce AntiForgery: enabled Author: The Orchard Team Website: Version: 0.5.0 OrchardVersion: 0.5.0 Description: A simple commerce module Features: SimpleCommerce: Name: Simple Commerce Description: A simple product part. Category: Commerce Creating the Model for the Part Next, you will create a data model that is a representation of what will be stored in the database. In Modules/SimpleCommerce/Models, create a Product.cs file and add the following content: using System.ComponentModel.DataAnnotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Records; namespace SimpleCommerce.Models { public class ProductPartRecord : ContentPartRecord { public virtual string Sku { get; set; } public virtual float Price { get; set; } } public class ProductPart : ContentPart<ProductPartRecord> { [Required] public string Sku { get { return Retrieve(r => r.Sku); } set { Store(r => r.Sku, value); } } [Required] public float Price { get { return Retrieve(r => r.Price); } set { Store(r => r.Price, value); } } } } This code has two properties, Sku and Price, that are virtual in order to enable the creation of a dynamic proxy that will handle persistence transparently. The code also defines a content part that derives from ContentPart<ProductPartRecord> and that exposes the SKU and price from the record as public properties and infoset. You can find more info about infoset here. The properties have attributes that will surface in the UI as validation tests. In order for the application to pick up the new file, you need to add it to the module's project file. Open the SimpleCommerce.csproj file and look for "assemblyinfo.cs". After that line, add the following: <Compile Include="Models\Product.cs" /> Save the file, but leave it open, because you will make additional changes to it throughout the tutorial. Navigate to the site in your browser to make sure the application's dynamic compilation feature picks up the new part and record. You will know that everything is working if you go to the Features administration screen and see the new SimpleCommerce feature. In the command window, enable the new feature using the following command: feature enable SimpleCommerce Creating the Initial Data Migration File Data migration is a pattern that enables an application or component to handle new versions gracefully, without any data loss. The main idea is that the system keeps track of the current version installed and each data migration describes the changes to go from one version to the next. If the system detects that there is a new version installed and the current data is from a previous version, the administrator of the site is prompted to upgrade. The system then runs all necessary migration methods until the data version and the code version are in sync. Start by creating the initial migration for the new module, which will just create the data tables that are needed. In the command window, enter the following command: codegen datamigration SimpleCommerce This creates the following Migrations.cs file:; } } } The method name Create is the convention for the initial data migration. It calls the SchemaBuilder.CreateTable method that creates a ProductPartRecord table that has Sku and Price columns in addition to the columns from the basic ContentPartRecord table. Notice that the method returns 1, which is the version number for the migration. Add another migration step to this in order to illustrate how you can later alter the existing schema and type metadata as the module evolves. In this case, you will take this opportunity to add a feature that will enable the part to be attached to any content type. Add the following method to the data migration class: public int UpdateFrom1() { ContentDefinitionManager.AlterPartDefinition("ProductPart", builder => builder.Attachable()); return 2; } This new migration is named UpdateFrom1, which is the convention for upgrading from version 1. Your next migration should be called UpdateFrom2 and return 3, and so on. Make sure the following line is present in the .csproj file. (It should already have been added by the code generation command.) <Compile Include="Migrations.cs" /> Navigate to the Features screen in the dashboard. You see a warning that indicates that one of the features needs to be updated, and the Simple Commerce module is displayed in red. Click Update to ensure that the migrations are run and that the module is up to date. Adding a Handler A handler in Orchard is analogous to. To see what event handlers you can override in your own handlers, examine the source code for ContentHandlerBase. The handler you need in the module is not going to be very complex, but it will implement some plumbing that is necessary to set up the persistence of the part. We hope that this kind of plumbing will disappear in a future version of Orchard, possibly in favor of a more declarative approach such as using attributes. Create a Handlers folder and add a ProductHandler.cs file to it that contains the following code: using Orchard.ContentManagement.Handlers; using SimpleCommerce.Models; using Orchard.Data; namespace SimpleCommerce.Handlers { public class ProductHandler : ContentHandler { public ProductHandler(IRepository<ProductPartRecord> repository) { Filters.Add(StorageFilter.For(repository)); } } } Add the file to the .csproj file so that dynamic compilation can pick it up, using the following line: <Compile Include="Handlers\ProductHandler.cs" /> Adding a Driver A driver in Orchard is analogous to a controller in ASP.NET MVC, but is well adapted to the composition aspect that is necessary in web content management systems. It is specialized for a specific content part and can specify custom behavior for well-known actions such as displaying an item in the front end or editing it in the administration UI. A driver typically has overrides for the display and editor actions. For the product part, create a new Drivers folder and in that folder create a ProductDriver.cs file that contains the following code: using SimpleCommerce.Models; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement; namespace SimpleCommerce.Drivers { public class ProductDriver : ContentPartDriver<ProductPart> { protected override DriverResult Display( ProductPart part, string displayType, dynamic shapeHelper) { return ContentShape("Parts_Product", () => shapeHelper.Parts_Product( Sku: part.Sku, Price: part.Price)); } //GET protected override DriverResult Editor(ProductPart part, dynamic shapeHelper) { return ContentShape("Parts_Product_Edit", () => shapeHelper.EditorTemplate( TemplateName: "Parts/Product", Model: part, Prefix: Prefix)); } //POST protected override DriverResult Editor( ProductPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); return Editor(part, shapeHelper); } } } The code in the Display method creates a shape to use when rendering the item in the front end. That shape has Sku and Price properties copied from the part. Update the .csproj file to include the following line: <Compile Include="Drivers\ProductDriver.cs" /> The Editor method also creates a shape named EditorTemplate. The shape has a TemplateName property that instructs Orchard where to look for the rendering template. The code also specifies that the model for that template will be the part, not the shape (which would be the default). The placement of those parts within the larger front end or dashboard must be specified using a Placement.info file that is located at the root of the module. That file, like a view, can be overridden from a theme. Create the Placement.info file with the following contents: <Placement> <Place Parts_Product_Edit="Content:3"/> <Place Parts_Product="Content:3"/> </Placement> Add the Placement.info file to the .csproj file using the following line: <Content Include="Placement.info" /> Building the Templates The last thing to do in order for the new content part to work is to write the two templates (front end and admin) that are configured in the driver. Create the front-end template first. Create a Parts folder under Views and add a Product.cshtml file that contains the following code: <br/> @T("Price"): <b>$@Model.Price</b><br /> @Model.Sku<br/> This is very plain rendering of the shape. Notice the use of the T method call to wrap the "Price" string literal. This enables localization of that text. The administration view is a little heavier on HTML helper calls. Create an EditorTemplates folder under Views and a Parts folder under that. Add a Product.cshtml to the Parts folder that contains the following code: @model SimpleCommerce.Models.ProductPart <fieldset> <label class="sub" for="Sku">@T("Sku")</label><br /> @Html.TextBoxFor(m => m.Sku, new { @@T("Price")</label><br /> @Html.TextBoxFor(m => m.Price, new { @class = "text" }) </fieldset> Add those two templates to the .csproj file using the following lines: <Content Include="Views\Parts\Product.cshtml" /> <Content Include="Views\EditorTemplates\Parts\Product.cshtml" /> Putting it All Together into a Content Type The content part that you've put together could already be composed from the administration UI into a content type (see Creating Custom Content Types), but per the goal of this topic, you will continue by writing code using a text editor. You will now build a new Product content type that will include the Product part and a number of parts that you can get from Orchard. So far, you have been focused on your specific domain. This will now change and you will start integrating into Orchard. To build the content type from a new migration, open the Migrations.cs file and add the following method to the class: public int UpdateFrom2() { ContentDefinitionManager.AlterTypeDefinition("Product", cfg => cfg .WithPart("CommonPart") .WithPart("RoutePart") .WithPart("BodyPart") .WithPart("ProductPart") .WithPart("CommentsPart") .WithPart("TagsPart") .WithPart("LocalizationPart") .Creatable() .Indexed()); return 3; } Also add using Orchard.Indexing; to the top of the file. What you are doing is creating (or updating) the Product content type and adding to it the ability to have its own URL and title ( RoutePart), to have a rich text description ( BodyPart), to be a product, to be commented on ( TagsPart) and to be localizable ( LocalizationPart). It can also be created, which will add a Create Product menu entry, and it will also enter the search index ( Indexed). To enable your new module, open the Orchard dashboard and click Modules. Select the Features tab, find the SimpleCommerce module, and click Enable. To add a new Product content type, click Content on the dashboard, select the Content Types tab, find Product, and click Create New Product. You now have a product editor that features your Sku and Price fields. The code for this module can be downloaded from the following page: Orchard.Module.SimpleCommerce.0.5.0.zip
http://docs.orchardproject.net/en/latest/Documentation/Creating-a-module-with-a-simple-text-editor/
CC-MAIN-2017-26
refinedweb
2,222
57.98
EXC_HANDLE(3L) EXC_HANDLE(3L) NAME exc_handle, exc_unhandle, exc_bound, exc_notify, exc_raise, exc_on_exit, exc_uniqpatt - LWP exception handling SYNOPSIS #include <<lwp/lwp.h>> int exc_handle(pattern, func, arg) int pattern; caddr_t (*func)(); caddr_t arg; int exc_raise(pattern) int pattern; int exc_unhandle() caddr_t (*exc_bound(pattern, arg))() int pattern; caddr_t *arg; int exc_notify(pattern) int pattern; int exc_on_exit(func, arg) void (*func)(); caddr_t arg; int exc_uniqpatt() DESCRIPTION These primitives can be used to manage exceptional conditions in a thread. Basically, raising an exception is a more general form of non- local goto or longjmp, but the invocation is pattern-based. It is also possible to notify an exception handler whereby a function supplied by the exception handler is invoked and control is returned to the raiser of the exception. Finally, one can establish a handler which is always invoked upon procedure exit, regardless of whether the procedure exits using a return or an exception raised to a handler established prior to the invocation of the exiting procedure. exc_handle() is used to establish an exception handler. exc_handle() returns 0 to indicate that a handler has been established. A return of -1 indicates an error in trying to establish the exception handler. If it returns something else, an exception has occurred and any procedure calls deeper than the one containing the handler have disappeared. All exception handlers established by a procedure are automatically dis- carded when the procedure terminates. exc_handle() binds a pattern to the handler, where a pattern is an integer, and two patterns match if their values are equal. When an exception is raised with exc_raise(), the most recent handler that has established a matching pattern will catch the exception. A special pattern (CATCHALL) is provided which matches any exc_raise() pattern. This is useful for handlers which know that there is no chance the resources allocated in a routine can be reclaimed by previous routines in the call chain. The other two arguments to exc_handle() are a function and an argument to that function. exc_bound() retrieves these arguments from an exc_handle() call made by the specified thread. By using exc_bound() to retrieve and call a function bound by the exception handler, a pro- cedure can raise a notification exception which allows control to return to the raiser of the exception after the exception is handled. exc_raise() allows the caller to transfer control (do a non-local goto) to the matching exc_handle(). This matching exception handler is destroyed after the control transfer. At this time, it behaves as if exc_handle() returns with the pattern from exc_raise() as the return value. Note: func of exc_handle() is not called using exc_raise() -- it is only there for notification exceptions. Because the exception handler returns the pattern that invoked it, it is possible for a han- dler that matches the CATCHALL pattern to reraise the exact exception it caught by using exc_raise() on the caught pattern. It is illegal to handle or raise the pattern 0 or the pattern -1. Handlers are searched for pattern matches in the reverse execution order that they are set (i.e., the most recently established handler is searched first). exc_unhandle() destroys the most recently established exception handler set by the current thread. It is an error to destroy an exit-handler set up by exc_on_exit(). When a procedure exits, all handlers and exit handlers set in the procedure are automatically deallocated. exc_notify() is a convenient way to use exc_bound. The function which is bound to pattern is retrieved. If the function is not NULL, the function is called with the associated argument and the result is returned. If the function is NULL, exc_raise(pattern) is returned. exc_on_exit() specifies an exit procedure and argument to be passed to the exit procedure, which is called when the procedure which sets an exit handler using exc_on_exit() exits. The exit procedures (more than one may be set) will be called regardless if the setting procedure is exited using a return or an exc_raise(). Because the exit procedure is called as if the handling procedure had returned, the argument passed to it should not contain addresses on the handler's stack. However, any value returned by the procedure which established the exit proce- dure is preserved no matter what the exit procedure returns. This primitive is used in the MONITOR macro to enforce the monitor disci- pline on procedures. Some signals can be considered to be synchronous traps. They are usu- ally the starred (*) signals in the signal(3V) man pages. These are: SIGSYS, SIGBUS, SIGEMT, SIGFPE, SIGILL, SIGTRAP, SIGSEGV. If an event is marked as a trap using agt_trap() (see agt_create(3L)) the event will generate exceptions instead of agent messages. This mapping is per-pod, not per-thread. A thread which handles the signal number of one of these as the pattern for exc_handle() will catch such a signal as an exception. The exception will be raised as an exc_notify() so either escape or notification style exceptions can be used, depending on what the matching exc_handle() provides. If the exception is not handled, the thread will terminate. Note: it can be dangerous to sup- ply an exception handler to treat stack overflow since the client's stack is used in raising the exception. exc_uniqpatt() returns an exception pattern that is not any of the pre- defined patterns (any of the synchronous exceptions or -1 or CATCHALL). Each call to exc_uniqpatt() results in a different pattern. If exc_uniqpatt() cannot guarantee uniqueness, -1 is returned instead the first time this happens. Subsequent calls after this error result in patterns which may be duplicates. RETURN VALUES exc_uniqpatt() returns a unique pattern on success. The first time it fails, exc_uniqpatt() returns -1. exc_handle() returns: 0 on success. -1 on failure. When exc_handle() returns because of a matching call to exc_raise(), it returns the pattern raised by exc_raise(). On success, exc_raise() transfers control to the matching exc_handle() and does not return. On failure, it returns -1. exc_unhandle() returns: 0 on success. -1 on failure. exc_bound() returns a pointer to a function on success. On failure, it returns NULL. On success, exc_notify() returns the return value of a function, or transfers control to a matching exc_handle() and does not return. On failure, it returns -1. exc_on_exit() returns 0. ERRORS exc_unhandle() will fail if one or more of the following is true: LE_NONEXIST Attempt to remove a non-existent handler. Attempt to remove an exit handler. exc_raise() will fail if one or more of the following is true: LE_INVALIDARG Attempt to raise an illegal pattern (-1 or 0). LE_NONEXIST No context found to raise an exception to. exc_handle() will fail if one or more of the following is true: LE_INVALIDARG Attempt to handle an illegal pattern (-1 or 0). exc_uniqpatt() will fail if one or more of the following is true: LE_REUSE Possible reuse of existing object. agt_create(3L), signal(3V) BUGS The stack may not contain useful information after an exception has been caught so post-exception debugging can be difficult. The reason for this is that a given handler may call procedures that trash the stack before reraising an exception. The distinction between traps and interrupts can be problematical. The environment restored on exc_raise() consists of the registers at the time of the exc_handle(). As a result, modifications to register variables between the times of exc_handle() and exc_raise() will not be seen. This problem does not occur in the sun4 implementation. WARNINGS exc_on_exit() passes a simple type as an argument to the exit routine. If you need to pass a complex type, such as thread_t, mon_t, or cv_t, pass a pointer to the object instead. 21 January 1990 EXC_HANDLE(3L)
http://modman.unixdev.net/?sektion=3&page=exc_uniqpatt&manpath=SunOS-4.1.3
CC-MAIN-2017-17
refinedweb
1,268
55.54
> On Aug 10, 2017, at 7:46 AM, James Froggatt via swift-evolution > <swift-evolution. > > ------------ Begin Message ------------ > Group: gmane.comp.lang.swift.evolution > MsgID: <CAGY80u=kVQA1q=5tmxxxfgm4tlgfuqh61en1daepemaa_fo...@mail.gmail.com> > > On Tue, Aug 8, 2017 at 5:27 PM, Jordan Rose via swift-evolution < > swift-evolution-m3fhrko0vlzytjvyw6y...@public.gmane.org> wrote: > >> Hi, everyone. Now that Swift 5 is starting up, I'd like to circle back to >> an issue that's been around for a while: the source compatibility of enums. >> Today, it's an error to switch over an enum without handling all the cases, >> but this breaks down in a number of ways: >> >> - A C enum may have "private cases" that aren't defined inside the >> original enum declaration, and there's no way to detect these in a switch >> without dropping down to the rawValue. >> - For the same reason, the compiler-synthesized 'init(rawValue:)' on an >> imported enum never produces 'nil', because who knows how anyone's using C >> enums anyway? >> - Adding a new case to a *Swift* enum in a library breaks any client code >> that was trying to switch over it. >> >> (This list might sound familiar, and that's because it's from a message of >> mine on a thread started by Matthew Johnson back in February called >> "[Pitch] consistent public access modifiers". Most of the rest of this >> email is going to go the same way, because we still need to make progress >> here.) >> >> At the same time, we really like our exhaustive switches, especially over >> enums we define ourselves. And there's a performance side to this whole >> thing too; if all cases of an enum are known, it can be passed around much >> more efficiently than if it might suddenly grow a new case containing a >> struct with 5000 Strings in it. >> >> >> *Behavior* >> >> I think there's certain behavior that is probably not *terribly* >> controversial: >> >> - When enums are imported from Apple frameworks, they should always >> require a default case, except for a few exceptions like NSRectEdge. (It's >> Apple's job to handle this and get it right, but if we get it wrong with an >> imported enum there's still the workaround of dropping down to the raw >> value.) >> - When I define Swift enums in the current framework, there's obviously no >> compatibility issues; we should allow exhaustive switches. >> >> Everything else falls somewhere in the middle, both for enums defined in >> Objective-C: >> >> - If I define an Objective-C enum in the current framework, should it >> allow exhaustive switching, because there are no compatibility issues, or >> not, because there could still be private cases defined in a .m file? >> - If there's an Objective-C enum in *another* framework (that I built >> locally with Xcode, Carthage, CocoaPods, SwiftPM, etc.), should it allow >> exhaustive switching, because there are no *binary* compatibility issues, >> or not, because there may be *source* compatibility issues? We'd really >> like adding a new enum case to *not* be a breaking change even at the >> source level. >> - If there's an Objective-C enum coming in through a bridging header, >> should it allow exhaustive switching, because I might have defined it >> myself, or not, because it might be non-modular content I've used the >> bridging header to import? >> >> And in Swift: >> >> - If there's a Swift enum in another framework I built locally, should it >> allow exhaustive switching, because there are no binary compatibility >> issues, or not, because there may be source compatibility issues? Again, >> we'd really like adding a new enum case to *not* be a breaking change >> even at the source level. >> >> Let's now flip this to the other side of the equation. I've been talking >> about us disallowing exhaustive switching, i.e. "if the enum might grow new >> cases you must have a 'default' in a switch". In previous (in-person) >> discussions about this feature, it's been pointed out that the code in an >> otherwise-fully-covered switch is, by definition, unreachable, and >> therefore untestable. This also isn't a desirable situation to be in, but >> it's mitigated somewhat by the fact that there probably aren't many >> framework enums you should exhaustively switch over anyway. (Think about >> Apple's frameworks again.) I don't have a great answer, though. >> >> For people who like exhaustive switches, we thought about adding a new >> kind of 'default'—let's call it 'unknownCase' just to be able to talk about >> it. This lets you get warnings when you update to a new SDK, but is even >> more likely to be untested code. We didn't think this was worth the >> complexity. >> >> >> *Terminology* >> >> The "Library Evolution >> <>" doc (mostly >> written by me) originally called these "open" and "closed" enums ("requires >> a default" and "allows exhaustive switching", respectively), but this >> predated the use of 'open' to describe classes and class members. Matthew's >> original thread did suggest using 'open' for enums as well, but I argued >> against that, for a few reasons: >> >> - For classes, "open" and "non-open" restrict what the *client* can do. >> For enums, it's more about providing the client with additional >> guarantees—and "non-open" is the one with more guarantees. >> - The "safe" default is backwards: a merely-public class can be made >> 'open', while an 'open' class cannot be made non-open. Conversely, an >> "open" enum can be made "closed" (making default cases unnecessary), but a >> "closed" enum cannot be made "open". >> >> That said, Clang now has an 'enum_extensibility' attribute that does take >> 'open' or 'closed' as an argument. >> >> On Matthew's thread, a few other possible names came up, though mostly >> only for the "closed" case: >> >> - 'final': has the right meaning abstractly, but again it behaves >> differently than 'final' on a class, which is a restriction on code >> elsewhere in the same module. >> - 'locked': reasonable, but not a standard term, and could get confused >> with the concurrency concept >> - 'exhaustive': matches how we've been explaining it (with an "exhaustive >> switch"), but it's not exactly the *enum* that's exhaustive, and it's a >> long keyword to actually write in source. >> >> - 'extensible': matches the Clang attribute, but also long >> >> >> I don't have better names than "open" and "closed", so I'll continue using >> them below even though I avoided them above. But I would *really like to >> find some*. >> >> >> *Proposal* >> >> Just to have something to work off of, I propose the following: >> >> 1. All enums (NS_ENUMs) imported from Objective-C are "open" unless they >> are declared "non-open" in some way (likely using the enum_extensibility >> attribute mentioned above). >> 2. All public Swift enums in modules compiled "with resilience" (still to >> be designed) have the option to be either "open" or "closed". This only >> applies to libraries not distributed with an app, where binary >> compatibility is a concern. >> 3. All public Swift enums in modules compiled from source have the option >> to be either "open" or "closed". >> 4. In Swift 5 mode, a public enum should be *required* to declare if it >> is "open" or "closed", so that it's a conscious decision on the part of the >> library author. (I'm assuming we'll have a "Swift 4 compatibility mode" >> next year that would leave unannotated enums as "closed".) >> 5. None of this affects non-public enums. >> >> (4) is the controversial one, I expect. "Open" enums are by far the common >> case in Apple's frameworks, but that may be less true in Swift. >> >> >> *Why now?* >> >> Source compatibility was a big issue in Swift 4, and will continue to be >> an important requirement going into Swift 5. But this also has an impact on >> the ABI: if an enum is "closed", it can be accessed more efficiently by a >> client. We don't *have* to do this before ABI stability—we could access >> all enums the slow way if the library cares about binary compatibility, and >> add another attribute for this distinction later—but it would be nice™ (an >> easy model for developers to understand) if "open" vs. "closed" was also >> the primary distinction between "indirect access" vs. "direct access". >> >> I've written quite enough at this point. Looking forward to feedback! >> Jordan >> > >@swift.org > _______________________________________________ swift-evolution mailing list swift-evolution@swift.org
https://www.mail-archive.com/swift-evolution@swift.org/msg28374.html
CC-MAIN-2017-34
refinedweb
1,366
58.32
If you are new to Clojure, this post will quickly get you started. You will create a basic Clojure application and learn how to use Leiningen, a tool which helps to manage various tasks for Clojure projects, like creating them, managing dependencies or executing the code. Installing Leiningen is pretty straighforward. You have to download this script (be sure to get the 2.x version) and make it accessible in your $PATH. Upon the first run Leiningen bootstraps itself using that script. Let's start with a most basic way of creating a Clojure project with Leiningen λ lein new baaz Generating a project called baaz based on the 'default' template. To see other templates (app, lein plugin, etc), try `lein help new`. This is our project file structure: . ├── README.md ├── doc │ └── intro.md ├── project.clj ├── src │ └── baaz │ └── core.clj └── test └── baaz └── core_test.clj Let's take a look at src/baaz/core.clj. (ns baaz.core) (defn foo "I don't do a whole lot." [x] (println x "Hello, World!")) There is only one function defined. You can launch an interactive Clojure shell (called REPL) using lein repl command. Notice that an attempt to call that function will result in an error: Unable to resolve symbol: foo in this context. The reason for that is foo being defined in a different namespace than the one being loaded when REPL starts. In order to make this project run on the command line through Leiningen you must add to that file a special -main function. (defn -main [] (foo "Zaiste")) Once added, you can run it as: λ lein run -m baaz.core Zaiste Hello, World! If you don't want to include -m parameter for each run, you can specify it inside project.clj using a :main parameter as shown below: (defproject baaz "0.1.0" :main baaz.core :dependencies [[org.clojure/clojure "1.4.0"]]) Launching REPL with :main parameter defined will automatically switch to baaz.core namespace, othwerwise default user namespace will be used. Now, you know what happens while creating a barebone application with Leiningen. You can speed up this process using one of predefined application templates (you can also create your own template). For example, there is a template called app which includes a -main definition along with the necessary declaration inside project.clj. You can run this this template as: λ lein new app baaz You have the basics now. Next step would be to read more about Leiningen and its features. My Tech Newsletter Get emails from me about programming & web development. I usually send it once a month
https://zaiste.net/posts/clojure_app_101/
CC-MAIN-2021-10
refinedweb
434
68.06
User Name: Published: 10 Dec 2008 By: Medusa M Download Sample Code This article is an effort to demystify remoting in simple terms and put forth the basic concepts of remoting. Remoting is a very vast and one of the most complex topics in .NET development. Entire books have been written to explain and demonstrate the concept of remoting. This article is an effort to demystify remoting in simple terms and put forth the basic concepts of remoting. Distributed applications allow objects to communicate or talk outside process boundaries and application domains. Enterprise applications benefit greatly from the distributed application architecture. Distributed application development or distributed computing in .NET is typically implemented using one of two approaches - .NET remoting or Web Services. .NET Remoting and XML Web services give developers a rich framework to create distributed applications. But what is .NET Remoting? .NET Remoting allows client applications to instantiate components on remote computers and use them as though they were local objects. Remoting is a mechanism through which a .NET client application can interact with a .NET component that’s part of another application domain. .NET remoting is used when both the client and server are under your control. XML web services are used when they are not. XML Web service objects are single use - they are created at the beginning of each call and destroyed at the end of each call. Remoting enables you to create and use stateful objects. Remoting also offers you great flexibility. Unlike Web services which mostly use SOAP messages to exchange information, remoting allows you to implement and use binary channels as well. Remoting is simple to configure and easy to scale. It’s ideal if you want to maintain state or you need to create a peer to peer application. You should not however make use of distributed computing or remoting needlessly. If you are going to be create components that are going to be on the same computer, you don’t need remoting. If you are designing a small scale system that can work well without a distributed architecture then don’t use it just for the sake of it. The overhead would be too much. There are various actors on the stage of remoting. A remotable class can be invoked remotely. It is typically derived from MarshalByRefObject or a child class of MarshalByRefObject. All the public members of a remotable class can be invoked or used remotely. To use or invoke the remotable object on a client, you need a server. This server must be a dedicated one so that it can listen to client requests and create the remotable objects as and when necessary. The server can either be a console based application, a Windows Forms application with a GUI, or a Windows service. Remotable objects, that is, instances of the remotable class, are classified into two types: Marshal By Value (MBV) and Marshal By Reference (MBR). MBV objects are present on the server. MBV objects are copied and sent from the server application domain to client application domain. When a client calls a method on the MBV object, the object is serialized, transferred over the network and restored on the client as an exact copy of the server-side objects. Once this is done, the object becomes locally available to the client. MBV objects don’t need to be remotely activated because the MBV object itself is transferred to the client side. MBR, on the other hand, are remote objects. They always reside on the server and all methods called on them are executed at the server side. In MBR, a proxy is used to access these objects on the client side. The client just holds a reference to object. The client uses a local proxy object holding the reference to the MBR object in order to call its methods. When to use which? Use MBV for faster performance and fewer network round trips. Use MBR for very large objects or when the functionality of the object is available only in the server on which it is created. MBR objects are of two types: Server activated and client activated. Server Activated Objects (SAO) have lifetimes controlled by the server. The remote object when requested by a client is instantiated or activated on the server only when a client calls a method on the proxy of the remote object that is created on the client side. Only the default constructor can be used to instantiate SAO. SAOs can be either Singleton SAO or Single Call SAOs. You will use a Single Call approach when you don’t want an object to maintain state, when you expect many requests on the server and the overhead of creating an object is not important. You will use Singleton objects when the object needs to retain state, many clients need to work on the same instance and when the overhead of creating the object is substantial. To repeat, server activated objects are not created when the client instantiates them but instead created only when the first method call is made. Remote objects activated as server activated objects are also called well-known objects. Client Activated Objects (CAOs) are created as soon as the client instantiates them. Also, CAOs can use parameterized constructors. The other actors in the remoting world are: a formatter and a transport channel. A formatter packages client requests or server responses in the appropriate format. It can serialize a message into a binary or SOAP format before sending it. SOAP and Binary formatters are the commonly used ones. You can also create custom formatters if you wish. A transport channel transmits the information using the appropriate protocol. HTTP and TCP channels are the commonly used ones. You can also create custom channels if you wish. The System.Runtime.Remoting namespace is the core for implementing .NET remoting architecture. System.Runtime.Remoting This namespace provides classes and interfaces that allow developers to create and configure distributed applications. In addition, other commonly used namespaces for implementing remoting are: System.Runtime.Remoting.Activation System.Runtime.Remoting.Channels System.Runtime.Remoting.Messaging We shall now see an example to understand remoting. Consider that you are running a jewelry manufacturing company named Ark Jewelries and that you have offices scattered all over the globe. Buyer details and product details are stored in a centralized database. You now want to develop a distributed system that will enable an end user in one location to access information from the database using a server present in another location. Consider that you will supply the buyer id through a user interface (in a Windows Forms application) and you need to retrieve the phone number of the buyer based on the id. You wish to make use of remoting for all the advantages that it has to offer. The ideal course of action would be to have a database logic class that will act as a remotable class, and create a remotable server and client. Finally, invoke an instance of the remotable class in the client. The first step will be to create the remotable class. We shall create this as a class library so that it compiles into a DLL. Launch Visual Studio 2008 and select File-> New Project. Choose Visual C# as the language and Class Library as the project type. Rename the class library as ArkLibrary. Rename the default Class1 class to ArkClass. Replace the default code in the class with the code given below: What was done in the above class is summarized briefly here: : GetPhoneNumber() GetData GetPhoneNumber Next, create a new Windows Forms project in the same solution by right clicking on the Solution and then selecting Add and New Project. Rename the project to ArkMain. Add a Project Referece to System.Runtime.Remoting. Add a reference to the dll created in the previous step – ArkLibrary.dll. Create the user interface for the server as shown in the Figure 3. Replace the default code in the Form with the following code: What was done in the above code is summarized below: btnRun btnShutDown The next action would be to create the client. Create a new Windows Forms project in the same solution named ArkBuyer. Again, add References to ArkLibrary.dll and System.Runtime.Remoting. Create a user interface with a combobox and a button and a text box as shown in the Figure. Replace the default code with the following code: What was done in the above code is summarized briefly: When the client is loaded, the combo box has to be populated with the buyer ids and names. To retrieve this data, the GetData() method of the remotable object has to be invoked. Hence, the client creates and registers a channel. Then it registers the remotable object as a well-known type and creates an instance of it. The method GetData() is then invoked and the data is populated into the combo box. When the end user selects a buyer id, the corresponding phone number has to be retrieved. To do this, the GetPhoneNumber() method of the remotable object is invoked and the relevant data is finally retrieved and displayed. GetData() GetPhoneNumber() As this was an MBR, the methods will be executed at the server side. And because this is a Singleton mode, the object will retain state. Build each of the projects. To run each project, select “Debug-> Start new instance” from the Context menu. Some dummy data has been entered into the database. The output of the client is seen in the Figure: You’ve learned what is remoting, what are its advantages, what are the different terms used in remoting, and also explored an example that demonstrated remoting in action.
http://dotnetslackers.com/articles/net/Understanding-NET-Remoting.aspx
crawl-003
refinedweb
1,618
56.55
If you'd missed it ... Visual Studio 2008 Beta 2 Professional was made available for download last Friday. The marketing blurb about it is below. Note : if you already have the Windows Mobile 6 SDK or SDK Refresh installed, you'll need to re-install it after you're done with installing the VIsual Studio 2008 Beta 2. Download Link Visual Studio 2008 delivers on Microsoft’s vision of smart client applications by letting developers quickly create connected applications that deliver the highest quality rich user experiences.. Visual Studio 2008 Beta 2 is available for download from July 27th 2007 and introduces several new features for mobile developers. New Features for Mobile Developers · Unit testing is now available to mobile developers o Developers have told us that testing mobile applications is time consuming and costly. Visual Studio 2008 enables automated functional testing of managed code to reduce that burden. · Latest Device Emulator (version 3.0) o You can now automate testing scenarios in the device emulator allowing you to simulate real world changes in device state – signal dropoff, battery running dead etc · Latest .NET Compact Framework (version 3.5) o .NET Compact Framework 3.5 introduces new features like LINQ as well as an implementation of the Windows Communication Foundation enabling device to device and device to server communication over the Exchange Activesync transport · Designer support for SQL Server 3.5 Compact Edition o You can now build SQL Server 3.5 Compact Edition applications using the Visual Studio 2008 designer experience Mobile developers will need to use Visual Studio 2008 Professional Beta 2 and above to build Windows Mobile applications. Supported Platforms · .NET Compact Framework 3.5 · .NET Compact Framework 2.0 · .NET Compact Framework 1.0 (projects will be upgraded to 2.0) · Windows Mobile 6 (by installing the Windows Mobile 6 SDK Refresh) · Windows Mobile 5.0 · Pocket PC 2003 (managed and native code) · Smartphone 2003 (native code only) · Windows Embedded CE 6.0 · Windows Embedded CE 5.0 If you would like to receive an email when updates are made to this post, please register here RSS Why no unit testing for us Native C++ developers? Does the new .net cf 3.5 include CardSpace for mobile? Cheers Matt What's about Mobile Asp.Net ? I don't find it in Beta 2 Vs 2008. Unit testing on native : I'll post back on that in due course. Just gathering some information from our development team. Cardspace mobile : We do not have that in NET CF 3.5 Mobile ASP.NET : We have a webcast scheduled for September on using the ASP.NET AJAX Toolkit to build web apps for Windows Mobile. It will be accompanied by an article as well. Now why not improve the Windows Mobile Device center sync to work well with Vista. With Orcas beta 2, i can't use System.Net.NetworkInformation namespace for sending a ping in WM6. Why? How i can send ping in WM6? Will it be possible to use the final Visual Studio 2008 *Standard* edition to develop mobile applications, As it is now the case with VS2005? (I'm considering the price here.) Hmm,... if installing Visual Studio 2008 beta 2 on a clean maching, I am unable to install the Windows Mobile SDK Refresh. The installer claims that "Visual Studio 2005 or later is not installed"! How can I solve this? Best Regards Steffe That's what I got when I was trying to install the *Standard* edition (which has no support for mobile development). (I haven't tried the Pro edition for Beta 2, but I did for Beta 1 and it worked.) I'd like to debug unit test inside VS 2008, is it possible? Run test works fine but can't have debugger break when selecting Debug Test option. You're correct, you need the Professional version of Visual Studio 2008 to get the mobile development features. The Visual Studio 2008 SKU structure is based on how our customers were using Visual Studio 2005. Very few customers use Visual Studio 2005 Standard to build applications for Windows Mobile devices so in order to deliver a Standard SKU that is simplified and tuned to the customers that use it, Visual Studio 2008 Standard no longer includes support for mobile development. If you're concerned about the cost of Visual Studio Professional, you should consider joining the ISV Empower Program which is designed for Independent Software Vendors and provides limited Microsoft software licenses – including Visual Studio – for internal use, development and testing and technical support. Registration with the program costs around $375 for companies in the United States. Please consult for a list of other countries which have an ISV Empower Program. ISV Empower Program Overview : I have a question about ISV Empower program: it comes with VS2005, but if we develop an app with VS2005 that maybe will last 18 months of development, when we have the final release it will be older in technology, you know what I mean???? So what happen with the VS2008???? Is there "Standard SDK" for Windows CE 5.0 and/or Windows CE 6.0 which will work with VS2008? Is there any intentions to include reporting and the ability to print them in VS 2008? Microsoft just announced the launch of Visuak Studio 2008, which is close to my heart as I was part of I saw the story at Visual Studio 2008 adds mobile application features that summarised the new features Manchmal muss ich leider auch, entgegen meiner Jobbezeichnung "Evangelist" (= "Überbringer guter Nachrichten"), Manchmal muss ich leider auch, entgegen meiner Jobbezeichnung "Evangelist" (= "Überbringer This is annoying The download page states the following are pre-requisites: * Microsoft Visual Studio 2005, Standard Edition or above (Express Editions are not supported). SP1 recommended. So I purchased a new Windows smartphone (TyTN II - I have previously stuck with Symbian) and now I find I cant do the development I wanted to do after all as I have an 'above' verison of Visual Studio, i.e. 2008 standard, but M$ have changed the goal posts. I wonder how sympathetic they'll be when people start asking for refunds. I dont understand why the Windows Mobile 6.0 SDK is not inbuilt in the Visual Studio 2008 professional. Why there is a seperate download and installation post installing VS 2008. M$ is ridiculous. I attended the lauch for "heroes happen here". They give out both VS2008 (standard) and windows mobile 6 resource kits. Go to install resource kit, doesn't work with VS2008 standard. Java's looking better and better all the time.. This does suck. Attended the Heroes happen here event... got VS2008 standard only to find out that I cannot use the Mobile SDK without spending $375+. So much for Microsoft really caring for developers. Maybe I'll just hop on the Android bandwagon. I have to say I am annoyed at the lack of support in VS2008 Standard Edition too. I occasionally develop for the Compact Framework at work, and of course we pay for the right tool for the job - but as a hobbyist, I can't afford the Professional edition just to experiment with. With a Palm device, or older versions of the Pocket PC, it used to be possible to experiment with development on a personal device cheaply. Now my Palm has died, I'm looking for what to replace it with and I'm struggling to find a platform that I'll be able to tinker with. If you want to give Windows Mobile a boost I strongly suggest that one of the things you should consider is making it easier and cheaper to develop for it, as you've done for Windows itself. You're currently going in the wrong direction. Wish this had been more clear on the WM SDK pages. By that I mean -- mentioned at all. I recently purchased VS 2008 Standard specifically for mobile applications, deciding that it would be a safer choice than VS 2005 Standard. Instead it was a total waste of money. I have no use for it. Very very not happy. It is indeed disappointing for developers to pay for the Pro version to get WM development capability, when numerous other mobile platforms give away tools for free to create Developer mind share and support. Apple and RIM are clear examples of such strategies. I fail to understand, why Microsoft has chosen to reverse their strategy in this context from VS 2005. Continues to baffle my mind ???? I love the Microsoft Developer platform and would like to see Microsoft uphold their prior support for WM Developers. There is any chance to use VS 2008 Unit testing for Smart Device Database applications? Are you kidding me?!?! Does Microsoft want to encourage people to develop for Windows Mobile, or not? Yep, I too have vs 2008 standard and just bought a Windows Mobile 6.1 phone to start developing apps and find I can't !!! Having followed MS development path throughout the whole Vista/WPF/Silverlight debarcle, I am getting more and more frustrated with Microsoft and have begun retraining. So long M$ Happy trails to you all, you won't be getting any more of my money ! Wow, I purchased 2K8 Std with mobile development in mind. Guess that was a waste of money. I make the recommendations for my org, and I have thus far been advocating windows mobile over Blackberry as we are a Microsoft shop. . Blackberry is looking better and better every day. We don't have a BES yet, but I am going to need to re-think my position... With Motorola getting out of the smart phone biz, and Microsoft creating toolset scarcity, it will be a miracle if windows mobile ever gets market share. And market share is everything. Ditto to the above. Have wasted a day trying to make VS 2008 Standard work for my Mobile projects. Bad choice Microsoft and even worse documentation.
http://blogs.msdn.com/windowsmobile/archive/2007/07/30/visual-studio-beta-2-professional-available-for-download.aspx
crawl-002
refinedweb
1,665
65.22
NOTICE This package is discontinued. It will not be maintained or upgraded in the future. This package combines two functionalities: package:URI to a platform specific URI (usually http:or file:, depending on the platform) The former no longer makes sense when a large number of Dart programs are ahead-of-time compiled. Those programs do not have access to source files at runtime, and a package: URI references a source file. There is no standard way to find a runtime location of a source file, or even ensure that it is available. The platform specific loading functionality can still be useful. However, without a way to produce such platform specific URIs from platform independent ones, the only URIs which can still be loaded on all platforms are http:/ https: ones. Loading those is better supported by the http package. As such, this package can no longer supports its original goal, being a cross platform resource loading solution. It will be discontinued rather than provide an inadequate solution. Reading data from package contents and files. A resource is data that can be read into a Dart program at runtime. A resource is identified by a URI. It can be loaded as bytes or data. The resource URI may be a package: URI. Example: import 'package:resource/resource.dart' show Resource; import 'dart:convert' show utf8; main() async { var resource = new Resource("package:foo/foo_data.txt"); var string = await resource.readAsString(encoding: utf8); print(string); } Please check out the API docs. Please file feature requests and bugs at the issue tracker.
https://dart.googlesource.com/resource/
CC-MAIN-2020-29
refinedweb
260
67.45
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. Print report of another related model I created a new model and report for this model. In this new model, one of the fields is a Many2one with the model sale.order In can easily print my report from the new model views. And I would also be able to print this same report from the sale.order form view. I want to add a button that call a method (done), this method get all new model records linked to my sale.order id and i lunch the print. But i am completely lost and i cannot find the good keywords to find my answer on Google. So, need your help :0 Hi you can write a code that will call your method and return report action to print report. May be below code helps you. @api.multi def your_method_name(self): #your code to call method(done) #code for print report data = {'ids': self.ids,(list of ids that you need for print report) 'model': 'model',(eg.'sale.order') 'form': self.read([])[0], } return {'type': 'ir.actions.report.xml', 'report_name': 'your report name', 'report_type': "qweb-pdf", 'datas': data } Hi, Thanks, but I still need some help. I have this error : TypeError: sale.order.products(1, 2, 3) is not JSON serializable And, the model that i put data json, should be sale.order or sale.order.products ? ----------------------------------------------------------------- class my_class(models.Model): _inherit = 'sale.order' products = fields.One2many(comodel_name='sale.order.products', inverse_name='order_id') @api.multi def my_print_method(self): data = {'ids': self.products, 'model': 'sale.order.products', 'form': self.read([])[0], } return {'type': 'ir.actions.report.xml', 'report_name': 'mymodule.sale_order_products_report', 'report_type': "qweb-pdf", 'datas': data } please use 'ids': self.products.ids instead of self.products thanks. I get this message: QWebException: ('MissingError', u'Record does not exist or has been deleted.') I tried to change: 'model': 'sale.order.products', to 'model': 'sale.order', But same result. Of course the ids exist. Don't know what i am missing. I am still stucked on it, if you have some idea About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/print-report-of-another-related-model-107320
CC-MAIN-2017-39
refinedweb
393
62.54
Upcasting Posted on March 1st, 2001. You also saw a problem arise, which is embodied in the following: (See page 97 if you have trouble executing this program.) //: Music.java // Inheritance & upcasting package c07; class Note { private int value; private Note(int val) { value = val; } public static final Note middleC = new Note(0), cSharp = new Note(1), cFlat =C); } public static void main(String[] args) { Wind flute = new Wind(); tune(flute); // Upcasting } } ///:~ The method Music.tune( ) accepts an Instrument handle, but also anything derived from Instrument. In main( ), you can see this happening as a Wind handle is passed to tune( ), with no cast necessary. This is acceptable; the interface in Instrument must exist in Wind, because Wind is inherited from Instrument. Upcasting from Wind to Instrument may “narrow” that interface, but it cannot make it anything less than the full interface to Instrument. Why upcast? This program might seem strange to you. Why should anyone intentionally forget the type of an object? This is what happens when you upcast, and it seems like it could be much more straightforward if tune( ) simply takes a Wind handle as its argument. This brings up an essential point: If you did that, you’d need to write a new tune( ) for every type of Instrument in your system. Suppose we follow this reasoning and add Stringed and Brass instruments: //: Music2.java // Overloading instead of upcasting class Note2 { private int value; private Note2(int val) { value = val; } public static final Note2 middleC = new Note2(0), cSharp = new Note2(1), cFlat = new Note2(2); } // Etc. class Instrument2 { public void play(Note2 n) { System.out.println("Instrument2.play()"); } } class Wind2 extends Instrument2 { public void play(Note2 n) { System.out.println("Wind2.play()"); } } class Stringed2 extends Instrument2 { public void play(Note2 n) { System.out.println("Stringed2.play()"); } } class Brass2 extends Instrument2 { public void play(Note2 n) { System.out.println("Brass2.play()"); } } public class Music2 { public static void tune(Wind2 i) { i.play(Note2.middleC); } public static void tune(Stringed2 i) { i.play(Note2.middleC); } public static void tune(Brass2 i) { i.play(Note2.middleC); } public static void main(String[] args) { Wind2 flute = new Wind2(); Stringed2 violin = new Stringed2(); Brass2 frenchHorn = new Brass2(); tune(flute); // No upcasting tune(violin); tune(frenchHorn); } } ///:~ This works, but there’s a major drawback: You must write type-specific methods for each new Instrument2? That’s exactly what polymorphism allows you to do. However, most programmers (who come from a procedural programming background) have a bit of trouble with the way polymorphism works. There are no comments yet. Be the first to comment!
https://www.codeguru.com/java/tij/tij0076.shtml
CC-MAIN-2018-26
refinedweb
431
56.05
First of all, the problem of handling spaces in arguments is NOT actually a Java problem. Rather it is a problem that needs to be handled by the command shell that you are using when you run a Java program. As an example, let us suppose that we have the following simple program that prints the size of a file: import java.io.File; public class PrintFileSizes { public static void main(String[] args) { for (String name: args) { File file = new File(name); System.out.println("Size of '" + file + "' is " + file.size()); } } } Now suppose that we want print the size of a file whose pathname has spaces in it; e.g. /home/steve/Test File.txt. If we run the command like this: $ java PrintFileSizes /home/steve/Test File.txt the shell won't know that /home/steve/Test File.txt is actually one pathname. Instead, it will pass 2 distinct arguments to the Java application, which will attempt to find their respective file sizes, and fail because files with those paths (probably) do not exist. POSIX shells include sh as well derivatives such as bash and ksh. If you are using one of these shells, then you can solve the problem by quoting the argument. $ java PrintFileSizes "/home/steve/Test File.txt" The double-quotes around the pathname tell the shell that it should be passed as a single argument. The quotes will be removed when this happens. There are a couple of other ways to do this: $ java PrintFileSizes '/home/steve/Test File.txt' Single (straight) quotes are treated like double-quotes except that they also suppress various expansions within the argument. $ java PrintFileSizes /home/steve/Test\ File.txt A backslash escapes the following space, and causes it not to be interpreted as an argument separator. For more comprehensive documentation, including descriptions of how to deal with other special characters in arguments, please refer to the quoting topic in the Bash documentation. The fundamental problem for Windows is that at the OS level, the arguments are passed to a child process as a single string (source). This means that the ultimate responsibility of parsing (or re-parsing) the command line falls on either program or its runtime libraries. There is lots of inconsistency. In the Java case, to cut a long story short: You can put double-quotes around an argument in a java command, and that will allow you to pass arguments with spaces in them. Apparently, the java command itself is parsing the command string, and it gets it more or less right However, when you try to combine this with the use of SET and variable substitution in a batch file, it gets really complicated as to whether double-quotes get removed. The cmd.exe shell apparently has other escaping mechanisms; e.g. doubling double-quotes, and using ^ escapes. For more detail, please refer to the Batch-File documentation.
https://riptutorial.com/java/example/22925/spaces-and-other-special-characters-in-arguments
CC-MAIN-2022-40
refinedweb
483
63.8
With technological advances, we're at the point where our devices can use their built-in cameras to accurately identify and label images using a pre-trained data set. You can also train your own models, but in this tutorial, we'll be using an open-source model to create an image classification app. I'll show you how to create an app that can identify images. We'll start with an empty Xcode project, and implement machine-learning-powered image recognition one step at a time. Getting Started Xcode Version Before we begin, make sure you have the latest version of Xcode installed on your Mac. This is very important because Core ML, or if you don't have it, download it for free. Sample Project New Project After you have made sure you have the right version of Xcode, you'll need to make a new Xcode project. Go ahead and open Xcode and click Create a new Xcode project. Next, you'll need to choose a template for your new Xcode project. It's pretty common to use a Single View App, so go ahead and select that and click Next. You can name your project anything you like, but I will be naming mine CoreML Image Classification. For this project, we'll be using Swift, so make sure that it's selected in the Language dropdown. Preparing to Debug-related apps). If you already have an iPhone connected to Xcode, you can skip ahead to the next step. A nifty new feature in Xcode 9 is that you can wirelessly debug your app on a device, so let's take the time. To add other devices, you can follow a similar process. Simulator Selection When you want to finally use your iPhone to debug, simply select it from the dropdown beside the Run button. You should see a network icon next to it, showing that it's connected for wireless debugging. I've selected Vardhan's iPhone, but you need to select your specific device. Diving Deeper Now that you've created your project and set up your iPhone as a simulator, we'll dive a bit deeper and begin programming the real-time image classification app. Preparing Your Project Getting a Model To be able to start making your Core ML image classification app, you'll first need to get the Core ML model from Apple's website. As I mentioned before, you can also train your own models, but that requires a separate process. If you scroll to the bottom of Apple's machine learning website, you'll be able to choose and download a model. In this tutorial, I will be using the MobileNet.mlmodel model, but you can use any model as long as you know its name and can ensure that it ends in .mlmodel. Importing Libraries There are a couple of frameworks you'll need to import along with the usual UIKit. At the top of the file, make sure the following import statements are present: import UIKit import AVKit import Vision We'll need AVKit because we'll be creating an AVCaptureSession to display a live feed while classifying images in real time. Also, since this is using computer vision, we'll need to import the Vision framework. Designing Your User Interface An important part of this app is displaying the image classification data labels as well as the live video feed from the device's camera. To begin designing your user interface, head to your Main.storyboard file. Adding an Image View Head to the Object Library and search for an Image View. Simply drag this onto your View Controller to add it in. If you'd like, you can also add a placeholder image so that you can get a general idea of what the app will look like when it's being used. If you do choose to have a placeholder image, make sure that the Content Mode is set to Aspect Fit, and that you check the box which says Clip to Bounds. This way, the image will not appear stretched, and it won't appear outside of the UIImageView box. Here's what your storyboard should now look like: Adding a View Back in the Object Library, search for a View and drag it onto your View Controller. This will serve as a nice background for our labels so that they don't get hidden in the image being displayed. We'll be making this view translucent so that some of the preview layer is still visible (this is just a nice touch for the user interface of the app). Drag this to the bottom of the screen so that it touches the container on three sides. It doesn't matter what height you choose because we'll be setting constraints for this in just a moment here. Adding Labels This, perhaps, is the most important part of our user interface. We need to display what our app thinks the object is, and how sure it is (confidence level). As you've probably guessed, you'll need to drag two Label(s) from the Object Library to the view we just created. Drag these labels somewhere near the center, stacked on top of each other. For the top label, head to the Attributes Inspector and click the T button next to the font style and size and, in the popup, select System as the font. To differentiate this from the confidence label, select Black as the style. Lastly, change the size to 24. For the bottom label, follow the same steps, but instead of selecting Black as the style, select Regular, and for the size, select 17. The image below shows how your Storyboard should look when you've added all these views and labels. Don't worry if they aren't exactly the same as yours; we'll be adding constraints to them in the next step. Adding Constraints In order for this app to work on different screen sizes, it's important to add constraints. This step isn't crucial to the rest of the app, but it's highly recommended that you do this in all your iOS apps. Image View Constraints The first thing to constrain is our UIImageView. To do this, select your image view, and open the Pin Menu in the bottom toolbar (this looks like a square with the constraints and it's the second from the right). Then, you'll need to add the following values: Before you proceed, make sure that the Constrain to Margins box isn't checked as this will create a gap between the screen and the actual image view. Then, hit Enter. Now your UIImageView is centered on the screen, and it should look right on all device sizes. View Constraints Now, the next step is to constrain the view on which the labels appear. Select the view, and then go to the Pin Menu again. Add the following values: Now, simply hit Enter to save the values. Your view is now constrained to the bottom of the screen. Label Constraints Since the view is now constrained, you can add constraints to the labels relative to the view instead of the screen. This is helpful if you later decide to change the position of the labels or the view. Select both of the labels, and put them in a stack view. If you don't know how to do this, you simply need to press the button (second one from the left) which looks like a stack of books with a downwards arrow. You will then see the buttons become one selectable object. Click on your stack view, and then click on the Align Menu (third from the left) and make sure the following boxes are checked: Now, hit Enter. Your labels should be centered in the view from the previous step, and they will now appear the same on all screen sizes. Interface Builder Outlets The last step in the user interface would be to connect the elements to your ViewController() class. Simply open the Assistant Editor and then Control-Click and Drag each element to the top of your class inside ViewController.swift. Here's what I'll be naming them in this tutorial: UILabel: objectLabel UILabel: confidenceLabel UIImageView: imageView Of course, you can name them whatever you want, but these are the names you'll find in my code. Preparing a Capture Session The live video feed will require an AVCaptureSession, so let's create one now. We'll also be displaying our camera input to the user in real time. Making a capture session is a pretty long process, and it's important that you understand how to do it because it will be useful in any other development you do using the on-board camera on any of Apple's devices. Class Extension and Function To begin, we can create a class extension and then make it conform to the AVCaptureVideoDataOutputSampleBufferDelegate protocol. You can easily do this within the actual ViewController class, but we're using best practices here so that the code is neat and organized (this is the way you would be doing it for production apps). So that we can call this inside of viewDidLoad(), we'll need to create a function called setupSession() which doesn't take in any parameters. You can name this anything you want, but be mindful of the naming when we call this method later. Once you're finished, your code should look like the following: // MARK: - AVCaptureSession extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate { func setupSession() { // Your code goes here } } Device Input and Capture Session The first step in creating the capture session is to check whether or not the device has a camera. In other words, don't attempt to use the camera if there is no camera. We'll then need to create the actual capture session. Add the following code to your setupSession() method: guard let device = AVCaptureDevice.default(for: .video) else { return } guard let input = try? AVCaptureDeviceInput(device: device) else { return } let session = AVCaptureSession() session.sessionPreset = .hd4K3840x2160 Here, we're using a guard let statement to check if the device ( AVCaptureDevice) has a camera. When you try to get the camera of the device, you must also specify the mediaType, which, in this case, is .video. Then, we create an AVCaptureDeviceInput, which is an input which brings the media from the device to the capture session. Finally, we simply create an instance of the AVCaptureSession class, and then assign it to a variable called session. We've customized the session bitrate and quality to Ultra-High-Definition (UHD) which is 3840 by 2160 pixels. You can experiment with this setting to see what works for you. Preview Layer and Output The next step in doing our AVCaptureSession setup is to create a preview layer, where the user can see the input from the camera. We'll be adding this onto the UIImageView we created earlier in our Storyboard. The most important part, though, is actually creating our output for the Core ML model to process later in this tutorial, which we'll also do in this step. Add the following code directly underneath the code from the previous step: et previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.frame = view.frame imageView.layer.addSublayer(previewLayer) let output = AVCaptureVideoDataOutput() output.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue")) session.addOutput(output) We first create an instance of the AVCaptureVideoPreviewLayer class, and then initialize it with the session we created in the previous step. After that's done, we're assigning it to a variable called previewLayer. This layer is used to actually display the input from the camera. Next, we'll make the preview layer fill the whole screen by setting the frame dimensions to those of the view. This way, the desired appearance will persist for all screen sizes. To actually show the preview layer, we'll add it in as a sub-layer of the UIImageView that we created when we were making the user interface. Now, for the important part: We create an instance of the AVCaptureDataOutput class and assign it to a variable called output. Input and Start Session Finally, we're done with our capture session. All that's left to do before the actual Core ML code is to add the input and start the capture session. Add the following two lines of code directly under the previous step: // Sets the input of the AVCaptureSession to the device's camera input session.addInput(input) // Starts the capture session session.startRunning() This adds the input that we created earlier to the AVCaptureSession, because before this, we'd only created the input and hadn't added it. Lastly, this line of code starts the session which we've spent so long creating. Integrating the Core ML Model We've already downloaded the model, so the next step is to actually use it in our app. So let's get started with using it to classify images. Delegate Method To begin, you'll need to add the following delegate method into your app: func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { // Your code goes here } This delegate method is triggered when a new video frame is written. In our app, this happens every time a frame gets recorded through our live video feed (the speed of this is solely dependent on the hardware which the app is running on). Pixel Buffer and Model Now, we'll be turning the image (one frame from the live feed) into a pixel buffer, which is recognizable by the model. With this, we'll be able to later create a VNCoreMLRequest. Add the following two lines of code inside the delegate method you created earlier: guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } guard let model = try? VNCoreMLModel(for: MobileNet().model) else { return } First we create a pixel buffer (a format which Core ML accepts) from the argument passed in through the delegate method, and then assign it to a variable called pixelBuffer. Then we assign our MobileNet model to a constant called model. Notice that both of these are created using guard let statements, and that the function will return if either of these are nil values. Creating a Request After the previous two lines of code have been executed, we know for sure that we have a pixel buffer and a model. The next step would be to create a VNCoreMLRequest using both of them. Right below the previous step, paste the following lines of code inside of the delegate method: let request = VNCoreMLRequest(model: model) { (data, error) in { // Your code goes here } Here, we're creating a constant called request and assigning it the return value of the method VNCoreMLRequest when our model is passed into it. Getting and Sorting Results We're almost finished! All we need to do now is get our results (what the model thinks our image is) and then display them to the user. Add the next two lines of code into the completion handler of your request: // Checks if the data is in the correct format and assigns it to results guard let results = data.results as? [VNClassificationObservation] else { return } // Assigns the first result (if it exists) to firstObject guard let firstObject = results.first else { return } If the results from the data (from the completion handler of the request) are available as an array of VNClassificationObservations, this line of code gets the first object from the array we created earlier. It will then be assigned to a constant called firstObject. The first object in this array is the one for which the image recognition engine has the most confidence. Displaying Data and Image Processing Remember when we created the two labels (confidence and object)? We'll now be using them to display what the model thinks the image is. Append the following lines of code after the previous step: if firstObject.confidence * 100 >= 50 { self.objectLabel.text = firstObject.identifier.capitalized self.confidenceLabel.text = String(firstObject.confidence * 100) + "%" } The if statement makes sure that the algorithm is at least 50% certain about its identification of the object. Then we just set the firstObject as the text of the objectLabel because we know that the confidence level is high enough. We'll just display the certainty percentage using the text property of confidenceLabel. Since firstObject.confidence is represented as a decimal, we'll need to multiply by 100 to get the percentage. The last thing to do is to process the image through the algorithm we just created. To do this, you'll need to type the following line of code directly before exiting the captureOutput(_:didOutput:from:) delegate method: try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request]) Conclusion The concepts you learned in this tutorial can be applied to many kinds of apps. I hope you've enjoyed learning to classify images using your phone. While it may not yet be perfect, you can train your own models in the future to be more accurate. Here's what the app should look like when it's done: While you're here, check out some of our other posts on machine learning and iOS app development! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/image-classification-through-machine-learning-using-coreml--cms-29819
CC-MAIN-2019-22
refinedweb
2,902
60.75
The Java Specialists' Newsletter Issue 1242006-03-28 Category: Performance Java version: JDK 1.5.0_06 GitHub Subscribe Free RSS Feed Welcome to the 124th edition of The Java(tm) Specialists' Newsletter, which I started writing for you in Las Vegas, where I had the fortune of attending TheServerSide Java Symposium. One of the highlights of these conferences is the networking during coffee breaks. Shaking hands with the likes of Ted Neward, Kirk Pepperdine, Bruce Snyder, Bruce Tate, Stephan Janssen, Rod Johnson, Adrian Coyler, Gregor Hohpe and Eugene Ciurana. At the TSSJS conferences you can get easy access to the speakers. It was also great linking up with my old friends from Estonia and with suscribers from around the world, such as David Jones (who wrote J2EE Singleton for us many years ago) and Robert Lentz, a Java Architect from Germany. On Friday night Kirk Pepperdine and I led a Birds-of-a-Feather (BoF) on whether performance testing was still a relevant activity. Some people think that instead of tuning the performance, one could simply buy more hardware. This is not always the case. For example, if you are hitting the limits of memory, the garbage collector may degrade the performance of the entire system to such an extent that the only option is to fix the problem. The difficulty with looking at performance, as we will see in this newsletter, is eliminating the noise from the problem. Beware of the microbenchmark! NEW: We have revised our "Advanced Topics" course, covering Reflection, Java NIO, Data Structures, Memory Management and several other useful topics for Java experts to master. 2 days of extreme fun and learning. Extreme Java - Advanced Topics. A month ago, my friend Paul van Spronsen sent me this puzzle (Paul wrote an excellent newsletter on multicasting in Java): Look at the attached class. Guess which test will be faster and then run X.main. Startling result. import java.util.Random; public class X { private final byte[] byteValue = new byte[16]; X() { new Random(0).nextBytes(byteValue); } public byte[] testClone() { return byteValue.clone(); } public byte[] testNewAndCopy() { byte[] b = new byte[byteValue.length]; System.arraycopy(byteValue, 0, b, 0, byteValue.length); return b; } public static void main(String[] args) { doTest(); doTest(); } private static void doTest() { X x = new X(); int m = 50000000; long t0 = System.currentTimeMillis(); for (int i = 0; i < m; i++) { x.testClone(); } long t1 = System.currentTimeMillis(); System.out.println("clone(): " + (t1 - t0)); t0 = System.currentTimeMillis(); for (int i = 0; i < m; i++) { x.testNewAndCopy(); } t1 = System.currentTimeMillis(); System.out.println("arraycopy(): " + (t1 - t0)); } } I guessed, based on previous experience, that the testNewAndCopy() would be faster. The System.arrayCopy() method uses JNI to copy the memory and I knew that was fast. (I also knew my friend Paul would only send me a puzzle if the result was surprising) Here we see that clone takes about 5 times longer than copying the array: testNewAndCopy() System.arrayCopy() clone(): 26598 arraycopy(): 5618 clone(): 26639 arraycopy(): 5648 We could run off now and change all our code to use the more verbose approach instead of clone(), and expect to see an improvement in performance. clone() Beware of the Microbenchmark! I cannot emphasize this enough. When we encounter surprises, we need to find out why they are there. Changing code before knowing why it is slower can result in ugly, slow code. When I showed this to Kirk Pepperdine at TheServerSide Java Symposium, he suggested that I would need to look at the source code of clone() to see why there was such a large difference. But before we do that, let's have a look at some more robust testing classes. First off, a class that runs a method repeatedly within some time period. Here, higher numbers are better. This time I added some JavaDocs to explain how it works. Please let me know if you like seeing JavaDocs in the code, or if I can strip them out? import java.util.*; /** * The PerformanceChecker tries to run the task as often as possible * in the allotted time. It then returns the number of times that * the task was called. To make sure that the timer stops the test * timeously, we check that the difference between start and end * time is less than EPSILON. After it has tried unsuccessfully for * MAXIMUM_ATTEMPTS times, it throws an exception. * * @author Heinz Kabutz * @since 2006/03/27 */ public class PerformanceChecker { /** * Whether the test should continue running. Will expire after * some time specified in testTime. Needs to be volatile for * visibility. */ private volatile boolean expired = false; /** The number of milliseconds that each test should run */ private final long testTime; /** The task to execute for the duration of the test run. */ private final Runnable task; /** * Accuracy of test. It must finish within 20ms of the testTime * otherwise we retry the test. This could be configurable. */ public static final int EPSILON = 20; /** * Number of repeats before giving up with this test. */ private static final int MAXIMUM_ATTEMPTS = 3; /** * Set up the number of milliseconds that the test should run, and * the task that should be executed during that time. The task * should ideally run for less than 10ms at most, otherwise you * will get too many retry attempts. * * @param testTime the number of milliseconds that the test should * execute. * @param task the task that should be executed repeatedly * until the time is used up. */ public PerformanceChecker(long testTime, Runnable task) { this.testTime = testTime; this.task = task; } /** * Start the test, and after the set time interrupt the test and * return the number of times that we were able to execute the * run() method of the task. */ public long start() { long numberOfLoops; long start; int runs = 0; do { if (++runs > MAXIMUM_ATTEMPTS) { throw new IllegalStateException("Test not accurate"); } expired = false; start = System.currentTimeMillis(); numberOfLoops = 0; Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { expired = true; } }, testTime); while (!expired) { task.run(); numberOfLoops++; } start = System.currentTimeMillis() - start; timer.cancel(); } while (Math.abs(start - testTime) > EPSILON); collectGarbage(); return numberOfLoops; } /** * After every test run, we collect garbage by calling System.gc() * and sleeping for a short while to make sure that the garbage * collector has had a chance to collect objects. */ private void collectGarbage() { for (int i = 0; i < 3; i++) { System.gc(); try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } } I do not like running performance tests without calculating the standard deviation of the average, otherwise we cannot detect how noisy the environment is. Here is a class to calculate mean and standard deviation: import java.util.*; /** * Calculates the mean and average of a series of numbers. Not the * most efficient algorithm, but fast enough. * * @author Heinz Kabutz */ public class Average { /** The set of values stored as doubles. Autoboxed. */ private Collection<Double> values = new ArrayList<Double>(); /** * Add a new value to the series. Changes the values returned by * mean() and stddev(). * @param value the new value to add to the series. */ public void add(double value) { values.add(value); } /** * Calculate and return the mean of the series of numbers. * Throws an exception if this is called before the add() method. * @return the mean of all the numbers added to the series. * @throws IllegalStateException if no values have been added yet. * Otherwise we could cause a NullPointerException. */ public double mean() { int elements = values.size(); if (elements == 0) throw new IllegalStateException("No values"); double sum = 0; for (double value : values) { sum += value; } return sum / elements; } /** * Calculate and return the standard deviation of the series of * numbers. See Stats 101 for more information... * Throws an exception if this is called before the add() method. * @return the standard deviation of numbers added to the series. * @throws IllegalStateException if no values have been added yet. * Otherwise we could cause a NullPointerException. */ public double stddev() { double mean = mean(); double stddevtotal = 0; for (double value : values) { double dev = value - mean; stddevtotal += dev * dev; } return Math.sqrt(stddevtotal / values.size()); } } I know we will cause noise in the system, but what I definitely want to prevent is objects ending up in the Old Space. The point at which an object is put into Old Space is when it is larger than 512kb. Since byte[] takes up 8 bytes for the object pointer and 4 bytes for the array length, the largest byte array that will fit into Young Space is 512 * 1024 - 12. Try it out! We experiment with this in our Java Performance Tuning Course, and essential course if you are coding in Java. byte[] Here we calculate the performance of a PerformanceChecker instance, based on the given number of runs. The result that comes back is an instance of Average. The standard deviation should be as small as possible. If it is large, then we know that there was background noise and that the values might or might not be invalid. /** * This class calculates the performance of a PerformanceChecker * instance, based on the given number of runs. * * @author Heinz Kabutz */ public class PerformanceHarness { /** * We calculate the average number of times that the check * executed, together with the standard deviation. * @param check The test that we want to evaluate * @param runs How many times it should be executed * @return an average number of times that test could run */ public Average calculatePerf(PerformanceChecker check, int runs) { Average avg = new Average(); // first we warm up the hotspot compiler check.start(); check.start(); for(int i=0; i < runs; i++) { long count = check.start(); avg.add(count); } return avg; } } We now need to run this with the clone and array copy tests. First, I define some code for each of these test cases. import java.util.Random; public class ArrayCloneTest implements Runnable { private final byte[] byteValue; public ArrayCloneTest(int length) { byteValue = new byte[length]; // always the same set of bytes... new Random(0).nextBytes(byteValue); } public void run() { byte[] result = byteValue.clone(); } } import java.util.Random; public class ArrayNewAndCopyTest implements Runnable { private final byte[] byteValue; public ArrayNewAndCopyTest(int length) { byteValue = new byte[length]; // always the same set of bytes... new Random(0).nextBytes(byteValue); } public void run() { byte[] b = new byte[byteValue.length]; System.arraycopy(byteValue, 0, b, 0, byteValue.length); } } We can now run the complete benchmark, by writing a CompleteTest class that tests everything thoroughly. In order to make this interesting, I test the difference between clone() and copy() for various sizes of byte[]. As mentioned before, we have to be careful not to exceed the maximum size of byte[] that can exist in the Young Space, otherwise the performance will degrade to such an extent that the whole test will fail. public class CompleteTest { private static final int RUNS = 10; private static final long TEST_TIME = 100; public static void main(String[] args) throws Exception { test(1); test(10); test(100); test(1000); test(10000); test(100000); } private static void test(int length) { PerformanceHarness harness = new PerformanceHarness(); Average arrayClone = harness.calculatePerf( new PerformanceChecker(TEST_TIME, new ArrayCloneTest(length)), RUNS); Average arrayNewAndCopy = harness.calculatePerf( new PerformanceChecker(TEST_TIME, new ArrayNewAndCopyTest(length)), RUNS); System.out.println("Length=" + length); System.out.printf("Clone %.0f\t%.0f%n", arrayClone.mean(), arrayClone.stddev()); System.out.printf("Copy %.0f\t%.0f%n", arrayNewAndCopy.mean(), arrayNewAndCopy.stddev()); System.out.printf("Diff %.2fx%n", arrayNewAndCopy.mean() / arrayClone.mean()); System.out.println(); } } When we now run this more comprehensive test, we see an interesting phenomenon. As the byte[] increases in size, the difference between the two techniques disappears. Why is that, you might wonder? Let's first look at the result, before we try to find out why... Length=1 Clone 253606 19767 Copy 1282556 139950 Diff 5.06x Length=10 Clone 240096 10105 Copy 1159128 59049 Diff 4.83x Length=100 Clone 167628 13144 Copy 464809 43279 Diff 2.77x Length=1000 Clone 53575 3535 Copy 68080 7455 Diff 1.27x Length=10000 Clone 8842 162 Copy 7547 713 Diff 0.85x Length=100000 Clone 807 19 Copy 763 90 Diff 0.95x Oops, it seems that once the array becomes longer, the performance of the two is almost equal! Infact, the cloning seems marginally faster. Aren't you glad that you have not changed all your code yet? I followed Kirk's advice and looked at the source code of the clone() method, which you will find in the JVM_Clone method in jvm.c (You will need to download the complete JVM source code from Sun's website). After getting my head around the old C code, I realised that it does two things in addition to plain copying of the memory: It has to be extra careful when copying an object array to not publish pointers without telling the garbage collector, or you would get nasty memory leaks. These tests are in themselves not significant, but when the rest of our work is little (such as when the byte[] is small), then this causes our experiment to skew against cloning. Let's try out what would happen if we were to add those two checks to our test: import java.util.Random; public class ArrayNewAndCopyTest implements Runnable { private final byte[] byteValue; public ArrayNewAndCopyTest(int length) { byteValue = new byte[length]; // always the same set of bytes... new Random(0).nextBytes(byteValue); } public void run() { Class cls = byteValue.getClass(); if (cls.isArray()) { if (!cls.getComponentType().isAssignableFrom(Object.class)) { byte[] b = new byte[byteValue.length]; System.arraycopy(byteValue, 0, b, 0, byteValue.length); return; } } throw new RuntimeException(); } } The results are now almost identical: Length=1 Clone 237416 18007 Copy 235780 13080 Diff 0.99x Length=10 Clone 226804 9614 Copy 231363 12176 Diff 1.02x Length=100 Clone 153981 6809 Copy 169900 9851 Diff 1.10x Length=1000 Clone 50406 2835 Copy 52498 2579 Diff 1.04x Length=10000 Clone 7769 281 Copy 6807 271 Diff 0.88x Length=100000 Clone 724 24 Copy 680 49 Diff 0.94x This leads me to conclude that the only reason why Paul's test seemed so much faster was because he picked a byte[] size that was small enough that the actual copying was dwarfed by the two if statements. Using clone() for copying arrays is less code and the performance difference is, as we saw, only significant for tiny arrays. I think that in future I will rather use clone() than System.arrayCopy(). if It would have been great to eliminate more noise from the experiment, but since we are testing the speed of copying of arrays, we need to create new objects all the time, which then need to be garbage collected. An interesting method that I saw in Brian Goetz's new book on Java Concurrency in Practice (more details soon) is java.util.Arrays.copyOf(byte[] original, int newLength) which was added in JDK 1.6. The copyOf method uses System.arrayCopy() to make a copy of the array, but is more flexible than clone since you can make copies of parts of an array. java.util.Arrays.copyOf(byte[] original, int newLength) copyOf Our new website is now running on a dedicated server, which has stayed up beautifully. I want to make it as easy as possible for you to browse through my past newsletters. Please let me know if you think of ways to make this part of the website more navigable. Kind regards Heinz P.S. Sometimes it helps to cache byte[]'s especially if they are all of the same size and you need to create lots of them. Performance Articles Related Java Course
http://www.javaspecialists.co.za/archive/Issue124.html
CC-MAIN-2016-50
refinedweb
2,562
65.32
Results 1 to 10 of 12 Thread: Get sound from PC Speaker - Join Date - Mar 2008 - 287 Get sound from PC Speaker 1) set bell-style audible in .bashrc 2) for an xterminal have set xset b 100 800 10 3) set alsamixer's card 2 "PC Speak" to 80% and unmuted 4) loaded pcspkr with modprobe 5) have kernel configured with: CONFIG_PCSPKR_PLATFORM=y and CONFIG_INPUT_PCSPKR=m 6) uncommented /sbin/modprobe pcspkr in rc.modules 7) commented blacklist pcspkr in /etc/modprobe.d/blacklist.conf set bell-style audible in /etc/inputrc but cannot cause the PC speaker to make a sound with echo -e "^G" command. This will work but only in console. Any clues for my Slackware (13.0) 2.6.29.6-smp to get a sound from PC speaker using bash in an xterm? Last edited by clickit; 04-26-2011 at 06:05 AM. Reason: added 6, 7 & 8 - Join Date - May 2009 - Location - Oregon - 51 Hmm.. in Slackware 12 & 13 on my machines just using echo -e "\a" causes the audio bell to go off. I am not familiar with control G; though pressing it in an x-term with or without quotes causes a beep on my system. The same is true on urxvt terminals -- I'm running windowmaker as my window-manager. If it works in console, then it isn't a kernel module issue. Try using the escape sequence for audio "\a" and see if it works. - Join Date - Mar 2008 - 287 I too had no trouble with release 12.0. As you can see from what I had to do. The bell I learned was intentionally defeated in 13.0. If I use a console as root or a user I can get the bell. If in an xwindow then no it won't work with either echo ctrl-G or echo \a which I use in numerous scripts. - Join Date - May 2009 - Location - Oregon - 51 Probing the audio bell blockout problem. I assume you have superuser priveleges, so correct me if I am wrong. The connection between X windows and the audio system is where the problem is going to be. Either the terminal program itself has to send the signal or X windows must do it. Even with my audio driver modules disabled, the beep is generated. No evidence of any permanent connections to *any* /dev/ device exists. $( lsof | grep /dev/ ) so there is either a custom socket/node to the pc speaker somewhere, or the X/bash programs on my system are somehow locating the virtual console (owner) from which X11 was launched and using it to produce the beep. (Virtual consoles are hardcoded to audio, I think!...) running a $( strace echo -e "\a" ), I find a disgustingly large number of system calls.... I am about ready to write a C program to get around this garbage. Yep, I did: Code: #include <unistd.h> int main(void) { write( STDOUT_FILENO, "\a", 1 ); } And this is what a system trace of the program looks like. strace ./a.out execve("./a.out", ["./a.out"], [/* 45 vars */]) = 0 brk(0) = 0x804a000 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7739000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) open("/etc/ld.so.cache", O_RDONLY) = 3 fstat64(3, {st_mode=S_IFREG|0644, st_size=97729, ...}) = 0 mmap2(NULL, 97729, PROT_READ, MAP_PRIVATE, 3, 0) = 0xb7721000 close(3) = 0 open("/lib/libc.so.6", O_RDONLY) = 3 read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\3 40l\1"..., 512) = 512 fstat64(3, {st_mode=S_IFREG|0755, st_size=1649149, ...}) = 0 mmap2(NULL, 1452296, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0xb75be000 mprotect(0xb771a000, 4096, PROT_NONE) = 0 mmap2(0xb771b000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x15c) = 0xb771b000 mmap2(0xb771e000, 10504, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xb771e000 close(3) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb75bd000 set_thread_area({entry_number:-1 -> 6, base_addr:0xb75bd6c0, limit:1048575, seg_32bit:1, contents:0, read_exec_only:0, limit_in_pages:1, seg_not_present:0, useable:1}) = 0 mprotect(0xb771b000, 8192, PROT_READ) = 0 mprotect(0xb7758000, 4096, PROT_READ) = 0 munmap(0xb7721000, 97729) = 0 write(1, "\7", 1) = 1 exit_group(1) = ? Process 5032 detached If I do: $( echo -e '\a' | cat - > /dev/null ) There is no beep on my system, proving X11 isn't processing my stdout streams looking for a bell signal. If I do: $( echo -e '\a' > /dev/stderr ), I DO get a beep. (Try that one, stderr is often processed differently than stdout.) Now, to nail this down a bit: Running $( ps -axjf ) will print a program tree showing parent and child programs and ultimately which tty (virtual console) they belong to. Look for X windows, startx, init, etc. whatever you start it by.... and whichever tty it lists for you is the one needing to be checked for having trouble accessing the "Beep". I suspect that you start x windows from an /etc/init.rd script? If so, try exiting X windows (ctrl alt backspace) and see if THAT terminal is able to beep. If it isn't you know where the problem is. If you can't exit X that way, you can kill it from another virtual console (since you can get to one) and restart a simple session using startx from a console that does beep. There is only one thing that could stop a shell from beeping who's parent does BEEP -- and that is if when being forked (created) it's line discipline is reprogrammed or the IO totally redirected. In any event, I (hopefully) have given you enough information to isolate the location of the problem, which is most likely in your *shell* startup scripts, and not X itself as a whole. (running a terminal program like URXVT will have different settings than XTERM and would probably beep if Xterm is the problem. URXVT is also a LOT faster than Xterm, and eats far less memory.) It is possible that the X-term program (alone) has a setting to disable the beeping (since it prints the characters to the X windows screen, it must process the "print" statements from all programs running under it.) So it has to be an Xterm specific setting, or your shell's specific setting causing your problem. It isn't going to be an xorg.conf type problem. (/etc/X11/xorg.conf) if it's an emergency... something you would like to work around by using virtual consoles to activate the beep (it's hairy, but can be done) there is a trick that can be used to redirect a COPY of an interactive shell session to be printed on an invisible console, which is able to beep. eg: a virtual terminal. Let me know what you discover -- I'll see if I can locate the Xterm setting for blink vs. beep (if that's what's happening). Last edited by andrewr; 05-19-2011 at 07:27 AM. - Join Date - May 2009 - Location - Oregon - 51 hmmm... here's something interesting: From an xterm, launch another one: $xterm -mb +vb Now, move to the new xterm and hold a key down; at some point near the right side of the terminal -- a beep ought to sound. "-mb" turns ON the margin bell. "+vb" turns OFF the visual blink(bell replacement), and therefore turns the bell on if it is globally turned off somewhere else. I do have a full install of Slackware 13 (last version) on another machine I just realized, and I don't recall there being a no-beep situation. If none of what I am pointing out detects the problem -- I'll go check that machine. It doesn't launch the X window system from a startup script though (rc.d). cheers. - Join Date - Mar 2008 - 287 Get sound from PC Speaker Wow! Andrewr, U just went over the top in help!! Its late here at this moment and must get rest for tomorrow's jumping lesson so will test out UR suggestions and get back 2 U ASAP. - Join Date - Mar 2008 - 287 Get sound from PC Speaker OK here are the results of suggested probes: 1) echo -e '\a' | cat - > /dev/null NO SOUND echo -e '\a' > /dev/stderr NO SOUND 2) ps -axjf | egrep -i "xwindows|startx|xinit|init" which yields: Warning: bad ps syntax, perhaps a bogus '-'? See procps - Frequently Asked Questions (FAQ) 0 1 1 1 ? -1 Ss 0 0:00 init [3] 3200 3243 3243 3200 tty2 3243 S+ 502 0:00 \_ /bin/sh /usr/X11R6/bin/startx 3243 3262 3243 3200 tty2 3243 S+ 502 0:00 \_ xinit /home/auser/.xinitrc -- /usr/bin/X :0 -auth /home/auser/.serverauth.3243 3262 3268 3268 3200 tty2 3243 S 502 0:00 \_ /bin/sh /home/auser/.xinitrc 3797 3804 3803 3797 pts/2 3803 S+ 502 0:00 \_ egrep -i xwindows|startx|xinit|init 3) .xinitrc is where I copy the /etc/X11/xinit code to in order to startup the various window managers there via startx.When I run past right margin I get neither a bell nor a screen flash. 4) $xterm -mb +vb bash: -mb: command not found $xterm -mb (by itself creates a new xterm and within it the bell does work) 5) /etc/X11/xorg.conf is an empty file under 13.0 default configuration. - Join Date - May 2009 - Location - Oregon - 51 The '-' on ps -axjf is my mistake -- some habits die hard. I am not able to replicate the '-mb' command not found, though. I'll have a friend test it on his Slackware 13 install and see if it happens there and let you know, soon. - Join Date - Mar 2008 - 287 I was able to create an xterm window by running xterm -vb -mb and this time (who knows why??) it worked - got a bell sound as it neared the margin. Do you know of a way for me to apply this to an existing "Terminal" window (it is xterm too). I've apparently lost the means/method to do so. I've clicked preferences on the tool bar and looked in the list of apps window but don't recall how or if I applied it. I tried using the advanced tab and including -vb but I changed it back when it didn't respond as expected. Now when i man some pages I get a "WARNING: terminal is not fully functional". Was able to use echo -e "\a" >/dev/console as root and got the beep but still need it from Terminal as regular user. - Join Date - May 2009 - Location - Oregon - 51 Hmmm.... OK. I wasn't able to reproduce the errors, so I assume it is specific to your machine. There are a couple of choices; You wrote to /dev/console -- which writes to the active console device (parent) of X windows. One option is to change the write permissions to /dev/console so that a group or all users can write to it -- but perhaps not read it (to avoid keyboard sniffing security loophole.) The output on that console can't be trusted since anyone could write it ... but that's up to you. I think what is going on is that the resources for your X11 xterm are not being set when it is launched to the values that you would like. X11 has a resource database for every program under X. Since this problem seems (from the debug info you gave) specific to the xterm program itself, you could load a different terminal program like urxvt which should bypass the problem. Alternatively, you can try applying an X resource as a default to the terminal: My system is started differently than yours, so I am going to show mine as an example -- and you may need to adjust things a little bit. If you have strace on your system (best option), you can actually watch the launching of an xterm with: strace xterm 2>&1 | grep access | less It will show you all the configuration files that xterm read when starting up. Mine looks like: access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) access("/home/andrewr/.Xauthority", R_OK) = 0 access("/usr/share/X11/locale/en_US.UTF-8/XLC_LOCALE", R_OK) = 0("/etc/X11/en_US.UTF8/app-defaults/XTerm", R_OK) = -1 ENOENT (No such file or directory) access("/etc/X11/en/app-defaults/XTerm", R_OK) = -1 ENOENT (No such file or directory) access("/etc/X11/app-defaults/XTerm", R_OK) = 0 access("/usr/share/X11/locale/en_US.UTF-8/Compose", R_OK) = 0 On my system, the startup file for bash enables utf-8 encoding (as well as urxvt terminal program downloaded separately from Slackware.) So the first place xterm checks is the shared locale (and that is unimportant). All the rest of the default files don't exist, until the last two, and only one is important: '/etc/X11/app-defaults/XTerm' Which has an enable visual bell in it, but only as a menu item -- (click on an Xterm and then press and hold ctrl button and middle mouse at the same time to see the menu, visual bell ought to be off. ) -- and that doesn't affect my system; so my system has no enable or disable of the bell in any of the configuration files that my xterm program reads. You might be able to enable the bell from the xterm menu as I just mentioned. There is only one other place resources could have been set on X11, and that is the online resource database. Doing an: xrdb -query would list any special defaults you have. On my system, xrdb -query, returns nothing at all. Another thought you might want to check is: xset q # See what the bell settings are for X windows globally. xset b 100 2000 20 # Set the bell to 100% volume, 2000Hz, 20 milleseconds.... If that turns out to be the problem, and you have trouble getting it into a startup script let me know. To see how your xterms are started (whatever started them, eg: window manager, etc), just do a window listing with the command: xlsclients That should help you debug what you window manager is doing to start the xterm program. And finally, the only other thing I can think of is to add defaults for x-windows programs in an ~/.Xresources file, or an ~/XTerm file. For example. ! ~/XTerm defaults for X windows (andrews) XTerm*bellSuppressTime: 20 XTerm*background: yellow XTerm*marginBell: True XTerm*nMarginBell: 2 XTerm*visualBell: False you can also force a load of the file into the X windows database immediately by xrdb -load XTerm , but as far as I know, resources only apply to newly started xterms and not old ones -- so it shouldn't help you any more than the ~/XTerm file. It is possible that the xterm in 13.xx is actually named lowercase xterm instead of XTerm; but that would show up in the system trace I recommended above, and if so -- just chance all instances of the name XTerm to xterm in the instructions I gave. Let us all know how you come out so others can benefit too. Good luck.
http://www.linuxforums.org/forum/slackware-linux/177985-get-sound-pc-speaker.html
CC-MAIN-2018-26
refinedweb
2,547
70.33
i played again with vi-like input mode (i.e. control mode vs. edit mode), the motivation is to reduce the need to use modifier keys like shift/ctrl/alt which i find myself stretch my fingers in order to press those, too many times. i: x -see-on-status-bar-> x x1 -see-on-status-bar-> x,1 x12 x -see-on-status-bar-> x,1,2 and trigger keybinded action or x -see-on-status-bar-> x xy -see-on-status-bar-> <nothing to show> i guess i can implement this feature if the above API (2) was exposed. ohhh! i didn't know that one. searched the forum, read jon's email, i will have to play some with this... If you're interested in making a proper vi mode, then I'm happy to help out on the API side of things. I've done part of what's required already (commandMode, times, sequence, and key binding namespaces all come from some initial work to support vi emulation), but more still needs to be done. You'll want to use key binding namespaces at some point, e.g.: <binding key="d" command="deleteRange ${motion}"><context name="option" value="commandMode"/></binding> <namespace name="motion"> <binding key="w" command="words 1"/> <binding key="b" command="words -1"/> <binding key="j" command="lines 1"/> <binding key="k" command="lines -1"/> <binding key="enter" command="lines 1"/> <binding key="shift+enter" command="lines -1"/> <binding key="h" command="characters -1"/> <binding key="l" command="characters 1"/> <binding key=" " command="characters 1"/> <binding key="shift+space" command="characters -1"/> <binding key="$" command="eol"/> <binding key="^" command="bol"/> <binding key="G" command="eof"/> </namespace> (You'll need to implement deleteRange for the above to be useful, of course) The basic cursor movement commands will all need to be reimplemented for vi mode, because a few of the principles are different: the cursor can only move to EOL - 1, rather than to EOL, for example. For entering / exiting insert mode, I reccomend something along the lines of: class InsertModeCommand(sublimeplugin.TextCommand): def run(self, view, args): print "entering insert mode" view.options().set('commandMode', False) view.runCommand('markUndoGroupsForGluing') if len(args) > 0: if args[0] == 'bol': view.runCommand('moveTo bol') elif args[0] == 'eol': view.runCommand('moveTo eol') elif args[0] == 'append': view.runCommand('move characters 0') class CommandModeCommand(sublimeplugin.TextCommand): def run(self, view, args): print "entering command mode" view.options().set('commandMode', True) view.runCommand('glueMarkedUndoGroups') <binding key="i" command="insertMode"><context name="option" value="commandMode"/></binding> <binding key="I" command="insertMode bol"><context name="option" value="commandMode"/></binding> <binding key="a" command="insertMode append"><context name="option" value="commandMode"/></binding> <binding key="A" command="insertMode eol"><context name="option" value="commandMode"/></binding> The otherwise unused commands markUndoGroupsForGluing and glueMarkedUndoGroups are used so that all actions done in insert mode will be combined into a single entry in the undo stack, which in turn allows repeat (i.e., '.' in vi) to work as expected. More API support will be required, such as displaying the current mode on the status bar, and allowing the cursor to be drawn under a character rather that between characters while not in insert mode, is still required, but I'm happy to add these. If you don't have them, it won't cause any problems, so I wouldn't think it's related. Normally, when running several different commands, you'll get several different undo groups, each one of which will get undone in turn when ctrl+z is pressed. 'markUndoGroupsForGluing' simply records the current location in the undo stack. glueMarkedUndoGroups' takes every entry in the undo stack between the marked one and the current one, and combines them into a single undo group. This means that a single ctrl+z will undo them all in one go. this is actually one of the differences from Vi. on Vi, when having two key bindings that over lap, e.g. d - action1 and dd - action2, after you press d once, Vi will wait for a short period of time (half a sec +/-) and if no more inputs it will decide you wanted action1 (d). Sublime Text it will wait till it sure what is the key sequence you entered, so when you enter d once it will wait till your next key press, to see if it's another d (->action2) or another key (->action1 and use the other input as normal key stroke). this have always seems odd to me, because due to this behavior i can't bind frequent commands to shorter sequences. i would prefer to be able to group similar commands, like that: <binding key="ctrl+h" command="open"/> <binding key="ctrl+h,2" command="openIn"/> <binding key="ctrl+h,2,a" command="openInSomething"/> <binding key="ctrl+h,p" command="openProj"/> <binding key="ctrl+h,p,p" command="openProj quickpanel"/> anyway, check this out: i have pushed this: code.google.com/p/sublime-text-c ... /trunk/Vim do you think this is the right direction to go with? Looks good to me, yeah. quoting my self anyway, there is a real issue here, when i bind sequences that overlap shorter sequences, the shorter become unpractical to use. need to think ho to solve this, the VIM way is some kind of timer (which has its drawbacks - lag on response for the shorter keybindings), but maybe there are better ways.
https://forum.sublimetext.com/t/sublime-api-request/423/4
CC-MAIN-2016-44
refinedweb
907
50.77
Lib. Libglade can also automatically connect signal handlers in the user interface. It does this by matching handler names specified in the glade file with symbols in the executable looked up with the gmodule library (this requires that applications be linked with the --export-dynamic flag). A minimal libglade program in C looks like this: #include <gtk/gtk.h> #include <glade/glade.h> void some_handler(GtkWidget *widget) { /* a handler referenced by the glade file. Must not be static * so that it appears in the global symbol table. */ } int main(int argc, char **argv) { GladeXML *xml; GtkWidget *widget; gtk_init(&argc, &argv); xml = glade_xml_new("filename.glade", NULL, NULL); /* get a widget (useful if you want to change something) */ widget = glade_xml_get_widget(xml, "widgetname"); /* connect signal handlers */ glade_xml_signal_autoconnect(xml); gtk_main(); return 0; } There are also Python bindings for libglade. This makes a nice rapid application development system. The Python equivalent of the above program is: import gtk import gtk.glade def some_handler(widget): pass xml = gtk.glade.XML('filename.glade') widget = xml.get_widget('widgetname') xml.autoconnect({ 'some_handler': some_handler }) gtk.main() Libglade can be downloaded from or its mirrors:
http://www.jamesh.id.au/software/libglade/
CC-MAIN-2013-48
refinedweb
184
51.24
Experts Exchange connects you with the people and services you need so you can get back to work. Submit The revolutionary project management tool is here! Plan visually with a single glance and make sure your projects get done. <StructLayout(LayoutKind.Sequential, CharSet := CharSet.Ansi)> _ Structure StringInfoA <MarshalAs(UnmanagedType.LPStr)> Public f1 As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst := 256)> _ Public f2 As String End Structure <StructLayout(LayoutKind.Sequential, CharSet := CharSet.Unicode)> _ Structure StringInfoW <MarshalAs(UnmanagedType.LPWStr)> Public f1 As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst := 256)> _ Public f2 As String <MarshalAs(UnmanagedType.BStr)> Public f3 As String End Structure <StructLayout(LayoutKind.Sequential, CharSet := CharSet.Auto)> _ Structure StringInfoT <MarshalAs(UnmanagedType.LPTStr)> Public f1 As String <MarshalAs(UnmanagedType.ByValTStr, SizeConst := 256)> _ Public f2 As String End Structure Select all Open in new window A 2-byte, null-terminated Unicode character string. Note that you cannot use the LPWStr value with an unmanaged string unless the string was created using the unmanaged CoTaskMemAlloc $31.25. Premium members get this course for $159.20. Premium members get this course for $25.00. So, for an hour's effort I think I have my problem solved. Many thanks again "TheLearnedOne" for your patience, Sid. I can also access properties defined in the library as long as they are the common data types like integers and strings. It would be possible to write some long form code to copy all this data into the unmanaged structures so that the application can process and access it, however I was hoping to write that copying code in a more efficient way by being able to refer to the class library's structures and iterate through them in the application. Thank you, Sid. The revolutionary project management tool is here! Plan visually with a single glance and make sure your projects get done. If you are working with a COM library, that may mean a different approach versus p/invoke. CoInitialize(NULL) ; hr = CoCreateInstance(CLSID_XML Sid. There is a COM section in the Add Reference dialog, where you can add the reference to the COM library. #import "..\XMLReader_LINQ\bin\deb using namespace XMLReader_LINQ ; In my VB.NET DLL I have the following method: Public Sub getDeviceData(ByRef theDevice As Device) theDevice = sDevice End Sub And in the application I have: Device sMyDevice ; pMyInterface->getDeviceDat I get an "out of memory" error on the call to getDeviceData. It would be great to be able to access the device data as a structure in the application rather than iterating over it element-by-element and copying the data to the local structures. Thanks, Sid. Public Structure Device Dim Name As String Dim Description As String Dim Peripherals() As Peripheral End Structure And declared in the libarary as: Private sDevice As New Device Sid. Sid. When you define the structure, you need to know the byte arrangement, and how you need to marshal the bytes to the unmanaged code. The MarshalAs attribute and the StructLayout can help in this case, but you need to know exactly what you are working with. Default Marshaling for Strings Examples: Open in new window Public Structure RegBit Dim wcsDescription As String Dim wcsName As String Dim dwOffset As Int32 Dim dwWidth As Int32 Dim eAccess As IDB_ACCESS_TYPE End Structure Public Structure Reg Dim wcsDescription As String Dim wcsName As String Dim eType As IDB_REG_TYPE Dim dwAddressOffset As Int32 Dim dwSize As Int32 Dim eAccess As IDB_ACCESS_TYPE Dim sBits() As RegBit End Structure Public Structure Peripheral Dim wcsName As String Dim wcsDescription As String Dim dwBaseAddress As UInt32 Dim eAccess As IDB_ACCESS_TYPE Dim sRegisters() As Reg End Structure Public Structure Device Dim Name As String Dim Description As String Dim Peripherals() As Peripheral End Structure The unmaged code has a very similar structure already in place and I need to transfer the data to that structure so that the existing application code is able to use it with the minumim change. All the strings in tht C application are of type wchar_t. In the C application we also have a device structure tghaty contains, amoung otehr things, an array of peripheral structures. Each peripher has an array of register structures, and each register structure may have an array of bit structures. So, what I need to do, in pseudo-code, is something like: copy device data and strings to C application structure for each peripheral in the device { copy the data and strings at this level to the C application structure for each register in the peripheral { copy the data and strings at this level to the C application structure if there is a bit array { copy the data and strings at this level to the C application structure } } } Sid. UnmanagedType Enumeration The default string marshalling is BSTR, and so you would have to override the default with the MarshalAs attribute to indicate LPWStr. Are you suggesting declaring my VB.NET structures using the style you mentioned ealier: <StructLayout(LayoutKind.S Structure StringInfoA <MarshalAs(UnmanagedType.L <MarshalAs(UnmanagedType.B Public f2 As String End Structure And, having done that I can get the structure returned to my C appication and iterate over it as I described? Many thanks for your patience, Sid. Also, it is important to get the correct structure layout, so that the bytes are arranged appropriately, when crossing the boundary, too. This is a fairly complex operation, and I wanted to help you find your own way through the marshalling concepts between managed and unmanaged world. It might not as much of a "science", as it is an "art". I have seen others who created C++.NET managed wrappers, since it can be used to build a better bridge, because it understands both sides better. Sometimes the need to finish the job takes precendence over the most elegant approach. Once again a valuable technology (COM Interop) appears to have a wealth of technical references but very few practical aricles for real-world scenarios. Handling the basic types like integers and even strings is well covered, however once we get to more complex structures and arrays of structures it seems we are on our own. Plus, the majority of examples out there appear to be calling unmanaged code from managed, the opposite of what I required. Anyway, thanks again for your help and guidance, proving once more what a valuable resource Experts Exchange is, and well worth the subscription. Sid. Sid.
https://www.experts-exchange.com/questions/27663200/Returning-structures-from-Managed-to-unmanged-code.html
CC-MAIN-2018-13
refinedweb
1,071
53
getitimer(2) BSD System Calls Manual getitimer(2) NAME getitimer, setitimer -- get/set value of interval timer SYNOPSIS #include <sys/time.h> #define ITIMER_REAL 0 #define ITIMER_VIRTUAL 1 #define ITIMER_PROF non-nil). reloading it_value when the timer expires. Setting it_value to 0 dis- ables inter- preted programs. Each time the ITIMER_PROF timer expires, the SIGPROF signal is delivered. Because this signal may interrupt in-progress sys- tem calls, programs using this timer must be prepared to restart inter- rupted system calls. NOTES Three macros for manipulating time values are defined in <sys/time.h>. Timerclear sets a time value to zero, timerisset tests if a time value is non-zero, and timercmp compares two time values (beware that >= and <= do not work with this macro). RETURN VALUES Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned and the global integer variable errno is set to indi- cate the error. ERRORS Getitimer() and setitimer() will fail if: [EFAULT] The value parameter specified a bad address. [EINVAL] The value parameter specified a time that was too large to be handled or not in the canonical form. [EINVAL] The which parameter was invalid. SEE ALSO gettimeofday(2), select(2), sigaction(2) HISTORY The getitimer() function call appeared in 4.2BSD. 4.2 Berkeley Distribution December 11, 1993 4.2 Berkeley Distribution Mac OS X 10.9.1 - Generated Mon Jan 6 05:37:27 CST 2014
http://www.manpagez.com/man/2/setitimer/
CC-MAIN-2016-40
refinedweb
240
58.38
sort of preafrooding useful? -r ======= Page ii ======= We expect all further changes will be strictly limited to wording corrections and fixing production bugs. We expect that all further changes will be strictly limited to wording corrections and the fixing of production bugs. or perhaps We expect all further changes to be strictly limited to wording corrections and the fixing of production bugs. ====== We wish to thank implementers who have tirelessly tracked earlier versions of this specification, and our fabulous user community whose feedback has both validated and clarified our direction. We wish to thank our implementers, who have tirelessly tracked earlier versions of this specification, as well as our fabulous user community, whose feedback has both validated and clarified our direction. ====== ... [] ... URLs should probably be displayed in monospace font. ====== ... and to creating programs ... ... and to create programs ... ====== This document may be freely copied provided it is not modified. This document may be freely copied, provided that it is not modified. ======= Page iv ======= In the page header, "Language" is split across two lines. ====== Terms Index Why not just "Index"? ======= Page 1 ======= This specification is both an introduction to the YAML language and the concepts supporting it and also a complete reference of the information needed to develop applications for processing YAML. This specification is an introduction to the YAML language and the concepts supporting it; it is also a complete reference of the information needed to develop applications for processing YAML. ====== ... of structural characters, and allowing the data ... ... of structural characters and allowing the data ... A comma is not needed before "and" or "or" if only two items are involved. ====== ... colons separate mapping key: value pairs, ... ... colons separate mapping "key: value" pairs, ... ====== ... and dashes are used to "bullet" lists. ... and dashes are used to create "bullet" lists. ====== ... YAML excels in those languages ... ... YAML excels in working with those languages ... ====== ... PHP, Ruby and Javascript. ... PHP, Ruby, and Javascript. A comma IS needed before "and" or "or" if only three or more items are involved. Tom Christensen uses the example: "I'd like to thank my parents, God and Mother Teresa." ====== Later on it directly incorporated ... Later on, it directly incorporated ... ====== Since then YAML has matured ... Since then, YAML has matured ... ====== More URLs to put into fixed-width font. ======= Page 2 ======= ... ] and SOAP ... ... ], and SOAP ... ====== YAML's indentation based scoping ... YAML's indentation-based scoping ... Actually, there are quite a few places where hyphens might help to clarify things... ====== ... of traditional indicator-based scoping similar to Perl's. ... of traditional indicator-based scoping, similar to Perl's. ====== ... Java's DNS based package naming convention and XML's URI based namespaces. ... Java's DNS-based package naming convention and XML's URI-based namespaces. ====== YAML was designed to support incremental interfaces that includes both input pull-style and output push-style one-pass (SAX-like) interfaces. YAML was designed to support incremental interfaces, including both input (pull-style) and SAX-like output (push-style) interfaces. ??? ====== Together these enable YAML to support the processing of large documents, such as a transaction log, or continuous streams, such as a feed from a production machine. Together, these enable YAML to support the processing of large documents (e.g., transaction logs) or continuous streams (e.g., feeds from production machines or systems). ====== While the two languages ... Although the two languages ... ====== -- email: rdm@...; phone: +1 650-873-7841 - Canta Forda Computer Laboratory - The FreeBSD Browser, Meta Project, etc. - Prime Time Freeware's DOSSIER series Wed d2ViIHNpdGU6DQogIC9zcGVjL2luZGV4Lmh0bWw6IC9zcGVjL3R5cGUvIGRvZXMgbm90IHdvcmss IC90eXBlLyBkb2VzDQogIC9zcGVjL2N1cnJlbnQuaHRtbDogInRoaXMgdmVyc2lvbiIgbGluayBp cyBicm9rZW4gKC9zcGVjLzIwMDQtMTItMjguaHRtbCBpbnN0ZWFkIG9mIC9zcGVjL2hpc3Rvcnkv MjAwNC0xMi0yOC8yMDA0LTEyLTI4Lmh0bWwpDQogIC90eXBlL2luZGV4Lmh0bWw6IGluIENvbGxl Y3Rpb24gVHlwZXMgc2VjdGlvbiB0aGVyZSBpcyAhIXNldCB0d2ljZSAtIHRoZSBzZWNvbmQgb25l IHNob3VsZCBwcm9iYWJseSBiZSAhIXNlcQ0KDQp0eXBlcyByZXBvc2l0b3J5Og0KICBmbG9hdGlu Zy1wb2ludCBzZXhhZ2VzaW1hbCBudW1iZXJzOiBtYXliZSBpdCBzaG91bGQgYmUgbm90ZWQgZXhw bGljaXRseSB0aGF0IHRoZSBmcmFjdGlvbmFsIHBhcnQgYWZ0ZXIgX2RlY2ltYWxfIHBvaW50IGlz IHJlYWxseSBkZWNpbWFsDQoNCmJyYfJvDQo= On Thursday 30 December 2004 11:30, Bra=C3=B2o Tich=C3=BD wrote: > web site: [fixes] > types repository: [fixes] Thanks! I fixed all of these in the CVS version. Have fun, Oren Ben-Kiki On Thursday 30 December 2004 08:24, Rich Morin wrote: > Is this sort of preafrooding useful? Very! Nice work. I've incorporated (most of) the corrections to the CVS version. > In the page [iv] header, "Language" is split across two lines. I'm not shy about hacking and patching DocBook and XEP inputs and outputs - In fact, I already do strange and wondrous things to both. I had to give up on this one, though. <rationalize>It is just a single place...</rationalize> > YAML was designed to support incremental interfaces, including > both input (pull-style) and SAX-like output (push-style) > interfaces. > > ??? "Pull-style" input means you have a "getNextToken()" method as opposed to having a callback invoked for each token. "Push-style" output means you have a "putNextToken()" method - that is, that you are invoking a callback on the target of the tokens. Combined, this means that the C stack is owned by your code, which makes programming much easier. > :-( > ... there are quite a few places where hyphens might help > to clarify things... No argument here, but I doubt my intuition is worth anything here. Have fun, Oren Ben-Kiki On Thu, 2004-12-30 at 19:46 +0200, Oren Ben-Kiki wrote: > > :-( Firstly, congrats on getting the spec out, although I'm using Syck at the moment due to time pressures, I'll hopefully have time to put the spec to use with pyyaml this coming year. Back to 'The Comma'. This comma (before the last item) is commonly known as the 'Oxford comma' (or serial comma); To quote from an excellent resource on punctuation "Eats(,) Shoots and Leaves - The Zero Tolerance Approach to Punctuation" by Lynne Truss: Oh, the Oxford comma. Here, in case you don't know what it is yet, is the perennial example as espoused by Harold Ross: "The flag is red, white, and blue." So what do you think of it? (It's the comma after "white".) Are you for it or against it? Do you hover in between? In Britain, where standard usage is to leave it out, there are those that put it in - including, interestingly, Fowler's Modern English Usage. In America, conversely, where standard usage is to leave it in, there are those who make a point in removing it (especially journalists). British grammarians will concede that sometimes the extra comma prevents confusion when there are other ands in the vicinity, but this isn't much of a concession when you think about it. My own feeling is that one shouldn't be too rigid about the Oxford comma. Sometimes the sentence is improved by including it; sometimes it isn't. ... and so, as you are an international author, I think you should do what comes naturally and then change your behaviour if the sentence calls out for amendment. Then again, having used the suffix "-ize" throughout the documentation, perhaps you should add adopt the 'Oxford comma'? Just as a rejoinder to the 'son of god' quote : "A little known meeting happened before 9/11 between George Bush, a member of the Bin Laden family, and James R. Bath, a friend of the Bush family." Wouldn't you know it, a member of the Bin Ladens all along ... references :- On Friday 31 December 2004 13:01, Tim Parkin wrote: > Firstly, congrats on getting the spec out, Thanks. > Oh, the Oxford comma... Ah, it has a name. I fele better already :-) > ... and so, as you are an international author, I think you should do > what comes naturally and then change your behaviour if the sentence > calls out for amendment. Personally I tend to write it in, and Clark seems to prefer to leave it out. At this point in time the posted draft doesn't have it but the CVS one does. Sigh. > Then again, having used the suffix "-ize" > throughout the documentation, perhaps you should add adopt the > 'Oxford comma'? Probably; I studied "British" at school, and I still have an irrational belief in the Oxford English Dictionary as the ultimare authority on what is "proper" English. However, the world being what it is, almost everything I have read for the last 20 years was in "American". My writing has therefore drifted towards "American", with remnants of "British" showing through. It seems I'm doomed to writing "Mongrel" for the rest of my life. This brings to mind a piece of code I saw once: /* Isn't it great we all speak the same language? */ #define strrchr rindex Have fun, Oren Ben-Kiki
https://sourceforge.net/p/yaml/mailman/message/11695676/
CC-MAIN-2018-09
refinedweb
1,374
57.47
Transcript Evenson: We're talking all about Helm 3 today, and we've titled this talk "A Mariner's Delight," because as I think of everybody sailing on the high seas of Kubernetes, hopefully, Helm is the tool that you know and love and could get used to. We're going to focus very heavily on Helm 3 and what that brings to the table and also go back and learn a little bit of history about Helm 2 and teach you what Helm does and how it can be useful to applying packages to Kubernetes. With that, let's get into it. We got a packed agenda I'm going to go through soup to nuts. There's going to be demos and everything. If you can hold your questions to the end, I promise I will answer them and we'll get to them. First of all, a little history on Helm. We're going to go through why is Helm important and why does it exist in the Kubernetes ecosystem. We're going to look at Helm 3, which is the next iteration, next major version of the Helm release, which everybody is eagerly awaiting. I'm going to teach you about Helm 3, how it overcomes a lot of things, problems in the ecosystem that Helm 2 identified. Hopefully, everyone will give me a standing ovation at the end. That's the hope. We're going to go through breaking changes, new features, increasing reliability. As you release and use Helm to release your applications on Kubernetes, we're going to talk about how you can use it in a CI/CD context and actually get increased reliability using some open-source tools. Then we're going to go on to what's next, what does this mean from you and where do you go from here. I will be around at the conference, happy to talk to everybody after this. If you have very specific questions, I am more than happy to answer them. First, who is this guy up on stage, talking to you? My name is Lachlan Evenson. I look after open-source program management in the cloud-native compute foundation ecosystem. You may have seen me from such communities, such as the Helm upstream charts maintainer. I do that. I make sure and I saw on the Octoverse report yesterday that helm/charts repository is number six in changes to open-source computers over the last year out of all the repositories on GitHub. It is high churn, Helm is a high-use tool. It's very popular in the ecosystem. Also, the Kubernetes 1.16 release lead, so if you've got any feedback for that or you want to learn how to be a release lead yourself, happy to teach you on that. It's certainly a labor of love, but you can thank me for all those wonderful things that went into Helm Kubernetes 1.16, or not. Happy to take the brunt either way. I'm also a CNCF ambassador, and what that means is you can ask me about any CNCF projects. I'm happy to talk to you about any of them and what they do in the ecosystem. Feel free to ask me about those things. Why Helm? First, let's get into what Helm is and how it fits into the Kubernetes ecosystem. Simply put, Helm is a package manager for Kubernetes. What does that mean? The best way I like to think about Helm is, if you're a Mac user, everybody knows Homebrew, everybody's used to apt, yum, de facto packaging for applications on different platforms. Think about Helm as a package manager for applications on Kubernetes, specifically. Helm, the project, was donated back to the cloud-native compute foundation in June of 2018. It's used by 68% of the people, according to the last CNCF survey, in the ecosystem to deploy applications to Kubernetes. It is the third most popular ecosystem tool in the cloud-native compute foundation tool belt, only third to Kubernetes and Prometheus. It's a fairly well-known tool. If you're not familiar with it, take a look at it. It's used in a lot of different places and a lot of different companies publish this software using Helm charts to be able to have a one-click install for their packages. What does that this really mean under the hood, where the rubber meets the road as you're practicing using Helm? It allows you to define your applications and template them, because as we know, in Kubernetes, it doesn't have the notion of an application. It has notions of individual building blocks of applications, services, deployments. Helm allows you to package them all up and say, "This is my WordPress application as I know it," which consists of services, deployments, discs, so on and so forth, and allows you to install, upgrade, rollback, and have all those common lifecycle verbs at your fingertips that you know and love from other package managers. It also allows you to build chart repositories. The packaging format for Helm is called charts, and you can build a repository of charts that people can then leverage. You can distribute your software with charts internally and externally. As I mentioned before, I am the maintainer of the upstream charts repo, which is a set of curated charts in the ecosystem that allows you to have one-click install of any popular software on top of Kubernetes. You want a Jenkins, you can Helm install Jenkins. You want a Redis Cluster on Kubernetes, you can Helm install Redis. Charts allow you to package up and share your applications with other people or different organizations. It's reusable, repeatable, and packaged up. V3 Overview I'm going to go straight into Helm 3, because we've got a loaded deck on Helm 3 specifically, and I think that's the most exciting thing that most people are here for today. What have we learned? Helm 2 has been around for several years. I think circa 2016, Helm 2 was released prior to Helm 1. Helm 1 was completely client-side, Helm 2 went client-server, and Helm 3 is going back to client-side. More on that in a moment. What we've taken as a community is all the best practices feeding back from the Kubernetes community to how they want to deploy apps and rolled it into one piece of software, which is Helm 3. We used Helm 2 as a sounding board for how people want to use applications on Kubernetes, how to package them, and rolled all that feedback into one binary. Let's see if we get everybody excited about that. We've also made it really simple, much more simple than Helm 2, so there's a lot less moving parts, and I'll show you what that means. We've focused on security as a priority. A lot of feedback is, "I want to use Helm, but I cannot use it in my production environment because the architecture is insecure in Helm 2." We will show you how we've addressed that in Helm 3 so that you can use Helm in production and know that it is secure. In order to get to Helm 3, we needed a major refactor of Helm. Who was around in the Kubernetes 1.1, 1.2 days? If you know that there was no RBAC, there weren't even deployments, there wasn't even ingresses. A lot of the resources didn't exist that you have today in Kubernetes. Helm comes from that legacy of very early boilerplate Kubernetes, where it was designed where there weren't many security controls. As the Kubernetes ecosystem has grown up and added security controls, it has exposed the inherent insecurity of the architecture that Helm employed prior to having all these things. We needed to go back and look at this. We also didn't have custom resources. Kubernetes just shipped an inbuilt set of APIs, and you could not extend them. The first version of extendability to bring your own APIs was back Kubernetes 1.4, and they were called third party resources. If you go back, they were horrible. Thank goodness, we have CRDs today and we also have RBAC. We're able to use the tools under the hood that Kubernetes provides and roll them in as native features to Helm. Again, focusing on simpler, more secure, and production-ready. One of the other things we wanted to do was make Helm more Kubernetes-native. Now, people have grown up with Kubernetes, and they're used to a specific vernacular and way to interact with Kubernetes. Helm was kind of a little off on its own world. What we've done with Helm 3 is brought it back in the line of what people know and expect with Kubernetes. When you're using kubectl, you expect a very precise experience, and we've modeled that experience in Helm as well, so that you can be comfortable coming from the Kubernetes-native tooling into the Helm ecosystem. We've inherited security controls from kubeconfig, which allows your identity to access the cluster, which we did not have in Helm 2. Using RBAC and replacing custom APIs for charts and deployments with secrets. We've removed a lot of custom code and rolled that in the Kubernetes-native resources, meaning we don't have to carry a lot of that code in Helm itself, which brings me to Tiller. Tiller in Helm 2 was the server-side component, which exposed a lot of security risk. Basically, it sat in cluster, and I like to call Tiller the first Kubernetes operator. It basically interacts with the Kubernetes API, but it was doing so in a way that was insecure. It allowed unsolicited, unauthenticated commands to come into it, and then it would execute directly against the Kubernetes API, often as a root user. That made everybody in the Kubernetes ecosystem fairly uncomfortable as RBAC became a thing and as many other tools that we know and love in the security aspect of Kubernetes. We've decided with Helm 3 to actually collapse Tiller and remove the server-side component, and that took out a big security risk in the architecture, which was we were using our way to basically pseudoroot into your cluster. We've gotten rid of that, and Helm now operates client-side and directly accesses the Kubernetes APIs. The released objects are also rendered client-side as well and stored in a secret. I'll show you how that all works. Really, not having this server-side component means people can get something out of Helm very quickly. They can download the binary, run an install, and not be reliant on a server-side component already being installed in the cluster. Cluster administrators can actually determine what you can install where, lowering the barrier of entry there. As I mentioned, we made Helm 3 a lot more Kubernetes-native. With this, we actually employed a whole new set of verbs. Worry not, we aliased all the old verbs to the new verbs. What we wanted to do was make sure that most things operated, but there are some breaking changes, which I will show soon. Basically, helm delete is now helm uninstall, inspect is show, fetch is pull, search is search repo, and purge is now the default. Purge, when you're deleting, is now the default to remove all the released artifacts from the server-side where they're stored. The idea is that people can come in and drop in the Helm 3 binary in place of the Helm 2 binary and they have an experience that works and allows them to move over to the verbs in Helm 3. Breaking Changes Now, we're going to get into where the rubber meets the road. I'm going to share the breaking changes. There is a link here that is a doc that details all the changes between Helm 2 and Helm 3, so you don't have to heed on to my every slide. These are all detailed on the Helm website as well, where you can find all this information. I'm going to go into particular depth about all these things, but I want everybody not to panic. The idea here to move to Helm 3 was not to segregate the community and have a Helm 2 ecosystem and a Helm 3 ecosystem. It was to bring everybody over to Helm 3. The intent with the move and the community work was to bring all your Helm 2 artifacts, bring everything you know and love about Helm 2 over to Helm 3, and then you can keep that experience going. The most often question I get asked is, "I've been using Helm 2 for years. Can I move to Helm 3? Do I have to rewrite everything?" The answer is no, you should be able to drop in the Helm 3 binary in place, and I urge you to do that if you're using Helm today, if you take into consideration the following things I'm going to state. Don't worry, they're fairly low. Let's go into namespace changes. A release is when you install an application, a packaged application on Kubernetes. That constitutes a release, and you may have many releases as you upgrade, rollback other specific application but that metadata. If I install an app and Wes installs an app, that metadata about who's installed it where and what the release information is stored server-side in Kubernetes as a secret. That is different and it is stored in the namespace that you release that application to. This is a behavioral difference from Helm 2 to Helm 3. In Helm 2, that release metadata was stored where Tiller was actually resided as a ConfigMap, usually in the kube-system namespace. Templated resources. Helm packages are templated Kubernetes resources. If you'd specify the --namespace flag, it will annotate those resources with the namespace. You can say, "I want to deploy WordPress in the Lachy namespace," by saying helm install --namespace Lachy, and it will go and do that. Caveat to that is it doesn't actually create the namespace on your behalf. We did that in Helm 2 as an ease-of-use, but that is anti-Kubernetes. You should not create any resources people don't ask you to do. I'm going to model the behavior in Helm 3 in a demo shortly, but you need somebody to create, whether it's yourself, that namespace. Again, we're detaching use cases and different personas. There's a developer who wants you to install an app and there's a cluster administrator that says, "Here's a namespace for you to just deploy that application." We assume somebody is issuing namespaces. If you wear both those hats, you need to create the namespace. As I said, don't be scared of that. I'll show you how it works. Again, we're modeling kubectl create where it won't create a namespace on your behalf. Now, people ask me, "Why do you do that?" That's really a pain in the butt. If you want to do that with Kubernetes, you can use an admission controller called the NamespaceLifecycle controller, which will actually, if you create a resource and a namespace that doesn't exist, it will create it on your behalf. Again, it's not really best practices. If you're used to that kind of experience, you can recreate it using Kubernetes, but if you're not, we hope that somebody will come and create that namespace on your behalf. Chart dependency management. Like all package managers, if you have dependencies on other packages, like I have WordPress and I need a MariaDB or a database, you can say, "I take a dependency on the chart for MariaDB or MySQL," or whatever it is that supports the data storage for WordPress. Now, what I want people to think is dependencies were added to Helm 2 very late in the game so that we're bolt-on. They weren't actually part of the chart definition. We bolted them on. What we've done with Helm 3 is we moved them into the chart definition itself. If you're using dependencies in charts, the toolchain should still work, but some of the subcommands will break under Helm dependency. That command is actually changed to Helm package, but most of the workflows that I've seen continue to operate if you're taking a chart from the old style to Helm 3, the old style being a Helm 2 chart to Helm 3. Just something to note, but if you are to build a chart today with Helm 3, the dependencies would be reflected in the chart metadata itself, not in a requirements.yaml and a requirements.lock, as they previously used to. CRD installation, so custom resources. Many charts chip with custom resources in-built. For example, the Prometheus operator, where I can configure Prometheus from a custom resource, will ship with a set of custom resources. In Helm 2, we model those custom resources as CRD install hooks. We say, "Here are some CRDs that you need to install prior to installing the operator, which looks at those custom resources." This is about order of operation. In Helm 2, they were all predefined as these hooks, which were essentially annotations on the resource that said, "Please install these before you install the application or the operator," as it were. In Helm 3, you'll get a lovely warning message to say, "You've got CRDs, but I'm not installing them." What Helm 3 expects is that you put these in a directory at the root of the chart called CRDs, and it only has custom resource definitions in there. You'll get a lovely warning message. Don't worry, but you need to move those CRDs. This is a big thing for people using Helm 2 charts that'll eventually be updated, but as you can see over on the right, you can see the CRDs directory with crontab.yaml that would contain the custom resource definition for crontabs. Everything else is the same, but if you find that you're installing a chart and you get a nice warning message, "By the way, I didn't do your CRDs," this is exactly why. You have a Helm 2 chart with a Helm 3 binary. Release metadata – I briefly touched on this. It's no longer stored in the same namespace as Tiller, because there is no Tiller. It's stored in the namespace that you're deploying the release to. Also, it's stored as a Kubernetes secret, and it is double base64 encoded. I mention this because most people will go and pop the hood on this afterward and say, "What is that thing?" It's double base64 encoded because we have different storage back ends for Helm. Kubernetes secrets happens to be one, but we have MySQL that wants a base64 encoded blob put in. It doesn't do the translation. We encoded on the in-code before we store it in there. If you go and grab and pop the hood on that blob, you'll see you need to decrypt it twice, and there'll be a big JSON blob with all your release metadata, so who installed it, when it was installed, what exactly happened. If you want to go and pop the hood, you're going to have to double decode it. Finally, it is not backwards compatible with Helm 2. The Helm ecosystem has published a Helm 2 to 3 plugin. If you have a cluster and you've installed packages on it with Helm 2, you run this plugin, it will migrate that release metadata to the Helm 3 format so you can pick up the Helm 3 binary and actually introspect those applications as they run. There's been a lot of work in the community to make sure that people can actually bring their released artifacts from an operating Kubernetes cluster without having to say, "You got to greenfield it and start again." Check out that tool. It's written by members of the Helm community that we're very thankful for. It basically converts from the old release metadata to the new release metadata. Deprecated functions. I felt compelled to actually mention one deprecated function here, Release.Time. People embed functions in their templates to generate different aspects of their templates. Release.Time wasn't very configurable, but now, you can just call them "now" function and dictate how you want your time to be sliced down. No big deal, but if you have Release.Time there, you will get an error message and say, "Please go and use now." Generate-name. If anybody's done a Helm install without giving it a name, it generates these quirky little animal names, like crazy emu or something like that. We now have changed that not to be the default behavior. Again, the paradigm in Kubernetes is to do exactly what's asked. We were generating things we didn't feel that was in line with the Kubernetes ecosystem. We've gotten rid of that. Now, you actually need to say, "I give it this name." If you don't want to give it a name, you have to explicitly say, "Generate a name." If you have Helm in pipelines or running off code, it's already there, and you pop this in, and why isn't it working? Most probably, you're relying on the generated name. You're going to need to pop that flag at the end. Helm 3 End-to-End I'm going to do an end-to-end demo. I actually recorded this so I could talk, because I can't talk and type at the same time very well. I wanted to do you justice with the demo. I think what you'll find is a Helm 3 is very much similar to a Helm 2 demo. I'm going to go through everything here to show you the end-to-end experience to install an app and what it looks like in Helm 3 as opposed to what people are familiar with in Helm 2. I'm going to show you how a Kubernetes cluster running 1.16.2, and I have Helm version 3; 0.0-rc.3. What we're going to do here is I'm going to show you a list of repositories. This is the upstream stable repo. I'm going to run an install of WordPress. I'm going to call it wp and take the stable upstream WordPress chart and run an install using Helm. I'm installing WordPress on Kubernetes with a single command. We can see that that's actually been deployed, and then I will actually go and show you the resources using kubectl. Here are the pods where you see we have a MariaDB and a WordPress pod there. We can see we have a release in the default namespace of the WordPress chart. I will show you the release metadata here. You can see the secret named release.v1.wp.v1. For posterity, let's go ahead and pop the hood on that. You will see the data payload is a big double encrypted JSON blob with base64. Not encrypted, encoded. Don't want to make that mistake. I'm going to show you doing an install of the NGINX Ingress, which is another popular chart in the Helm ecosystem, into a namespace called nginx-ingress, which does not currently exist. Just to hop on there. Namespace not found. I haven't done anything, so what I need to do is, either an admin or if my user allows, create that namespace, and then I should be able to go back and install the NGINX Ingress into that specific namespace. We can see that that now has deployed. I will show you the deployment status. We've installed that. I'll go and show you the pods using kubectl get pods in the namespace nginx-ingress, and we should see that we actually have the Ingress controller installed into that namespace. Namespace releases, so I did it without a namespace. I only stored default. I did it with all namespaces, so you can see both the NGINX Ingress and the WordPress. Releases are now namespace-specific. Finally, I show you just with the namespace specified. I'm going to do a delete without the namespace. It doesn't know about it. All the releases are namespaced now, not just one global namespace like they were in Helm 2. Finally, I'm going to go and clean up the WordPress release as well in the default namespace. That's been uninstalled and share with you the secret. The release metadata is gone, so it's purged by default, and you can see that the WordPress application is now being deleted and terminated. Just to reiterate, we went through the whole lifecycle using Helm 3 install/uninstall. We did a list, a non-namespaced and a namespaced, because everything is namespaced now in Helm 3. I also showed you the release metadata where you can have a look at that yourself. That's all there is to it with Helm 3. It's that simple to install apps. The other thing that I was showing is they're all Helm 2 charts from the upstream chart repository that's published under the CNCF. They have not been migrated to Helm 3 specifically, but the tool will just install them as long as they don't have any of those constraints that I mentioned. You can see that many of the upstream charts do not have those constraints. I've gone on breaking changes, now the exciting stuff. Let's talk about what's actually new in Helm 3 and what you can get excited about. New Features Chart repository API. In Helm 2, charts were stored in a chart repository. A chart repository was generated from the Helm tool itself, which was basically an index YAML file that needed to be served by a web server. It only supported basic authentication in the client, but in Helm 3, we're moving to charts being stored in container repositories. For those following along at home, there has been updates in the OCI distribution, which is the governing body that takes care of container registries and how they are actually operated. In the distribution spec v2, they have allowed storage of any arbitrary metadata. Now, you can store Helm charts in a container repository, which means you can leverage all the authentication and all the tooling in the container ecosystem to store your charts. Who wants to build another web server to support charts anyway? Nobody. I certainly didn't. With the chart repository API, we ask people to try this out, some public providers support distribution v2, which you need to supply charts and have them stored in the container repositories. You need to figure out who they are, and then you can test this. By default, this is turned off in Helm 3. You need to enable an experimental flag that says, "Pull your charts from a chart repository that's stored in a container repository, an OCI standard repository." This is great as people managing infrastructure. You now don't need to have another repository just to store your Helm charts. You can store them where you store your containers, and typically, the container registries that are out there are rock solid, whether you're running them on-prem or public cloud. We know that it's a known entity, they're stored, they're backed up. You don't have to manage that on your own. Put all your stuff in the same place. I dare say, you'll see a lot more packaging taking advantage of distribution v2 for storage. Just a word that that's coming. Everything will be stored in a container registry soon. Surprise, surprise. Chart API version v2. We've bumped the API version to v2. Now, this is a little bit, as I like to say, handwavy. It's mainly for tools and third party tools to say, "This is a Helm 3 chart or a Helm 2 chart." You can install different logic if you're building tooling. As I mentioned, there are dependency changes. They're stored in the chart.yaml. We also have library charts. Let me talk about library charts because I think this is exciting for most people who are using maybe customized and other tools in the ecosystem. In Helm 2, when you define the chart, it needed to install resources. It had to intrinsically have things that are installed against the Kubernetes API. With library charts, you can bump all pieces of your templating or pieces of your helper functions to a library chart that's imported. What this means is, as a chart author, you can import from one place. Let's say your company has a standard set of labels that it wants enforced on all its Kubernetes resources. Go put them in a library chart. They say, "Please, can you add one more label?" You add it to the library chart, and all the charts that import that library chart get that function. Now, we're lowering having to copy and paste things around. Then, if you have hundreds of charts, then you make one change and copying and pasting to 100 charts. Library charts, we call them library charts and application charts. Library charts store functions that you could import and reuse, and application charts actually deploy resources to Kubernetes cluster. This one, I don't know why I'm really excited about it, but I am really excited about it. You can bundle up validation to your values.yaml. values.yaml in Helm is the parameter you want to be able to tweak, so if you want to change a container image, you want to change how many replicas. What we can do using JSON Schema, is you can actually provide typed values and have them packaged up. If you say, "I have a parameter called replicas and it must be an integer," and I go ahead and put a string in there, it's going to say, "You need to put an integer in there." Give you early failure detection and error reporting. As a chart maintainer, this is optional, you can provide a JSON Schema so that you can actually have your values typed. The other thing I've seen people do is there are fancy web UIs people build to install Helm charts. You can already prepopulate that from the schema that you provide here in your web app. I have a dropdown list. Here are accepted values, I can generate them on the fly, rather than having them untyped in Helm 2. Let me just pop that up. As you can see here, we have a property called image. We give it a description. Under there, we have a repo and type as a string. We can strictly type everything under here and package it up with a chart. Everybody excited about that, or is it just me? Maybe just me, that's ok. Three-way merge for upgrade. This is super awesome. Again, we're falling into the Kubernetes. The way kubectl apply works is it takes your new config, looks at your old config, and also takes a look at the config of what's actually running, and merges the three of them. Helm 2 only looked at the new and the old and diffed them. If somebody had gone in and edited a deployment artifact on the cluster live, which nobody ever does, added something manually, that wouldn't have been taken into account. You blow that away in Helm 2. In Helm 3, it will take that into consideration in the diff and present that to you as a user. Again, it's more in line with what kubectl apply does, but we're adding the current state, which was a big blocker to many people that had tools that would change things after Helm had touched them. Increasing Reliability I'm going to move into a period of looking at how we can actually make releases more reliable. One of the things with getting rid of Tiller – Tiller used to operate as the cluster admin in most cases, which meant, whatever you threw at Tiller, it was able to do. Now, with the removal of Tiller, people don't know if they have access to do things. What we end up seeing is a lot of people have failed releases. "I want to install WordPress, I install a resource that I don't actually have permissions to install." When I say pre-release checks, what I'm thinking about here is other tools we can use to make sure that when I land a release, it's actually going to be successful. I'm going to take you through three or four different tools from the ecosystem that are all plugged into the Helm ecosystem where you can actually look and do pre-release checks. Either you as a user on your workstation installing to a Kubernetes cluster can use them, or if you want to bolt them into your CI/CD process to do some very early linting, can this user do this, is this possible, is there policy violations, you can take these tools and plug them in as well. The top three ways I see Helm releases fail today are as follows. Invalid Kubernetes resources. You put in values that aren't valid in Kubernetes. We've talked about JSON Schema. That's one way to do it. I'm going to share another way. Denied by policy. For those people who are using OPA, the Open Policy Agent, and admission controllers which say, "You can't define that container registry. You can't have a resource without limits," they're late binding server-side errors. What you'll end up with is a failed release. Role-based access control, RBAC. "I want to create a service." You can't create a service, Lachy. What that'll end up is in a failed release. What we want to do is make sure preempting the failure using standard tooling that's reproducible. I'm going to give you some examples here. Here is an invalid Kubernetes resource. This is supposed to be ugly, so don't worry that it's ugly, but what I'm doing is installing the nginx-ingress, and obviously, I've set the controller.replicaCount to a string word of two. If anybody can decipher that error there, that's the error you're going to get. Basically, what that says is you can't have a string where there's supposed to be an integer. If you can figure out where that is actually stated there as a user, and this is your day one on Kubernetes, you're a better person than me. If you can't, come up, I'll give you a handful of stickers. I'm going to show you an easy way to do that. The other one is this one. If anybody, I'm partly to blame for this Kubernetes 1.16, we deprecated a whole bunch of APIs. What you'll see is, "By the way, deployment in v1beta1 no longer exists in Kubernetes 1.16." It was there in 1.15. Again, not a nice error message there. "What? I just worked yesterday. I don't know what happened." I put the link there for posterity. If you're moving to 1.16, please take a look at this. We deprecated a lot of workload APIs, and I imagine a lot of people are having headaches with this. We're going to talk about a plugin called kubeval. Kubeval is a Helm plugin, so you do helm plugin install. It is written by a gentleman called Gareth. Gareth works for a company called Snyk, but he does this on his spare time. You can go grab it. It's a tool that plugs natively into Helm, and we'll show you what it looks like. This time I've replaced the second verb, helm install with helm kubeval, and passed it the same parameters. This time, you can see in bold, "spec.replicas isn't a valid type. I expected an integer and you gave me a string." Just using one very lightweight command, I can actually throw an error that's actually readable to the chart author or the person trying to run the install that's usable. Again, let's go back to that first use case, stable/nginx-ingress. What I'm doing here is saying, "Is this going to install against Kubernetes 1.15 APIs as defined?" This tool is going to go pull the schemas from the upstream Kubernetes repositories and say, "These are all valid resources." If I went and did that against 1.16, it would say, "By the way, deployments is not valid in 1.16." Again, one tool tied straight to Helm, you can run it and pass it the same parameters. Super simple, your releases will already be way more reliable. Another example is policy. What I'm going to do here is use a tool called conftest. Again, we're using a Helm plugin called conftest. What conftest does is use OPA policy. If you're using Open Policy Agent policy server-side in Kubernetes, you can take that policy and bring it client-side and have it validated before you push it to Kubernetes. It's portable through Open Policy Agent, but here, I'm using the Kubernetes best practices, conftest publish best practices for all your resources, and it says, "By the way, you don't have a memory limit set or a CPU limit set for any of these things. I'm going to exit with an error." Here's a way you can define policy, and if somebody installs anything on your cluster, you can actually go and make sure that it's valid, client-side, early binding before you have a failed release. Let's have a look at the success case of this. I'm going to supply those limits. I'm running the same command, but I'm feeding in those limits, and the command exits without error. Finally, we're going to take a look at the RBAC case here. Without Tiller, you lose your cluster root admin, which obviously we're focused on security here. This is a good thing. I wrote a really ugly script just to demonstrate it, but there's actually a command called kubectl can-i, and there's an API that exists in Kubernetes that says, "As this user, can I perform this operation on this resource?" There's a nice big bit of bash at the top here, but what that bash does is it says, "For any of the resources that this Helm chart spits out, can you pass them and tell me whether I can create them against the Kubernetes API?" You can see in bold, on the third line there, kubectl auth can-i create, and I've actually passed the resource to say, "I can't create a ClusterRole, I can't create a RoleBinding, but I can create a Deployment, Role, RoleBinding, Service, and ServiceAccount." That is a very common thing that many charts package cluster admin level resources that you, as a user, won't have access to. Again, you can use this can-i API, and there are a set of tools here you can go. I've given you a link to a doc and I'll publish these slides, but here's the upstream documentation of how you can build tools around the Kubernetes API, because it ships with that can-i API. There's also a who-can plugin for kubectl that Aqua Security. It says, "Who can do this," rather than "Can I?" There are some ways you can plug this into your toolchain and get the most out of it. What's Next? What's next? Favorite one, security audit. Helm just had their security audit. They published the findings I think a week or two ago. It went great. Apart from Linkerd, it was the second highest rate of security audit in the CNCF. No major vulnerabilities found. There was one symlinking very minor vulnerability found. That's already been patched, but just full disclosure there. Why you saw this as we're preparing Helm for graduation? Graduation means it's the highest level in the cloud-native compute foundation as a top-level project. An independent entity has done a security report on the code quality, threat vectors, everything. It's all there for some late bedtime reading. If you can't get to sleep, it's certainly a good read, it'll put you to sleep, but it's a really good document. I mean that in all seriousness. Again, they security-audited only Helm 3, because we want to deliver the security posture of Helm 3, because the ecosystem was so heavy on that being one of the postures we want to make for the Helm 3. You noticed that I had C3 up. Helm 3 release date, let's just drop it now. It's real soon now. You got the scoop here, please don't tweet it, but it should happen any moment. Finally, getting into support. After Helm 3 is released, for those people using Helm 2, as I said, we don't want an ecosystem of two different parts for you, but we have Helm 2 and Helm 3 running. What we're going to do is once we release Helm 3, we're going to allow bug fixes and security fixes for six months, and then own these security fixes for the following six. Twelve months out, Helm 2 will be completely end-of-life. What we're asking people to do is try the RC. If you had been, then it's not going to blow things up. Take it with a grain of salt, but you should be able to drop it in. I've given you enough information here to be able to do that. Read the FAQ to make sure that your chart or your tooling is able to use this. Obviously, we want to make sure that everybody's feedback is incorporated. Anybody who's using Helm out there, and they have a workflow that doesn't work when they migrate to Helm 3, please let us know. It's our goal to make all these workflows as many as we could support work so that we don't get people upset about moving to Helm 3. We want it to be nice and smooth. Fantastic, easy, actionable. Questions and Answers Participant 1: I have two quick questions. First of all, the Helm update is still necessary when we're using dependencies? Evenson: It depends if you want to package your dependent charts and snapshot them and have them in the chart repository when you zip it up or whether you want to pull them at runtime from an upstream source. You still need to use package update to pull them down into the actual chart before you package it. Participant 1: Also, for local charts, right? Evenson: Yes. Participant 1: Ok. The second one is, the CRDs, when I do helm uninstall, of course, it doesn't install the CRDs, right? Evenson: Helm uninstall does not uninstall the CRDs, which was a main pain point with Helm 2. It would process the hooks in reverse. When you uninstall an app that had CRDs, it would not uninstall the CRDs. Participant 2: You did mention the OCI. I just wanted to check if you can publish the Helm chart into Docker registry. Evenson: Docker Hub does not yet support distribution v2 yet, which is the specification that lays out the metadata required to store Helm charts in a container registry. They are part of the OCI, so I would assume. I don't know if there's any Docker folks here, but I would assume they would update to make that allowable in future. It's not there yet. I think Harbor has it. ChartMuseum has it. Azure Container Registry has it. They're the only three I know, but there may be more. Participant 2: Ok, thank you. I have another question. Can we use Helm update for scaling? Evenson: Yes. You can use Helm update to scale or change the parameter in a template, which could trigger a scaling event on a given resource. If you have a stateful application that's either using, typically there, a stateful set or a custom resource, if you change the template so that it becomes an applied that changes the replicas, then that will trigger the behavior. Helm doesn't do anything that changed their resource, and then it relies on Kubernetes to perform. Participant 2: So it will not redeploy the entire thing. Evenson: No, only the delta using the three-way merge. If you say, "I need this one field changed, which said three to six," it'll change that field, and then Kubernetes will pick that up and roll out change your stateful application. Participant 3: Once I deploy my release through Helm, are you saying we should not use kubectl to make any configuration changes, ConfigMaps or scaling up, all of them? Evenson: I can't give you a prescriptive advice. I think using Helm to perform all the operations might be easier, but if you have intrinsic knowledge of how Helm works and what it does, I know some people write tooling around not using Helm for day two. They'll lay down, use Helm, and then they use another set of tooling to actually deal with resource changes over time. The goal of Helm is to provide rollback, upgrade, install, delete, so all the lifecycle hooks that you would want, but how that plays out is really up to the chart maintainer to determine. Participant 3: If I say that I'm not using kubectl and using all the Helm to upgrade my pieces, you call it as best practice? Evenson: I would say the best practices use declarative. As long as you have it some way that's stored and that you're operating off resources that you had stored in some kind of versioning system, then that's probably best practice. Imperative changes, like editing replica counts live on a cluster, that's going to get lost. Participant 3: Ok, thank you. Now, the release name is stored within the namespace, now we can have the same release name... Evenson: Across namespaces, yes. If you and I are working on the same cluster, assuming we're not, that was something that was limiting in Helm 2. People wanted to call it WordPress and WordPress and we're in different namespaces, why can't we do that? Yes, it's now namespace-specific. Participant 3: Ok. One last question about kubeval plugin or pre-release check. Are these equivalent to testing your chart? Evenson: Yes. Participant 3: If yes, then can we do it in the earlier environment rather than the production environment? Evenson: Totally. Yes, they are pre-checks. Have you seen the chart testing repository in the Helm? There is a community maintained chart testing, and that's the tooling we use to test the upstream charts. We have linters and installations against a cluster. We make sure that everything works. You can use that as well and pull that down into your own deployment environment. Participant 3: In my environment, the policies are not going to be the same. Is there a better way to install various policies within this chart? Evenson: If there are environmental differences in policies, you'd need to store them in the chart and have them configurable depending on the environment. If you're using something like conftest, it'll pull policy from any repo. It pulls them from an upstream git-repo or any git-repo. You could have policy that's environment-specific and test against that environment's policy if you wanted to. Participant 4: Bringing the CRDs upfront is really cool, but is there more general lifecycle support? I'm thinking namespaces obviously, even anti-pattern maybe, service accounts, that kind of stuff that have to be made. I'm thinking the Istio chart literally has a separate init chart writer. Evenson: Right, just to build everything. Not at this point. The lines are blurry, I would say, between operators and Helm charts. Some people expect the operator to take care of that, and other people expect the resources to be pre-created. It's going to depend on how you want to use it and what the split of your personas are internally. Do I have an Ops person create the service accounts? We're willing to listen if that's a better practice for us to do as part of the Helm chart community. See more presentations with transcripts Community comments
https://www.infoq.com/presentations/helm-3/?utm_source=presentations&utm_medium=sf&utm_campaign=qcon
CC-MAIN-2020-16
refinedweb
8,338
72.87
Whenever you create or modify a user account from a web browser, you are indirectly working with the user view. From the perspective of altering user account information, it is the most significant view in the Identity Manager system. Workflow processes also interact with the user view. When a request is passed to a workflow process, the attributes are sent to the process as a view. When a manual process is requested during a workflow process, the attributes in the user view can be displayed and modified further. Like all views, the user view is implemented as a GenericObject that contains a set of attributes. The values of the attributes in the root object are themselves GenericObjects. Attributes can be nested. The user view contains the attributes described in the following table, which are further defined in subsequent sections.Table 3–1 Top-Level Attributes User View When you design a form, the field names are typically paths into the user view objects waveset. global, and account attributes (for example, global.firstname). The user view provides several namespaces for deriving account-related information. The following table summarizes these variable namespaces.Table 3–2 Account-Related User View Attributes Within a form, you can reference attributes in two ways: Use the name attribute of a Field element by adding the complete attribute pathname as follows: <Field name=’waveset.accountId’> For more information on setting the Field name element in a form field, see the chapter titled Identity Manager Forms. Reference an attribute from within another field: Within workflow, you can reference Field attributes as process variables (that is, variables that are visible to the workflow engine) or in XPRESS statements for actions and transitions. When referencing these attributes in workflow, you must prefix the path with the name of the workflow variable where the view is stored (for example, user.waveset.accountId). You can define fields that store values at the top-level of the user view, but these values are transient. Although they exist throughout the life of the in-memory user view (typically the life of the process), the values of these fields are not stored in the Identity Manager repository or propagated to a resource account. For example, a phone number value is the result of concatenating the values of three form fields. In the following example, p1 refers to the area code, p2 and p3 refer to the rest of the phone number. These are then combined by a field named global.workPhone. Because the combined phone number is the only value you want propagated to the resources, only that field is prepended with global. In general, use the top-level field syntax if you are: not pushing a field value out to Identity Manager or any other resource the field is being used only in email notifications or for calculating other fields. Any field that is to be passed to the next level must have one of the path prefixes defined in the preceding table, User View Attributes. The waveset attribute set contains the information that is stored in a WSUser object in the Identity Manager repository. Some attributes nested within this attribute set are not intended for direct manipulation in the form but are provided so that Identity Manager can fully represent all information in the WSUser object in the view. Not) Specifies the visible name of the Identity Manager user object. It must be set during user creation. Once the user has been created, modifications to this attribute will trigger the renaming of the Identity Manager account. For information on renaming a user, see Business Administrator's Guide. Contains a list of the names of each application (also called resource group in the Identity Manager User Interface) assigned directly to the user. This does not include applications that are assigned to a user through a role. Collection of arbitrary attributes that is stored with the WSUser in the Identity Manager. Contains the correlation value used to identify a user during reconciliation and discovery of users. You can directly edit it, although it is generally not exposed. Contains the name of the administrator that created this user. This attribute is read-only. Contains the date on which this account was created. Dates are rendered in the following format: MM/dd/yy HH:mm:ss z 05/21/02 14:34:30 CST This attribute is set once only and is read-only. Contains. Specifies the email address stored for a user in the Identity Manager repository. Typically, it is the same email address that is propagated to the resource accounts. Modifications to this attribute apply to the Identity Manager repository only. If you want to synchronize email values across resources, you must use the global.email attribute. You can modify this attribute. List the names of the resource that will be excluded from provisioning, even if the resource is assigned to the user through a role, resource group, or directly. Identifies the repository ID of the Identity Manager user object. Once the user has been created in Identity Manager, this value is non-null. You can test this value to see if the user is being created or edited. This attribute is tested with logic in the form. You can use it to customize the displayed fields depending on whether a new user is being created (waveset.id is null) or an existing user account is being edited (waveset.id is non-null). The following example shows an XPRESS statement that tests to see if waveset.id is null: <isnull><ref>waveset.id</ref></isnull> Contains the date at which the last modification was made. It represents the date by the number of milliseconds since midnight, January 1970 GMT. This attribute is updated each time a user account is modified. This attribute is read-only. Contains the name of the administrator or user that last modified this user account. This attribute is read-only. Indicates whether the user is locked. A value of true indicates that the user is locked. Specifies when the user lock expires if the user’s Lighthouse Account policy contains a non-zero value for the locked account expiry date. This attribute value is a human-readable date and time. Contains the name of the organization (or ObjectGroup) in which a user resides. An administrator can modify this attribute if he has sufficient privileges for the new organization. Since changing an organization is a significant event, the original value of the organization is also stored in the waveset.original attribute, which can be used for later comparison. Contains). Specifies the Identity Manager user password. When the view is first constructed, this attribute does not contain the decrypted user password. Instead, it contains a randomly generated string. The password attribute set contains the attributes described in the following table.Table 3–4 Attributes of the password Attribute (User View) Contains the date on which the Identity Manager password will expire. When the view is initially constructed, the memory representation will be a java.util.Date object. As the view is processed with the form, the value can either be a Date object or a String object that contains a text representation of the date in the format mm/dd/yy. Contains the date on which warning messages will start being displayed whenever the user logs into the Identity Manager User Interface. This is typically a date prior to the waveset.passwordExpiry date in the same format (mm/dd/yy). Contains information about the authentication questions and answers assigned to this user. The value of the attribute is a List whose elements are waveset.questions attributes. The waveset.questions attribute set contains the attributes described in the following table.Table 3–5 waveset.questions Attributes (User View) The name attribute is not stored. The system generates the name by transforming the id. This is necessary because question IDs are typically numbers, and numbers that are used to index an array in a path expression are considered absolute indexes rather than object names. For example, the path waveset.questions[#1].question addresses the second element of the questions list (list indexes start from zero). However, since there may be only one question on the list whose ID is the number 1, the ID is not necessarily suitable as a list index. To reliably address the elements of the list, the system manufactures a name for each question that consists of the letter Q followed by the ID (in this example, Q1). The path waveset.questions[Q1].question then always correctly addresses the question. Contains a list of the names of each resource that is assigned directly to the user. This list does not include resources that are assigned to a user through a role or through applications. You can add only unqualified resource names to this attribute. To find all resources that are assigned to a user, see the section on the accountInfo attribute. Qualifies. Contains a list of objects that contain information about the roles assigned to this user.Table 3–6 waveset.roleInfos Attributes Contains. Use to set unique server names when your deployment includes multiple Identity Manager instances that point to one repository on a single physical server. See Installation Guide for more information.
http://docs.oracle.com/cd/E19225-01/820-5821/6nh6l8upb/index.html
CC-MAIN-2016-30
refinedweb
1,543
56.66
Duncan Booth wrote: > > westernsam at hotmail.com (sam) wrote in > news:292c8da4.0307040627.59acda19 at posting.google.com: > > > So the Exception isn't recognised even though it has the same > > namespace and name as the exception defined in the module. I have to > > uncomment the 7th line to get my example to behave as I would like it > > to. > > > > Is this a bug/feature? Is there any reason why it shouldn't work the > > way I expect it to? > > It's a feature, and it probably ought to be in the FAQ in some form. [snip explanation] And the solution is to avoid putting things into your __main__ module (the one run from the command line) which other modules need to find by importing it. If the application is so complex that it needs to have multiple modules, make the main one do something simple like import an Application class from somewhere else, instantiate it, and call .run() on it (or whatever...). -Peter
https://mail.python.org/pipermail/python-list/2003-July/203628.html
CC-MAIN-2017-17
refinedweb
163
74.29
On Tuesday, 9 May 2000, [EMAIL PROTECTED] wrote: > -- Problem description: > When compiling, SA_NOMASK is undefined. > -- Other comments: > Checking a RedHat 6.2 machine indicates this is simply > #define'ed from SA_NODEFER. Adding the folowing code to > app/main.c and libgimp/gimp.c solves the problem: > > #ifndef SA_NOMASK > #define SA_NOMASK SA_NODEFER > #endif Why are we even _trying_ to set SA_NOMASK or SA_NODEFER? SA_NODEFER is a SVR4-ism, SA_NOMASK is as linux-ism, and neither of them are desirable. As far as I understand it, this asked that while the signal handling function runs, the signal being processed is not blocked. This is really quite dangerous behaviour, since the signal handler must now be made reentrant. I don't understand why we're going to quite a lot of trouble to enable a "feature" we really don't want in the first place! Austin
https://www.mail-archive.com/gimp-developer@scam.xcf.berkeley.edu/msg02336.html
CC-MAIN-2017-51
refinedweb
143
66.54
Since our last TechNet feature package on Windows 8, we have added several new resources to help you explore, plan for, deploy, manage, and support Windows 8 as part of your IT infrastructure. First up, the Springboard team hosted a virtual roundtable of deployment experts from the IT community, IT pros who have been through the Windows 8 deployment process, and members of the Windows product team. They came up with some valuable tips for deploying Windows 8 in the enterprise, and take a walk through the latest Windows 8 devices....Read more This new virtual lab shows you how to create and test a local and domain Windows 8 AppLocker policy for a preinstalled app. No complex setup or new hardware necessary - get hands-on today. Kevin Remde welcomes Senior Product Manager Michael Niehaus to the show as they discuss the tools, technologies, tips, and tricks that are available to enable efficient deployment of Windows 8 onto new or existing hardware. Tune in for part 1 of their discussion as they give us an overview of the Microsoft Deployment Toolkit, ADK, WDS, and System Center 2012 SP1 Configuration Manager. How do you deploy a read-only domain controller using PowerShell in Windows Server 2012? Learn how, hands-on and free in our new virtual lab. J. Peter Bruzzese investigates the storage improvements in Windows Server 2012. The outcome: "Windows Server 2012 makes a major push to improve its storage management and virtualization technologies." Evaluate these improvements yourself and download the Windows Server 2012 Evaluation. Join David Tesar and Drew McDaniel from the Azure products team for this demo-heavy video interview filled with tips and insight about Windows Azure VMs. The session covers the scenarios in which we see customers using Windows Azure IaaS. It will also provide demos of Windows Azure VMs, including creating gallery images with Windows Server and Linux. Kevin Remde welcomes Douglas Chrystall, Chief Architect at Dell Software, to discuss Foglight for Windows Azure applications - a new product offering from Dell that helps monitor applications built on the Azure platform. Tune in as they chat about this solution, which can provide diagnostics and improve your application's performance. Sign in with your Windows Account to try Windows Azure free for 90 days. HortonWorks announced another interoperability achievement for the Apache Hadoop project by highlighting how Hadoop now runs natively on Microsoft Windows platforms. Download a printable, one-page guide to the top resources that will help you explore, plan for, deploy, manage, and support Windows 8 as part of your IT infrastructure. Download the free Windows 8 Enterprise Evaluation to get started. A great thing about Windows Store apps is they are super simple to install (and uninstall). But what about line of business (LOB) apps? You can sideload LOB apps, which simply means installing a Windows Store app without publishing it to and downloading it from the store. You install it directly. This week on the Garage Series, hosts Jeremy Chapman and Yoni Kirsh. Learn about three customers who selected Windows Server Hyper-V over other providers, including VMware, to achieve impressive enterprise innovation and trim IT costs. ING Commercial Banking, American University of Beirut, and Florida Atlantic University deployed Hyper-V and are thrilled with the results. Learn how these customers use Microsoft's virtualized private cloud environments to gain benefits such as solved business problems, satisfied stakeholders, and savings up to US$600,000. Download the free Windows Server 2012 Evaluation now and test it yourself. Bob Hunt and Jose Barreto continue their TechNet Radio Windows Server 2012 File Server and SMB 3.0 series. In this episode they lay out their top tips and tricks. Tune in as they disclose a number of useful bits of information such as how to use multiple subnets when deploying SMB multichannel in a cluster, and how to avoid loopback configurations for Hyper-V over SMB. Check out the full series here.Sign in with your Windows Account to evaluate Windows Server 2012 or download Hyper-V 2012. Ann Vu, Ross Smith, Jeff Mealiffe, and Todd Luttinen are back, and in today's Exchange Ideas episode, they discuss Exchange Server 2013 architecture planning. Tune in as they chat about things you may want to plan for in your environment, such as multiple and single namespaces, high availability and site resilience, unified messaging, and virtualization considerations. Use hi-speed, hi-fidelity SharePoint replication for fast user access in every location. Watch the Replicator demo to see how. LinkFixer Advanced automatically fixes broken links within Word, Excel, Access, Acrobat, AutoCAD, and other files during data migrations.Get a free trial version today. Join certified virtualization expert Symon Perriman for an interactive Introduction to Hyper-V on April 3. This first session in a monthly series of free audience-led Q&A gives IT professionals who are new to virtualization or experienced with other hypervisors the chance to ask questions about technical capabilities, get advice for using products in a live environment, and learn from their peers in the industry. Need a plan to get Microsoft Certified Solutions Associate (MCSA) certified for the cloud? Join the 90 Days to MCSA program and get the resources you need, plus a plan of action to get certified for the cloud with Windows Server and SQL Server. When you join, you'll get access to a road map, tools, and community support designed to help you achieve your MCSA goal. Also, take the opportunity to purchase an exam voucher bundle and save 15%. Join us in New Orleans, Louisiana, June 3 - 6, or Madrid, Spain, June 25 - 28. TechEd is Microsoft's premiere event for IT professionals and enterprise developers. Get hands-on learning, deep product exploration, and countless opportunities to build relationships with a community of Microsoft experts and your peers. Early registration ends March 22, so sign up and save..
http://technet.microsoft.com/en-us/subscriptions/dn194018
CC-MAIN-2014-52
refinedweb
981
52.49
The Q3TableItem class provides the cell content for Q3Table cells. More... #include <Q3TableItem> This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information. Inherited by Q3CheckTableItem and Q3ComboTableItem. The Q3TableItem class provides the cell content for Q3Table cells. For many applications Q3TableItems are ideal for presenting and editing the contents of Q3Table cells. In situations where you need to create very large tables you may prefer an alternative approach to using Q3TableItems: see the notes on large tables. A Q33CheckTableItem, and if you want comboboxes use Q333TableItem(table, Q3TableItem::WhenCurrent, QString::number(row * col))); } } You can move a table item from one cell to another, in the same or a different table, using Q3Table::takeItem() and Q3Table::setItem() but see also Q33TableItems during the lifetime of a Q3Table. Therefore, if you create your own subclass of Q3TableItem, and you want to ensure that this does not happen, you must call setReplaceable(false) in the constructor of your subclass. See also Q3CheckTableItem and Q3ComboTableItem.3TableItem objects are created by the convenience functions Q3Table::setText() and Q3Table::setPixmap(). The cell is actually editable only if Q3Table::isRowReadOnly() is false for its row, Q3Table::isColumnReadOnly() is false for its column, and Q3Table::isReadOnly() is false. Q3ComboTableItems have an isEditable() property. This property is used to indicate whether the user may enter their own text or are restricted to choosing one of the choices in the list. Q3ComboTableItems may be interacted with only if they are editable in accordance with their EditType as described above.3Table::setItem(). The table takes ownership of the table item, so a table item should not be inserted in more than one table at a time. The destructor deletes this item and frees all allocated resources. If the table item is in a table (i.e. was inserted with setItem()), it will be removed from the table and the cell it occupied. The alignment function returns how the text contents of the cell are aligned when drawn. The default implementation aligns numbers to the right and any other text to the left. See also Qt::Alignment. Returns the column where the table item is located. If the cell spans multiple columns, this function returns the left-most column. See also row() and setCol(). Returns the column span of the table item, usually 1. See also setSpan() and rowSpan(). This virtual function creates an editor which the user can interact with to edit the cell's contents. The default implementation creates a QLineEdit. If the function returns 0, the cell is read-only. The returned widget should preferably be invisible, ideally with Q3Table::viewport() as parent. If you reimplement this function you'll almost certainly need to reimplement setContentFromEditor(), and may need to reimplement sizeHint(). See also Q3Table::createEditor(), setContentFromEditor(), Q3Table::viewport(), and setReplaceable(). Returns the table item's edit type. This is set when the table item is constructed. See also EditType and Q3TableItem(). Returns true if the table item is enabled; otherwise returns false. See also setEnabled().. This virtual function returns the key that should be used for sorting. The default implementation returns the text() of the relevant item. See also Q3Table::setSorting().); Returns the table item's pixmap or a null pixmap if no pixmap has been set. See also setPixmap() and text(). Returns the row where the table item is located. If the cell spans multiple rows, this function returns the top-most row. See also col() and setRow(). Returns the row span of the table item, usually 1. See also setSpan() and colSpan(). Returns the Run Time Type Identification value for this table item which for Q3TableItems is 0. When you create subclasses based on Q3TableItem make sure that each subclass returns a unique rtti() value. It is advisable to use values greater than 1000, preferably large random numbers, to allow for extensions to this class. See also Q3CheckTableItem::rtti() and Q3ComboTableItem::rtti(). Sets column c as the table item's column. Usually you will not need to call this function. If the cell spans multiple columns, this function sets the left-most column and retains the width of the multi-cell table item. See also col(), setRow(), and colSpan(). Whenever the content of a cell has been edited by the editor w, Q3Table calls this virtual function to copy the new values into the Q3TableItem. If you reimplement createEditor() and return something that is not a QLineEdit you will need to reimplement this function. See also Q3Table::setCellContentFromEditor(). If b is true, the table item is enabled; if b is false the table item is disabled. A disabled item doesn't respond to user interaction. See also isEnabled(). Sets pixmap p to be this item's pixmap. Note that setPixmap() does not update the cell the table item belongs to. Use Q3Table::updateCell() to repaint the cell's contents. For Q3ComboTableItems and Q3CheckTableItems this function has no visible effect. See also Q3Table::setPixmap(), pixmap(), and setText(). If b is true it is acceptable to replace the contents of the cell with the contents of another Q3(). Sets row r as the table item's row. Usually you do not need to call this function. If the cell spans multiple rows, this function sets the top row and retains the height of the multi-cell table item. See also row(), setCol(), and rowSpan(). Changes the extent of the Q3TableItem so that it spans multiple cells covering rs rows and cs columns. The top left cell is the original cell. Warning: This function only works if the item has already been inserted into the table using e.g. Q3Table::setItem(). This function also checks to make sure if rs and cs are within the bounds of the table and returns without changing the span if they are not. In addition swapping, inserting or removing rows and columns that cross Q3TableItems spanning more than one cell is not supported. See also rowSpan() and colSpan(). Changes the table item's text to str. Note that setText() does not update the cell the table item belongs to. Use Q3Table::updateCell() to repaint the cell's contents. See also Q3Table::setText(), text(), setPixmap(), and Q3Table::updateCell(). If b is true, the cell's text will be wrapped over multiple lines, when necessary, to fit the width of the cell; otherwise the text will be written as a single line. See also wordWrap(), Q3Table::adjustColumn(), and Q3Table::setColumnStretchable(). This virtual function returns the size a cell needs to show its entire content. If you subclass Q3TableItem you will often need to reimplement this function. Returns the Q3Table the table item belongs to. See also Q3Table::setItem() and Q3TableItem(). Returns the text of the table item or an empty string if there is no text.(). Returns true if word wrap is enabled for the cell; otherwise returns false. See also setWordWrap().
http://doc.trolltech.com/4.5-snapshot/q3tableitem.html#alignment
crawl-003
refinedweb
1,165
67.76