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
I'm having a problem with calling arrays from a class. I know I should should separate the user interface from the logic so that's what I've tried to do. If you know of a better way please mention that too Anyway, when ever I use an array list, it always starts with "null". The only fix I've been able to find is by chopping off the first few characters. This is an example of which the output is: nullname1 name2 name3 name4 name5student students = new student(); System.out.println(students.getStudent()); public class student { private String student; public String getStudent() { String[] students = {"name1","name2","name3","name4","name5"}; for (int i = 0; i < students.length; i++) { student = student + students[i] + "\n"; } return student; } } Thanks
http://www.javaprogrammingforums.com/whats-wrong-my-code/12801-array-null-same-arraylist.html
CC-MAIN-2017-26
refinedweb
127
63.59
). He was talking about the CSS & Javascript intellisense, but I have a feeling you knew that anyway. All the poster mentioned was CSS and JavaScript support, and quite frankly, Internet Explorer, Microsoft's development tools and proper, standard support of ECMA(Java)Script and Cascading Style Sheets are absolute polar opposites. The hint of irony and sarcasm was absolutely spot on, and pretty well done. Quite frankly, I'm distinctly underwhelmed by yet another new version of .Net that no normal person can keep up with. Microsoft simply have too many MSDN lunatics producing too many development tools no sane person can keep up with. I wonder if there is a way to develop a web browser that has a plug in architecture for the CSS. That would allow CSS to improve asynchronous to IE releases, or any browser release... and if it was an Open Source project, we might see some significant improvements in support all together. Quite frankly, I'm distinctly underwhelmed by yet another new version of .Net that no normal person can keep up with. Microsoft simply have too many MSDN lunatics producing too many development tools no sane person can keep up with. Haha, so true. I recall listening to an episode of the .NET Rocks podcast recently, and they were talking about how it used to be possible (like back in the early days) for a person to know pretty much everything there was to know about a PC. But now days, it's getting pretty much impossible just to keep track of everything in the .NET Framework itself. Makes me wonder if the people coding the .NET Framework ever sleep But now days, it's getting pretty much impossible just to keep track of everything in the .NET Framework itself. Makes me wonder if the people coding the .NET Framework ever sleep You specialize in certain areas and that's it (for example, ASP.NET). For other stuff you use MSDN/Help. You don't get to claim you're an expert on everything. "But now days, it's getting pretty much impossible just to keep track of everything in the .NET Framework itself." The key to any software developer's job is knowing how to read documentation, and knowing where to look for said documentation. The rest comes with experience. I've been a professional .Net dev for 6 years now, and still run into new BCL classes on a weekly basis. Concepts are always the most important part of the job, followed very closely by the tools you use.. Microsofts support of javascript is worse then mozilla, but better then anything else. And as of IE7, their CSS support is pretty much where everyone else is Anyone with half a brain can keep up with it, the last release was 3 years ago. Edited 2007-11-20 03:58 UTC. "Worrying about five different versions of .Net to target, with more on the way presumably, is not solving anyone's problems." FUD. Target whatever version you want. Just get the client to install the version you use. You know, you can have all the .net versions installed without any problems. FUD. Target whatever version you want. Just get the client to install the version you use. You know, you can have all the .net versions installed without any problems. If only it were that easy. Not only do you need to test with that version, or test with all versions, .Net and your application do not stand by themselves. There is a veritable panoply of dependencies to take care of in addition to .Net, in addition to worrying about what framework is installed, installing a new framework if the one you want isn't there or simply assuming things are compatible. WinForms or Avalon? God knows. Why should one even need to pick? Hell, installation on Linux is beginning to look attractive! This isn't FUD. This is happening today, and has been for some time. As Joel Spolsky once said about this, it's not 1990 any more.? I'd be inclined to say StyleMaster has been doing that for years, but obviously StyleMaster isn't an HTML editor, solely CSS. Anyone looking for a powerful CSS editor though that develops with tools other than VS.net, or develops on OS X, should probably check it out. N.B. I bought the 4.x version at least a year or two ago*, and it seems I'm still up to date (free upgrades), though whether they're planning a new major release or not anytime soon I don't know. Off-topic, but the logo was designed by Jon Hicks of Firefox/Thunderbird/Miro fame :-) * (edit) - 14 Dec 2005 21:32 to be precise, feh. Edited 2007-11-20 12:50 While most "zomg Microsoft steals from everyone I cut myself"-type posts like this have no basis in reality whatsoever, this actually has some fact behind it:. Agreed. And besides "LING to SQL" and "LINQ to XML", Microsoft has also created LINQ to Objects, which gives LINQ the ability to query any collection or object that implements IEnumerable. And there are already third party LINQ providers specializing in querying particular data (web queries, RSS feeds, etc). And of course, there's PLINQ (Parallel LINQ) that automatically runs queries on multiple cores/cpus. LINQ rocks. May I ask the question as to whether LINQ has a syntax that is the same across all database back-ends or is it specific to the database in question? If it is specific to a particular database then that sux from a migration point of view (which happens in the real world). I've just completed a government Postgresql to Oracle project and the database specific SQL in JDBC sux. They should have used Hibernate which has the same syntax no matter what the target is. LINQ is actually built into the C# (and other .NET) languages, so it is necessarily the same for all backends. However, you do have the option of sticking in custom stuff yourself into the code generated by the backends. So by default it is the same everywhere, but customizable enough that you can make it non-portable. MS hired the guy who does this, which is basically rails type scaffolding for .net.). Yes, but then you have to deal with the fact that you're writing in Java. >? Visual Studio.NET has always been an unbeatable IDE (though lacking in some basic functionalities that IDEs like Eclipse have, such as maximizing an editor). Maximizing an editor? You mean like full screen mode? It is available in Visual Studio 2008. And it is also in Visual Studio 2005. Funny. No, not full screen mode. He is referring to the nice little feature of Eclipse where you can click a small "maximize" button on a panel and make that panel take the whole window space. While VS's full-screen mode does hide some of the other panels (still shows the "Pending chekins" panel on mine), it also hides everything else, meaning I can't copy-and-paste from another source, can't quickly switch to an output window, etc. In other words Eclipse has a better UI (and I use VS every day). Please note that targeting 2.0 is NOT targeting 2.0 RTM. You will be targeting 2.0 SP1, which (depending on your application) can have significant ramifications. This blog explains it in detail:... I use vi *, ** - Gilboa * Even under Windows; Compared to VS.NET2K5 vim+ctags is like comparing a cargo 747 to a SR-71. You may do more with VS.NET2K5 but once you get the hang of it, vim is 1000 times faster... ** I write C code, so anything beyond VC6 is an over-kill for me. Sadly enough our IT department doesn't see it that way.."]); } } If you cannot keep up with the developments, perhaps you are in the wrong industry? I can tell you don't develop software for customers. Installation and implementation issues take up the vast majority of your time, not development. The developments are incremental over the period of 3 years since Visual Studio 2005. Each feature, and there are ONLY about 4-5 significant language/process changes People are installing their applications on Windows target machines, not Visual Studio or .Net. The productivity is poor as well. I'd rather not waste my life re-inventing the wheel every 8 seconds. One word: ActiveRecord. Try writing this in C with Vim in 45 seconds (even using any C library What are you talking about C for? Have a go at writing that in Python, Ruby or even Java. In reply to various comments: a) I do develop customer-centric software! Lots of it. b) ActiveRecord is POOR compared to LINQ. Its performance is horrible,. c) Java doesnt' have an equivalent to LINQ. Python has SQLobject which doesn't even remotely compare (different model), Ruby has ActiveRecord which is totally non performant. d) You don't need Visual studio to compile C# code - what total rubbish. csc.exe is present on ALL .Net installations (runtime!) in C:WindowsMicrosoft.NetFrameworkvWHATEVERcsc.exe and acts the same as GCC does on linux with respect to compilation. You can use cmd's type command and then use csc to compile. Idiots. Will people stop arguing without facts? Further rant: I have used Python (Django) and Ruby on Rails for some small projects but they just don't cut it.? Try writing this in C with Vim in 45 seconds (even using any C library: class A { public static void Main() { Dictionary<string, string> x = new Dictionary<string, string>(); x.Add("Key", "value"); Console.WriteLine(x["Key"]); } } How about Java using no editor at all? Did that 45 seconds include starting up Visual studio and creating a new project? $ cat > Test.java <<EOF && javac Test.java && java Test > import java.util.*; > public class Test{ > public static void main(final String args[]){ > Map<String,String> x = new HashMap<String,String>(); > x.put("Key","Value"); > System.out.println(x.get("Key")); > } > } > EOF Value $ echo Wow! Wow! $ Edited 2007-11-20 15:54.
http://www.osnews.com/comments/18949
CC-MAIN-2014-35
refinedweb
1,699
67.15
Boris Kolpackov wrote: > > In this case no re-execution happens unless you are using some > really cool technique inside > > ifeq ($(MAKELEVEL),0) > endif > > that I am not aware of (and you've got to tell me about it). Like I suggested in a prior email, please read for the technique to re-execute make. > No I am not and that's exactly why my makefiles are big (well, actually > they are not that big, there are just hundreds or even thousands of them) > and reading them all in just to re-execute is not an option. I haven't checked to see if the "gmake self wrapper" technique will read all the makefiles twice. If it does, you're right, this would be a bad thing. > > >Set where? in environment? No, thank you! ;-) > > > > One idea, from an offline thread, is to have a configuration file similar > > to CVS's .cvsrc. One thought is to have a global configuration file that > > can set MAKEFILES. > > Anything global would be a bad thing because people use make to build > a lot of different things. What may be useful for one build system can > render the others completely broken (-r comes to mind). An added thought in that thread is to have a MAKECONFIG environment variable which is set to a filename, eg .makerc. When make executes, $MAKECONFIG is searched in parent directories and used if it's found. In this scenario, there's no global setting whatsoever (except possibly for MAKECONFIG if users want to use it). > > Of course, this all depends on what sort of project you're supporting. > > Well, it is a general-purpose build system for configuring/building/installing > c/c++ applications. One day, when things settle a bit, I will make it > publicly available. I believe it's more general than that :-) Noel
http://lists.gnu.org/archive/html/help-make/2004-04/msg00028.html
CC-MAIN-2019-13
refinedweb
304
71.24
Frank Küster wrote: > Graham Wilson <bob@decoy.wox.org> schrieb: > > > On Mon, Oct 04, 2004 at 05:27:59PM +0200, Frank Küster wrote: > >> Seo Sanghyeon <tinuviel@sparcs.kaist.ac.kr> schrieb: > >> > For example, "camera" package name was changed to "camera.app" to > >> > prevent namespace pollution. Are you saying that it should be > >> > "gnustep-camera.app"? If so, why? > >> > >>? > > I never used nautilus or epiphany. I used evolution (in woody), but > dropped it because it didn't seem to behave deterministic... > > Anyway, I think it depends on what one means with "GNOME installed". I > don't mind having some libraries for Gnome around (actually I use > gnumeric), but for sure I do not want the Gnome desktop. > > But if I remember correctly, GNUstep applications do not just work if > X11 and some basic library is installed, but need the GNUstep desktop to > be installed. With Gnome and KDE, I had the impression that it was > intended that all applications are usable even without using the Desktop > environment - although of course they might work and interact nicer in > their "native" environment. With GNUstep, it seemed to me that it was > not intended to run applications without the Desktop > environment. Comparable to WindowMaker Dock applications, which probably > will not run under any other windowmanager. > > If I'm wrong, I apologize and will not object against cddb.bundle (at > least not because of this. Still the ".bundle" part is meaningless to > me, but that might be due to my bad english). If I am not wrong, and > GNUstep applications are indeed not designed to be used without using > the Desktop environment, then, please, add "gnustep-" to the name. Yes, you are _very_ clearly wrong. There is no GNUstep program that requires the GNUstep Desktop, because there no GNUstep Desktop to require! >From the user's perspective, GNUstep is basically a set of libs and some directory hierarchy imposed by the requirements of the specifications GNUstep implements. That's it. The libs provide a pretty platform-independant library of non-GUI classes, and a fairly-well-working library of GUI classes that is partially window-system independant (i.e. the only GUI backends that work completely are for X, but there's one for Windows GDI that isn't too evil). GNUstep does not form a desktop environment, and it doesn't even claim
https://lists.debian.org/debian-devel/2004/10/msg00146.html
CC-MAIN-2016-40
refinedweb
389
64.61
Download presentation Presentation is loading. Please wait. Published byMark Henry Modified about 1 year ago 1 Intel x86 Instruction Set Architecture Computer Organization and Assembly Languages Yung-Yu Chuang with slides by Kip Irvine 2 Data Transfers Instructions 3 3 MOV instruction Move from source to destination. Syntax: MOV destination, source Source and destination have the same size No more than one memory operand permitted CS, EIP, and IP cannot be the destination No immediate to segment moves 4 4 MOV instruction.data count BYTE 100 wVal WORD 2.code mov bl,count mov ax,wVal mov count,al mov al,wVal; error mov ax,count; error mov eax,count; error 5 5 Exercise... Explain why each of the following MOV statements are invalid:.data bVal BYTE 100 bVal2 BYTE ? wVal WORD 2 dVal DWORD 5.code mov ds,45; a. mov esi,wVal; b. mov eip,dVal; c. mov 25,bVal; d. mov bVal2,bVal; e. 6 6 Memory to memory.data var1 WORD ? var2 WORD ?.code mov ax, var1 mov var2, ax 7 7 Copy smaller to larger.data count WORD 1.code mov ecx, 0 mov cx, count.data signedVal SWORD -16; FFF0h.code mov ecx, 0 ; mov ecx, 0FFFFFFFFh mov cx, signedVal MOVZX and MOVSX instructions take care of extension for both sign and unsigned integers. 8 8 Zero extension mov bl, b movzx ax,bl; zero-extension When you copy a smaller value into a larger destination, the MOVZX instruction fills (extends) the upper half of the destination with zeros. The destination must be a register. movzx r32,r/m8 movzx r32,r/m16 movzx r16,r/m8 9 9 Sign extension mov bl, b movsx ax,bl; sign extension The MOVSX instruction fills the upper half of the destination with a copy of the source operand's sign bit. The destination must be a register. 10 10 MOVZX MOVSX From a smaller location to a larger one mov bx, 0A69Bh movzx eax, bx; EAX=0000A69Bh movzx edx, bl; EDX= Bh movzx cx, bl; EAX=009Bh mov bx, 0A69Bh movsx eax, bx; EAX=FFFFA69Bh movsx edx, bl; EDX=FFFFFF9Bh movsx cx, bl; EAX=FF9Bh 11 11 LAHF/SAHF (load/store status flag from/to AH).data saveflags BYTE ?.code lahf mov saveflags, ah... mov ah, saveflags sahf S,Z,A,P,C flags are copied. 12 12 EFLAGS 13 13 XCHG Instruction XCHG exchanges the values of two operands. At least one operand must be a register. No immediate operands are permitted..data var1 WORD 1000h var2 WORD 2000h.code xchg ax,bx; exchange 16-bit regs xchg ah,al; exchange 8-bit regs xchg var1,bx; exchange mem, reg xchg eax,ebx; exchange 32-bit regs xchg var1,var2; error 2 memory operands 14 14 Exchange two memory locations.data var1 WORD 1000h var2 WORD 2000h.code mov ax, val1 xchg ax, val2 mov val1, ax 15 Arithmetic Instructions 16 16 Addition and Subtraction INC and DEC Instructions ADD and SUB Instructions NEG Instruction Implementing Arithmetic Expressions Flags Affected by Arithmetic –Zero –Sign –Carry –Overflow 17 17 INC and DEC Instructions Add 1, subtract 1 from destination operand –operand may be register or memory INC destination Logic: destination destination + 1 DEC destination Logic: destination destination – 1 18 18 INC and DEC Examples.data myWord WORD 1000h myDword DWORD h.code inc myWord ; 1001h dec myWord; 1000h inc myDword; h mov ax,00FFh inc ax; AX = 0100h mov ax,00FFh inc al; AX = 0000h 19 19 Exercise... Show the value of the destination operand after each of the following instructions executes:.data myByte BYTE 0FFh, 0.code mov al,myByte; AL = mov ah,[myByte+1]; AH = dec ah; AH = inc al; AL = dec ax; AX = FFh 00h FFh 00h FEFF 20 20 ADD and SUB Instructions ADD destination, source Logic: destination destination + source SUB destination, source Logic: destination destination – source Same operand rules as for the MOV instruction 21 21 ADD and SUB Examples.data var1 DWORD 10000h var2 DWORD 20000h.code; ---EAX--- mov eax,var1; h add eax,var2 ; h add ax,0FFFFh; 0003FFFFh add eax,1; h sub ax,1; 0004FFFFh 22 22 NEG (negate) Instruction.data valB BYTE -1 valW WORD code mov al,valB; AL = -1 neg al; AL = +1 neg valW; valW = Reverses the sign of an operand. Operand can be a register or memory operand. 23 23 Implementing Arithmetic Expressions Rval DWORD ? Xval DWORD 26 Yval DWORD 30 Zval DWORD 40.code mov eax,Xval neg eax ; EAX = -26 mov ebx,Yval sub ebx,Zval ; EBX = -10 add eax,ebx mov Rval,eax ; -36 HLL compilers translate mathematical expressions into assembly language. You can do it also. For example: Rval = -Xval + (Yval – Zval) 24 24 Exercise... mov ebx,Yval neg ebx add ebx,Zval mov eax,Xval sub eax,ebx mov Rval,eax Translate the following expression into assembly language. Do not permit Xval, Yval, or Zval to be modified: Rval = Xval - (-Yval + Zval) Assume that all values are signed doublewords. 25 25 Flags Affected by Arithmetic The ALU has a number of status flags that reflect the outcome of arithmetic (and bitwise) operations –based on the contents of the destination operand Essential flags: –Zero flag – destination equals zero –Sign flag – destination is negative –Carry flag – unsigned value out of range –Overflow flag – signed value out of range The MOV instruction never affects the flags. 26 26 Zero Flag (ZF) mov cx,1 sub cx,1 ; CX = 0, ZF = 1 mov ax,0FFFFh inc ax ; AX = 0, ZF = 1 inc ax ; AX = 1, ZF = 0 Whenever the destination operand equals Zero, the Zero flag is set. A flag is set when it equals 1. A flag is clear when it equals 0. 27 27 Sign Flag (SF) mov cx,0 sub cx,1 ; CX = -1, SF = 1 add cx,2 ; CX = 1, SF = 0 The Sign flag is set when the destination operand is negative. The flag is clear when the destination is positive. The sign flag is a copy of the destination's highest bit: mov al,0 sub al,1 ; AL= b, SF=1 add al,2 ; AL= b, SF=0 28 28 Carry Flag (CF) Addition and CF: copy carry out of MSB to CF Subtraction and CF: copy inverted carry out of MSB to CF INC/DEC do not affect CF Applying NEG to a nonzero operand sets CF 29 29 Exercise... mov ax,00FFh add ax,1; AX= SF= ZF= CF= sub ax,1; AX= SF= ZF= CF= add al,1; AL= SF= ZF= CF= mov bh,6Ch add bh,95h; BH= SF= ZF= CF= mov al,2 sub al,3; AL= SF= ZF= CF= For each of the following marked entries, show the values of the destination operand and the Sign, Zero, and Carry flags: 0100h FFh h h FFh 1 0 1 30 30 Overflow Flag (OF) The Overflow flag is set when the signed result of an operation is invalid or out of range. ; Example 1 mov al,+127 add al,1; OF = 1, AL = ?? ; Example 2 mov al,7Fh; OF = 1, AL = 80h add al,1 The two examples are identical at the binary level because 7Fh equals To determine the value of the destination operand, it is often easier to calculate in hexadecimal. 31 31 A Rule of Thumb When adding two integers, remember that the Overflow flag is only set when... –Two positive operands are added and their sum is negative –Two negative operands are added and their sum is positive What will be the values of OF flag? mov al,80h add al,92h; OF = mov al,-2 add al,+127; OF = 32 32 Signed/Unsigned Integers: Hardware Viewpoint All CPU instructions operate exactly the same on signed and unsigned integers The CPU cannot distinguish between signed and unsigned integers YOU, the programmer, are solely responsible for using the correct data type with each instruction 33 33 Overflow/Carry Flags: Hardware Viewpoint How the ADD instruction modifies OF and CF: –CF = (carry out of the MSB) –OF = (carry out of the MSB) XOR (carry into the MSB) How the SUB instruction modifies OF and CF: –NEG the source and ADD it to the destination –CF = INVERT (carry out of the MSB) –OF = (carry out of the MSB) XOR (carry into the MSB) 34 34 Auxiliary Carry (AC) flag AC indicates a carry or borrow of bit 3 in the destination operand. It is primarily used in binary coded decimal (BCD) arithmetic. mov al, oFh add al, 1; AC = 1 35 35 Parity (PF) flag PF is set when LSB of the destination has an even number of 1 bits. mov al, b add al, b; AL= , PF=1 sub al, b; AL= , PF=0 36 Jump and Loop 37 37 JMP and LOOP Instructions Transfer of control or branch instructions –unconditional –conditional JMP Instruction LOOP Instruction LOOP Example Summing an Integer Array Copying a String 38 38 JMP Instruction top:. jmp top JMP is an unconditional jump to a label that is usually within the same procedure. Syntax: JMP target Logic: EIP target Example: 39 39 LOOP Instruction The LOOP instruction creates a counting loop Syntax: LOOP target Logic: ECX ECX – 1 if ECX != 0, jump to target Implementation: The assembler calculates the distance, in bytes, between the current location and the offset of the target label. It is called the relative offset. The relative offset is added to EIP. 40 40 LOOP Example The following loop calculates the sum of the integers : When LOOP is assembled, the current location = E. Looking at the LOOP machine code, we see that –5 (FBh) is added to the current location, causing a jump to location : E + FB B mov ax, B mov ecx, C1 L1:add ax,cx C E2 FB loop L E offset machine code source code 41 41 Exercise... If the relative offset is encoded in a single byte, (a) what is the largest possible backward jump? (b) what is the largest possible forward jump? (a) 128 (b) +127 Average sizes of machine instructions are about 3 bytes, so a loop might contain, on average, a maximum of 42 instructions! 42 42 Exercise... What will be the final value of AX? mov ax,6 mov ecx,4 L1: inc ax loop L1 How many times will the loop execute? mov ecx,0 X2: inc ax loop X2 10 4,294,967,296 43 43 Nested Loop If you need to code a loop within a loop, you must save the outer loop counter's ECX value. In the following example, the outer loop executes 100 times, and the inner loop 20 times..data count DWORD ?.code mov ecx,100; set outer loop count L1: mov count,ecx; save outer loop count mov ecx,20; set inner loop count L2:... loop L2; repeat the inner loop mov ecx,count; restore outer loop count loop L1; repeat the outer loop 44 44 Summing an Integer Array.data intarray WORD 100h,200h,300h,400h.code mov edi,OFFSET intarray ; address mov ecx,LENGTHOF intarray ; loop counter mov ax,0 ; zero the sum L1: add ax,[edi] ; add an integer add edi,TYPE intarray ; point to next loop L1; repeat until ECX = 0 The following code calculates the sum of an array of 16-bit integers. 45 45 Copying a String.data source BYTE "This is the source string",0 target BYTE SIZEOF source DUP(0),0.code mov esi,0; index register mov ecx,SIZEOF source; loop counter L1: mov al,source[esi]; get char from source mov target[esi],al; store in the target inc esi; move to next char loop L1 ; repeat for entire string good use of SIZEOF The following code copies a string from source to target. 46 Conditional Processing 47 47 Status flags - review The Zero flag is set when the result of an operation equals zero. The Carry flag is set when an instruction generates a result that is too large (or too small) for the destination operand. The Sign flag is set if the destination operand is negative, and it is clear if the destination operand is positive. The Overflow flag is set when an instruction generates an invalid signed result. Less important: –The Parity flag is set when an instruction generates an even number of 1 bits in the low byte of the destination operand. –The Auxiliary Carry flag is set when an operation produces a carry out from bit 3 to bit 4 48 48 NOT instruction Performs a bitwise Boolean NOT operation on a single destination operand Syntax: (no flag affected) NOT destination Example: mov al, b not al NOT 49 49 AND instruction Performs a bitwise Boolean AND operation between each pair of matching bits in two operands Syntax: (O=0,C=0,SZP) AND destination, source Example: mov al, b and al, b AND bit extraction 50 50 OR instruction Performs a bitwise Boolean OR operation between each pair of matching bits in two operands Syntax: (O=0,C=0,SZP) OR destination, source Example: mov dl, b or dl, b OR 51 51 XOR instruction Performs a bitwise Boolean exclusive-OR operation between each pair of matching bits in two operands Syntax: (O=0,C=0,SZP) XOR destination, source Example: mov dl, b xor dl, b XOR XOR is a useful way to invert the bits in an operand and data encryption 52 52 Applications (1 of 4) mov al,'a' ; AL = b and al, b ; AL = b Task: Convert the character in AL to upper case. Solution: Use the AND instruction to clear bit 5. 53 53 Applications (2 of 4) mov al,6 ; AL = b or al, b ; AL = b Task: Convert a binary decimal byte into its equivalent ASCII decimal digit. Solution: Use the OR instruction to set bits 4 and 5. The ASCII digit '6' = b 54 54 Applications (3 of 4) mov ax,wordVal and ax,1 ; low bit set? jz EvenValue ; jump if Zero flag set Task: Jump to a label if an integer is even. Solution: AND the lowest bit with a 1. If the result is Zero, the number was even. 55 55 Applications (4 of 4) or al,al jnz IsNotZero; jump if not zero Task: Jump to a label if the value in AL is not zero. Solution: OR the byte with itself, then use the JNZ (jump if not zero) instruction. ORing any number with itself does not change its value. 56 56 TEST instruction Performs a nondestructive AND operation between each pair of matching bits in two operands No operands are modified, but the flags are affected. Example: jump to a label if either bit 0 or bit 1 in AL is set. test al, b jnz ValueFound Example: jump to a label if neither bit 0 nor bit 1 in AL is set. test al, b jz ValueNotFound 57 57 CMP instruction (1 of 3) Compares the destination operand to the source operand –Nondestructive subtraction of source from destination (destination operand is not changed) Syntax: (OSZCAP) CMP destination, source Example: destination == source mov al,5 cmp al,5; Zero flag set Example: destination < source mov al,4 cmp al,5; Carry flag set 58 58 CMP instruction (2 of 3) Example: destination > source mov al,6 cmp al,5; ZF = 0, CF = 0 (both the Zero and Carry flags are clear) The comparisons shown so far were unsigned. 59 59 CMP instruction (3 of 3) Example: destination > source mov al,5 cmp al,-2; Sign flag == Overflow flag The comparisons shown here are performed with signed integers. Example: destination < source mov al,-1 cmp al,5; Sign flag != Overflow flag 60 60 Conditions unsignedZFCF destination 61 61 Setting and clearing individual flags and al, 0; set Zero or al, 1; clear Zero or al, 80h; set Sign and al, 7Fh; clear Sign stc; set Carry clc; clear Carry mov al, 7Fh inc al; set Overflow or eax, 0; clear Overflow 62 Conditional jumps 63 63 Conditional structures There are no high-level logic structures such as if-then-else, in the IA-32 instruction set. But, you can use combinations of comparisons and jumps to implement any logic structure. First, an operation such as CMP, AND or SUB is executed to modified the CPU flags. Second, a conditional jump instruction tests the flags and changes the execution flow accordingly. CMP AL, 0 JZ L1 : L1: 64 64 J cond instruction A conditional jump instruction branches to a label when specific register or flag conditions are met Jcond destination Four groups: (some are the same) 1.based on specific flag values 2.based on equality between operands 3.based on comparisons of unsigned operands 4.based on comparisons of signed operands 65 65 Jumps based on specific flags 66 66 Jumps based on equality 67 67 Jumps based on unsigned comparisons >≧<≦ 68 68 Jumps based on signed comparisons 69 69 Examples mov Large,bx cmp ax,bx jna Next mov Large,ax Next: Compare unsigned AX to BX, and copy the larger of the two into a variable named Large mov Small,ax cmp bx,ax jnl Next mov Small,bx Next: Compare signed AX to BX, and copy the smaller of the two into a variable named Small 70 70 Examples.date intArray DWORD 7,9,3,4,6,1.code... mov ebx, OFFSET intArray mov ecx, LENGTHOF intArray L1: test DWORD PTR [ebx], 1 jz found add ebx, 4 loop L1... Find the first even number in an array of unsigned integers 71 71 BT (Bit Test) instruction Copies bit n from an operand into the Carry flag Syntax: BT bitBase, n –bitBase may be r/m16 or r/m32 –n may be r16, r32, or imm8 Example: jump to label L1 if bit 9 is set in the AX register: bt AX,9; CF = bit 9 jc L1; jump if Carry BTC bitBase, n: bit test and complement BTR bitBase, n: bit test and reset (clear) BTS bitBase, n: bit test and set 72 Conditional loops 73 73 LOOPZ and LOOPE Syntax: LOOPE destination LOOPZ destination Logic: –ECX ECX – 1 –if ECX != 0 and ZF=1, jump to destination The destination label must be between -128 and +127 bytes from the location of the following instruction Useful when scanning an array for the first element that meets some condition. 74 74 LOOPNZ and LOOPNE Syntax: LOOPNZ destination LOOPNE destination Logic: –ECX ECX – 1; –if ECX != 0 and ZF=0, jump to destination 75 75 LOOPNZ example.data array SWORD -3,-6,-1,-10,10,30,40,4 sentinel SWORD 0.code mov esi,OFFSET array mov ecx,LENGTHOF array next: test WORD PTR [esi],8000h ; test sign bit pushfd; push flags on stack add esi,TYPE array popfd; pop flags from stack loopnz next; continue loop jnz quit; none found sub esi,TYPE array; ESI points to value quit: The following code finds the first positive value in an array: 76 76 Exercise....data array SWORD 50 DUP(?) sentinel SWORD 0FFFFh.code mov esi,OFFSET array mov ecx,LENGTHOF array L1: cmp WORD PTR [esi],0; check for zero quit: Locate the first nonzero value in the array. If none is found, let ESI point to the sentinel value: 77 77 Solution.data array SWORD 50 DUP(?) sentinel SWORD 0FFFFh.code mov esi,OFFSET array mov ecx,LENGTHOF array L1:cmp WORD PTR [esi],0; check for zero pushfd; push flags on stack add esi,TYPE array popfd ; pop flags from stack loope L1; continue loop jz quit; none found sub esi,TYPE array; ESI points to value quit: 78 Conditional structures 79 79 If statements if then else JNE else JMP endif else: endif: CTE C T E 80 80; 81 81 Example Implement the following pseudocode in assembly language. All values are unsigned: cmp ebx,ecx ja next mov eax,5 mov edx,6 next: if( ebx <= ecx ) { eax = 5; edx = 6; } 82 82 Example Implement the following pseudocode in assembly language. All values are 32-bit signed integers: mov eax,var1 cmp eax,var2 jle L1 mov var3,6 mov var4,7 jmp L2 L1: mov var3,10 L2: if( var1 <= var2 ) var3 = 10; else { var3 = 6; var4 = 7; } 83 83 Compound expression with AND When implementing the logical AND operator, consider that HLLs use short-circuit evaluation In the following example, if the first expression is false, the second expression is skipped: if (al > bl) AND (bl > cl) X = 1; 84 84 Compound expression with AND cmp al,bl; first expression... ja L1 jmp next L1: cmp bl,cl; second expression... ja L2 jmp next L2:; both are true mov X,1; set X to 1 next: if (al > bl) AND (bl > cl) X = 1; This is one possible implementation... 85 85 Compound expression with AND cmp al,bl; first expression... jbe next; quit if false cmp bl,cl; second expression... jbe next; quit if false mov X,1; both are true next: But the following implementation uses 29% less code by reversing the first relational operator. We allow the program to "fall through" to the second expression: if (al > bl) AND (bl > cl) X = 1; 86 86 Exercise... Implement the following pseudocode in assembly language. All values are unsigned: cmp ebx,ecx ja next cmp ecx,edx jbe next mov eax,5 mov edx,6 next: if( ebx <= ecx && ecx > edx ) { eax = 5; edx = 6; } (There are multiple correct solutions to this problem.) 87 87 Compound Expression with OR In the following example, if the first expression is true, the second expression is skipped: if (al > bl) OR (bl > cl) X = 1; 88 88 Compound Expression with OR cmp al,bl ; is AL > BL? ja L1 ; yes cmp bl,cl ; no: is BL > CL? jbe next ; no: skip next statement L1:mov X,1 ; set X to 1 next: if (al > bl) OR (bl > cl) X = 1; We can use "fall-through" logic to keep the code as short as possible: 89 89 WHILE Loops while( eax < ebx) eax = eax + 1; A WHILE loop is really an IF statement followed by the body of the loop, followed by an unconditional jump to the top of the loop. Consider the following example: _while: cmp eax,ebx ; check loop condition jae _endwhile ; false? exit loop inc eax ; body of loop jmp _while ; repeat the loop _endwhile: 90 90 Exercise... _while: cmp ebx,val1 ; check loop condition ja _endwhile ; false? exit loop add ebx,5 ; body of loop dec val1 jmp while ; repeat the loop _endwhile: while( ebx <= val1) { ebx = ebx + 5; val1 = val1 - 1 } Implement the following loop, using unsigned 32-bit integers: 91 91 Example: IF statement nested in a loop while(eax < ebx) { eax++; if (ebx==ecx) X=2; else X=3; } _while: cmp eax, ebx jae _endwhile inc eax cmp ebx, ecx jne _else mov X, 2 jmp _while _else: mov X, 3 jmp _while _endwhile: 92 92 Table-driven selection Table-driven selection uses a table lookup to replace a multiway selection structure (switch-case statements in C) Create a table containing lookup values and the offsets of labels or procedures Use a loop to search the table Suited to a large number of comparisons 93 93 Table-driven selection.data CaseTable BYTE 'A'; lookup value DWORD Process_A; address of procedure EntrySize = ($ - CaseTable) BYTE 'B' DWORD Process_B BYTE 'C' DWORD Process_C BYTE 'D' DWORD Process_D NumberOfEntries = ($ - CaseTable) / EntrySize Step 1: create a table containing lookup values and procedure offsets: 94 94 Table-driven selection mov ebx,OFFSET CaseTable ; point EBX to the table mov ecx,NumberOfEntries ; loop counter L1:cmp al,[ebx] ; match found? jne L2 ; no: continue call NEAR PTR [ebx + 1] ; yes: call the procedure jmp L3 ; and exit the loop L2:add ebx,EntrySize ; point to next entry loop L1 ; repeat until ECX = 0 L3: Step 2: Use a loop to search the table. When a match is found, we call the procedure offset stored in the current table entry: required for procedure pointers 95 Shift and rotate 96 96 Shift and Rotate Instructions Logical vs Arithmetic Shifts SHL Instruction SHR Instruction SAL and SAR Instructions ROL Instruction ROR Instruction RCL and RCR Instructions SHLD/SHRD Instructions 97 97 Logical vs arithmetic shifts A logical shift fills the newly created bit position with zero: An arithmetic shift fills the newly created bit position with a copy of the number’s sign bit: 98 98 SHL instruction The SHL (shift left) instruction performs a logical left shift on the destination operand, filling the lowest bit with 0. Operand types: SHL destination,count SHL reg,imm8 SHL mem,imm8 SHL reg,CL SHL mem,CL 99 99 Fast multiplication mov dl,5 shl dl,1 Shifting left 1 bit multiplies a number by 2 mov dl,5 shl dl,2; DL = 20 Shifting left n bits multiplies the operand by 2 n For example, 5 * 2 2 = 20 100 100 n 101 101 102 102 103 103 104 104 105 105 RCR instruction RCR (rotate carry right) shifts each bit to the right Copies the Carry flag to the most significant bit Copies the least significant bit to the Carry flag stc; CF = 1 mov ah,10h; CF,AH = rcr ah,1; CF,AH = 106 106 SHLD instruction Syntax: (shift left double) SHLD destination, source, count Shifts a destination operand a given number of bits to the left The bit positions opened up by the shift are filled by the most significant bits of the source operand The source operand is not affected 107 107 SHLD example.data wval WORD 9BA6h.code mov ax,0AC36h shld wval,ax,4 Shift wval 4 bits to the left and replace its lowest 4 bits with the high 4 bits of AX : Before: After: 108 108 SHRD instruction Syntax: SHRD destination, source, count Shifts a destination operand a given number of bits to the right The bit positions opened up by the shift are filled by the least significant bits of the source operand The source operand is not affected 109 109 SHRD example mov ax,234Bh mov dx,7654h shrd ax,dx,4 Shift AX 4 bits to the right and replace its highest 4 bits with the low 4 bits of DX: Before: After: 110 110 Shift and rotate applications Shifting Multiple Doublewords Binary Multiplication Displaying Binary Bits Isolating a Bit String 111 111 Shifting multiple doublewords Programs sometimes need to shift all bits within an array, as one might when moving a bitmapped graphic image from one screen location to another. The following shifts an array of 3 doublewords 1 bit to the right: shr array[esi + 8],1 ; high dword rcr array[esi + 4],1 ; middle dword, rcr array[esi],1 ; low dword, [esi+8][esi+4][esi] 112 112 Binary multiplication We already know that SHL performs unsigned multiplication efficiently when the multiplier is a power of 2. Factor any binary number into powers of 2. –For example, to multiply EAX * 36, factor 36 into and use the distributive property of multiplication to carry out the operation: EAX * 36 = EAX * (32 + 4) = (EAX * 32)+(EAX * 4) mov eax,123 mov ebx,eax shl eax,5 shl ebx,2 add eax,ebx 113 113 Displaying binary bits Algorithm: Shift MSB into the Carry flag; If CF = 1, append a "1" character to a string; otherwise, append a "0" character. Repeat in a loop, 32 times. mov ecx,32 mov esi,offset buffer L1: shl eax,1 mov BYTE PTR [esi],'0' jnc L2 mov BYTE PTR [esi],'1' L2: inc esi loop L1 114 114 Isolating a bit string The MS-DOS file date field packs the year (relative to 1980), month, and day into 16 bits: 115 115 Isolating a bit string mov al,dh ; make a copy of DX shr al,1 ; shift right 1 bit mov ah,0 ; clear AH to 0 add ax,1980 ; year is relative to 1980 mov year,ax ; save in year mov ax,dx ; make a copy of DX shr ax,5 ; shift right 5 bits and al, b ; clear bits 4-7 mov month,al ; save in month variable mov al,dl ; make a copy of DL and al, b ; clear bits 5-7 mov day,al ; save in day variable 116 Multiplication and division 117 117 MUL instruction The MUL (unsigned multiply) instruction multiplies an 8-, 16-, or 32-bit operand by either AL, AX, or EAX. The instruction formats are: MUL r/m8 MUL r/m16 MUL r/m32 Implied operands: 118 118 MUL examples 100h * 2000h, using 16-bit operands:.data val1 WORD 2000h val2 WORD 100h.code mov ax,val1 mul val2; DX:AX= h, CF=1 The Carry flag indicates whether or not the upper half of the product contains significant digits. mov eax,12345h mov ebx,1000h mul ebx; EDX:EAX= h, CF= h * 1000h, using 32-bit operands: 119 119 IMUL instruction IMUL (signed integer multiply) multiplies an 8-, 16-, or 32-bit signed operand by either AL, AX, or EAX (there are one/two/three operand format) Preserves the sign of the product by sign- extending it into the upper half of the destination register Example: multiply 48 * 4, using 8-bit operands: mov al,48 mov bl,4 imul bl; AX = 00C0h, OF=1 OF=1 because AH is not a sign extension of AL. 120 120: 121 121,EDX=3 122 122 Signed integer division Signed integers must be sign-extended before division takes place –fill high byte/word/doubleword with a copy of the low byte/word/doubleword's sign bit For example, the high byte contains a copy of the sign bit from the low byte: 123 123; -101 (32 bits) cdq; EDX:EAX = FFFFFFFFFFFFFF9Bh ; -101 (64 bits) 124 124 IDIV instruction IDIV (signed divide) performs signed integer division Uses same operands as DIV Example: 8-bit division of –48 by 5 mov al,-48 cbw ; extend AL into AH mov bl,5 idiv bl ; AL = -9, AH = -3 125 125 IDIV examples Example: 32-bit division of –48 by 5 mov eax,-48 cdq ; extend EAX into EDX mov ebx,5 idiv ebx ; EAX = -9, EDX = -3 Example: 16-bit division of –48 by 5 mov ax,-48 cwd; extend AX into DX mov bx,5 idiv bx; AX = -9, DX = -3 126 126 Divide overflow Divide overflow happens when the quotient is too large to fit into the destination. mov ax, 1000h mov bl, 10h div bl It causes a CPU interrupt and halts the program. (divided by zero cause similar results) 127 Arithmetic expressions 128 128 Implementing arithmetic expressions Some good reasons to learn how to implement expressions: –Learn how compilers do it –Test your understanding of MUL, IMUL, DIV, and IDIV –Check for 32-bit overflow Example: var4 = (var1 + var2) * var3 mov eax,var1 add eax,var2 mul var3 jo TooBig; check for overflow mov var4,eax; save product 129 129 Implementing arithmetic expressions Example: eax = (-var1 * var2) + var3 mov eax,var1 neg eax mul var2 jo TooBig; check for overflow add eax,var3 Example: var4 = (var1 * 5) / (var2 – 3) mov eax,var1 ; left side mov ebx,5 mul ebx ; EDX:EAX = product mov ebx,var2 ; right side sub ebx,3 div ebx ; final division mov var4,eax 130 130 Implementing arithmetic expressions Example: var4 = (var1 * -5) / (-var2 % var3); mov eax,var2; begin right side neg eax cdq ; sign-extend dividend idiv var3 ; EDX = remainder mov ebx,edx ; EBX = right side mov eax,-5 ; begin left side imul var1 ; EDX:EAX = left side idiv ebx ; final division mov var4,eax ; quotient Sometimes it's easiest to calculate the right-hand term of an expression first. 131 131 Exercise... mov eax,20 mul ebx div ecx Implement the following expression using signed 32-bit integers: eax = (ebx * 20) / ecx 132 132 Exercise... push ecx push edx push eax; EAX needed later mov eax,ecx mul edx; left side: EDX:EAX pop ecx; saved value of EAX div ecx; EAX = quotient pop edx; restore EDX, ECX pop ecx Implement the following expression using signed 32-bit integers. Save and restore ECX and EDX: eax = (ecx * edx) / eax 133 133 Exercise... mov eax,var1 mov edx,var2 neg edx mul edx; left side: edx:eax mov ecx,var3 sub ecx,ebx div ecx; eax = quotient mov var3,eax Implement the following expression using signed 32-bit integers. Do not modify any variables other than var3: var3 = (var1 * -var2) / (var3 – ebx) 134 Extended addition and subtraction 135 135 136 136 Extended addition example Add two integers of any size Pass pointers to the addends (ESI, EDI) and sum (EBX), ECX indicates the number of doublewords L1: mov eax,[esi] ; get the first integer adc eax,[edi] ; add the second integer pushfd ; save the Carry flag mov [ebx],eax ; store partial sum add esi,4 ; advance all 3 pointers add edi,4 add ebx,4 popfd ; restore the Carry flag loop L1 ; repeat the loop adc word ptr [ebx],0 ; add leftover carry 137 137 Extended addition example.data op1 QWORD 0A2B2A h op2 QWORD h sum DWORD 3 dup(?) ; = C32B0674BB5736.code... mov esi,OFFSET op1; first operand mov edi,OFFSET op2; second operand mov ebx,OFFSET sum; sum operand mov ecx,2 ; number of doublewords call Extended_Add... 138 138 SBB instruction 139 139 Assignment #4 CRC32 checksum unsigned int crc32(const char* data, size_t length) { // standard polynomial in CRC32 const unsigned int POLY = 0xEDB88320; // standard initial value in CRC32 unsigned int reminder = 0xFFFFFFFF; for(size_t i = 0; i < length; i++){ // must be zero extended reminder ^= (unsigned char)data[i]; for(size_t bit = 0; bit < 8; bit++) if(reminder & 0x01) reminder = (reminder >> 1) ^ POLY; else reminder >>= 1; } return reminder ^ 0xFFFFFFFF; } Similar presentations © 2017 SlidePlayer.com Inc.
http://slideplayer.com/slide/4321745/
CC-MAIN-2017-09
refinedweb
5,645
50.5
Tutorial How To Change Metadata in Vue.js with vue-meta. Dynamic metadata was already partially covered in this vue-router tutorial. In this article, you will explore how the vue-meta plugin handles this for you in a concise, logical way while providing you with even more control over your application’s metadata. Prerequisites If you would like to follow along with this article, you will need: - Some familiarity with <head>, <title>, <meta>. - Some familiarity with setting up a Vue.js project. This tutorial was verified with Node v15.8.0, npm v7.5.4, Vue v12.6.11, and vue-meta v2.4.0. Using vue-meta First, to use vue-meta, open your terminal and navigate to your existing Vue project directory. Then, run the following command: - npm install vue-meta@2.4.0 Next, with your code editor, open the main.js file and bootstrap the plugin: import Vue from 'vue' import VueMeta from 'vue-meta' import App from 'App.vue' Vue.use(VueMeta) new Vue({ render: h => h(App), }).$mount('#app') Save your changes and then vue-meta will be available to your application. Integrating with Vue Router If you are using a routing solution like vue-router, then you could bootstrap vue-meta in your router/index.js file: import Vue from 'vue' import Router from 'vue-router' import VueMeta from 'vue-meta' Vue.use(Router) Vue.use(VueMeta) export default new Router({}) Save your changes and then vue-meta and vue-router will be available to your application. Integrating with Server Side Rendering If you are using Server Side Rendering (SSR) you will want to bootstrap vue-meta in a file that runs on both the server and the client before the root Vue instance is mounted. Integrating with Vue Frameworks If you are using a framework that already uses vue-meta, such as NuxtJS, you will not need to bootstrap. Instead, you should refer to the documentation for your chosen framework. Other frameworks that already use vue-meta include Gridsome, Ream, Vue-Storefront, and Factor JS. Customizing Plugin Options vue-meta provides options to customize the plugin’s behavior. NuxtJS takes advantage of this by changing the name of the “ metaInfo” property to “ head”. You can replicate this by bootstrapping vue-meta with a keyName: vue-meta allows you to update the <title> tag on both parent and child components. In your root component, you can define a default title that will appear if a child component lacks one. You can also define a titleTemplate which will be used to display the title from child components. export default { name: 'App', metaInfo: { title: 'Default App Title', titleTemplate: '%s | vue-meta Example App' }, // ... } This titleTemplate will produce the following <title>: Output<title> Default App Title | vue-meta Example App </title> Often you want to include other information to pass to the browser or web crawler such as a page’s charset, description, or viewport. You can even add attributes to the page’s html and head tags. And also inject external scripts. export default { name: 'App', metaInfo: { title: 'Default App Title', titleTemplate: '%s | vue-meta Example App', htmlAttrs: { lang: 'en-US' }, meta: [ { charset: 'utf-8' }, { name: 'description', content: 'An example Vue application with vue-meta.' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' } ] }, // ... } This code will generate the following output: Output<html lang="en-US"> <head> <title>Default App Title | vue-meta Example App</title> <meta charset="utf-8"> <meta name="description" content="'An example Vue application with vue-meta."> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> </html> Make sure to check out the metaInfo properties spec of the vue-meta API documentation for all of the options available. Understanding metaInfo Behavior for Parent and Child Components Child components will recursively merge metadata with their parents. This allows us to update the page’s metadata based on which components are currently mounted. The App component is a parent component with title and titleTemplate defined: <template> <div> <HelloWorld /> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'App', metaInfo: { title: 'Default App Title', titleTemplate: '%s | vue-meta Example App' }, components: { HelloWorld } } </script> The HelloWorld component is a child component of the App component with a title defined: <template> <div>Hello World!</div> </template> <script> export default { name: 'HelloWorld', metaInfo: { title: 'Hello World!' } } </script> This code will generate the following output: Output<title> Hello World! | vue-meta Example App </title> The child component’s title overrides the parent’s title. You could also disable the titleTemplate from a child component like so: export default { name: 'HelloWorld', metaInfo: { title: 'Hello World!', titleTemplate: null } } This code will generate the following output: Output<title> Hello World! </title> If two child components are mounted and both contain metaInfo, the last child to be mounted will be used to populate the page’s metadata. Suppose you created a second child component called HelloWorld2. Modify the App component like the previous example as below: <template> <div> <HelloWorld /> <HelloWorld2 /> </div> </template> <script> } } </script> The HelloWorld2 component is a child component of the App component with a title defined - different from the title defined in the HelloWorld component: <template> <div>Hello World 2!</div> </template> <script> export default { name: 'HelloWorld2', metaInfo: { title: 'Hello World 2!' } } </script> This code will generate the following output: Output<title> Hello World 2! | vue-meta Example App </title> Using multiple Vue instances with vue-meta will result in only the metadata from the last app to be updated! Only duplicate metadata will be overwritten by child components. Other metadata will be concatenated. Enforcing Unique metaInfo Behavior with vmid vue-meta allows you to assign a special property called vmid to your metaInfo so that you can control how it resolves with your component tree. If two sets of metadata have the same vmid, such as a parent and child, they will not merge but instead, the child will override the parent. Here is an example of a parent component with a vmid of “description” and a content of “Parent description”: Parent Component{ metaInfo: { meta: [ { charset: 'utf-8' }, { vmid: 'description', name: 'description', content: 'Parent description.' } ] } } And here is an example of a child component with an identical vmid of “description” and a different content of “Child description”: Child Component{ metaInfo: { meta: [ { vmid: 'description', name: 'description', content: 'Child description.' } ] } } This code will generate the following output: Output<meta charset="utf-8"> <meta data- If a child component shares a vmid with a parent and a metaInfo property is set to null, this property will be removed from the parent. If a child component returns undefined for a metaInfo property vue-meta will fall back to the parent’s property. Conclusion vue-meta is a great solution if you’re looking to take control of and dynamically update your app’s metadata. Make sure to review the official documentation if you’d like to learn more about all the library has to offer. If you’d like to learn more about Vue.js, check out our Vue.js topic page for exercises and programming projects.
https://www.digitalocean.com/community/tutorials/vuejs-vue-meta
CC-MAIN-2021-31
refinedweb
1,181
54.52
The QMapConstIterator class provides an iterator for QMap. More... #include <qmap.h> List of all member functions. In contrast to QMapIterator this class is used to iterate over a const map. It does not allow to modify the values of the map since this would break the const semantics. For more informations on QMap iterators see QMapIterator. See also QMap and QMapIterator. Constructs an uninitialized iterator. Constructs an iterator starting at node p. Constructs a copy of the iterator. Constructs a copy of the iterator. Returns a const reference to the data of the current item. Returns a const reference to the current key. Compares both iterators and returns TRUE if they point to different items. Asterix operator. Returns a const reference to the current item. The same as data(). Compares both iterators and returns TRUE if they point to the same item. Search the documentation, FAQ, qt-interest archive and more (uses): This file is part of the Qt toolkit, copyright © 1995-2005 Trolltech, all rights reserved.
https://doc.qt.io/archives/2.3/qmapconstiterator.html
CC-MAIN-2021-21
refinedweb
168
61.63
Defining a 2D vector in C++ Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site Reading time: 30 minutes | Coding time: 10 minutes In this article, we have explored the different ways of defining a 2D vector in C++. Before getting in the nitty-gritty of 2-D vectors, let us first define some working definitions of basic terms: - Containers - These can be understood as implementation of abstract data types and as such are data structures available for use. e.g. arrays, set, map etc. - Vectors - Vectors are containers which implement dynamic arrays or arrays which can change size according to our needs. A 2-D vector is a vector of vectors. For e.g. you can define a two-dimensional vector of type T as follows: std::vector<std::vector<T>> vector_name; Note: All the examples given ahead are for type int but they can easily be replicated for other types such as double, char etc. just by changing int in declaration to the required type. Note:You can create a 2D array by doing int a[4][3], but std::vector<int> a(4,3) won't create a 2D vector - it will create a 4-element vector full of 3s. Syntax of defining 2-D vector Initializing at the time of declaration: std::vector<std::vector<int>> vect{{ 5, 6, 3 }, { 1, 2, 4 }}; Note: Languages like Java and C# allow for jagged arrays or 2-D arrays with variable columns in each row. In C++, we can achieve this by using 2-D vector as follows: std::vector<std::vector<int>> vect{{ 5, 7, 12 }, { 8, 5 }, { 7, 8, 9, 0 }}; Initializing a 2-D vector with help of 1-D vector std::vector<int> va(3, 1); // vector a {1, 1, 1} std::vector<int> vb(3, 2); // vector b {2, 2, 2} std::vector<int> vc(3, 3); // vector c {3, 3, 3} std::vector<std::vector<int>> vect {va, vb, vc}; Initializing a 2-D vector of n rows and m columns std::vector<std::vector<int>> vect( n , std::vector<int> (m)); Note: You can initialize the above vector with value k in each cell by using the following code: std::vector<std::vector<int>>vect( n , std::vector<int>(m,k)); Applications The applications of 2-D vectors are same as 2-D matrices even more as it is more versatile as we can add and delete rows according to our needs. Some uses are: - To represent images and manipulate them - To represent any 2-D grid - Used in programming techniques like Dynamic Programming Exercise Problem Write a program that takes input the no. of rows and the no. of columns in each row and outputs a 2-D vector giving output as in the following examples: Input: No. of rows = 4 No. of columns in rows = 5 2 4 1 Output: 1 2 3 4 5 1 2 1 2 3 4 1 Input: No. of rows = 3 No. of columns in rows = 5 6 1 Output: 1 2 3 4 5 1 2 3 4 5 6 1 Explanation of SolutionTo solve this problem, we need to form a 2-D vector whose rows contains natural numbers starting from 1 to the no. of columns in that row. Also as we know that a 2-D vector is a vector of vectors. So we must first make a 2-D vector (named matrix here) using the following line: std::vector <std::vector<int>> matrix; Then we will push required rows in it by first forming vector representing each row one by one and then pushing them in the 2-D vector. In the final step we print the 2-D vector. Note: This problem can be solved by various methods like an array whose each cell points to a linked list but here we are demonstrating 2-D vectors. You are free to experiment and be creative in coming up with various approaches. Solution #include <iostream> #include <vector> int main(){ //inputting the no. of rows in required 2-D matrix int rows; std::cout<<"No. of rows = "; std::cin>>rows; std::vector<int> columns; std::cout<<"No. of columns in rows = "; int temp; //inputting the no. of columns in (i+1)th row //and storing it in a vector for(int i=0;i<rows;++i){ std::cin>>temp; columns.push_back(temp); } //defining the 2-D vector std::vector <std::vector<int>> matrix; for(int i=0;i<rows;++i){ //defining a temporary vector std::vector <int> tempvect; //filling temporary vector with required //values for (i+1)th row from top for(int j=0;j<columns[i];++j){ tempvect.push_back(j+1); } //saving the created row in matrix matrix.push_back(tempvect); } //printing the matrix for(int i=0;i<matrix.size();++i){ //printing the (i+1)th row(or vector) from top for(int j=0;j<matrix[i].size();++j){ std::cout<<matrix[i][j]<<" "; } std::cout<<"\n"; } return 0; } Time Complexity - Worst case time complexity: O(N) - Average case time complexity: Θ(N) - Best case time complexity: Ω(N) - Space complexity: Θ(N) where N is the summation of all columns. With this article at OpenGenus, you must have the complete idea of defining a 2D vector in C++. Enjoy.
https://iq.opengenus.org/define-2d-vector-in-cpp/
CC-MAIN-2021-17
refinedweb
902
57.91
I have a SortedDictionary whose value is a List of objects. I want to sort the value(the list) of each key by a given property of the object. In the current situation, I need to sort the list first by objects's lastname, then by firstname. I tried LINQ and it got nasty pretty fast without producing the result. EDIT: I have the following structure: public class Person { private string firstName; private string lastName; ... } I need the dictionary sorted by the key. However, I need every List to be sorted first by Person's lastName, then by firstName. var dict = new SortedDictionary<string, List<Person>>(); I didn't provide code for the sorting because i can't get it to work. That's why I seek help.
http://www.howtobuildsoftware.com/index.php/how-do/djs/c-linq-sorting-dictionary-sorting-a-dictionary-value-which-is-a-list-of-objects-by-given-fields
CC-MAIN-2019-39
refinedweb
128
74.9
Thanks to a line of code kindly given to me by forum user "dodicat" , this line : screenres W,H,,, &h08 '&h08 is no frame (see fbgfx.bi in the inc folder) I got spurred into checking up and try to to learn more about ScreenRes . So I played around a little with a few lines of code , read some manual and also in the end also peeked into the fbgfx.bi in the inc folder of FreeBasic on my harddrive. So I have two questions in that connection , first question : This code will create a frame less window Code: Select all dim as integer W,H screeninfo W,H screenres W-200,H-200,,, &h08 Sleep So my question would be is there anyway to control where on my screen that the window is generated ? The window is generated centered mid-screen on my "monitor" and question is if I can move the point of generation of the generated Window up,down,right and left ? ------------------------------------------------ Second question : This code compiles without problems : Code: Select all dim as integer W,H screeninfo W,H screenres W,H,,, &h08 but if I change the &h08 with GFX_NO_FRAME then not only do I have to #include "fbgfx.bi" but state a Using FB : Code: Select all #include "fbgfx.bi" Using FB dim as integer W,H screeninfo W,H screenres W,H,,, GFX_NO_FRAME So let me see if I got it right (?) : The GFX_NO_FRAME is defined in the FB 'namespace and then because the GFX_NO_FRAME is used then compiler have to fetch info from the fbgfx.bi ? Further more , from studying the manual section for ScreenRes then I have seen that the &h08 must be a flag that is referred to by flag name GFX_NO_FRAME , which makes me think that the &h08 must be some internal reference or something for compiler since it do not require any include or namespace reference (?) So then my question is : But then where are the list of other stuff like &h08 and the proper description (I mean apart from what is listed in and related to the fbgfx.bi ) ???
https://www.freebasic.net/forum/viewtopic.php?f=2&t=25958&p=236578
CC-MAIN-2019-30
refinedweb
352
68.84
On Thu, Aug 1, 2013 at 10:00 AM, Nick Coghlan <ncoghlan at gmail.com> wrote: > On 1 August 2013 23:18, Brett Cannon <brett at python.org> wrote: > >> I see 2 as the best one. Is it really too late to change the return > type > >> of FileFinder.find_loader()? If we simply can't bear the backward > >> compatibility risk (no matter how small <wink>), > > > > We unfortunately can't. It would require a new method which as a stub > would > > call the old API to return the proper object (which is fine if you can > come > > up with a reasonable name). > > Just musing on this one for a bit. > > 1. We still have the silliness where we call "find_module" on metapath > importers to ask them for a loader. > 2. We have defined an inflexible signature for find_loader on path > entry finders (oops) > 3. There's other interesting metadata finders could expose *without* > loading the module > > So, how does this sound: add a new API called "find_module_info" for > both metapath importers and path entry finders (falling back to the > legacy APIs). This would return a simple namespace potentially > providing the following pieces of information, using the same rules as > the corresponding loader does for setting the module attributes > (): > > __loader__ > __name__ > __package__ > __path__ > __file__ > __cached__ > __indirect__ > > (We could also lose the double underscores for the namespace > attributes, but I quite like the symmetry of keeping them) > > Thoughts? If you're going to do that, why stop at types.SimpleNamespace and not move all the way to a module object? Then you can simply start moving to APIs which take the module object to be operated on and the various methods in the loader, etc. and just fill in details as necessary; that's what I would do if I got to redesign the loader API today since it would simplify load_module() and almost everything would just become a static method which set the attribute on the module (e.g. ExecutionLoader.get_filename('some.module') would become ExecutionLoader.filename(module) or even ExecutionLoader.__file__(module) which gets really meta as you can then have a decorator which checks for a non-None value for that attribute on the module and then returns it as a short-circuit instead of calling the method). Only drawback I see is it not being easy to tell if a module has been initialized or not, but I don't view that as a critical issue. IOW introduce new_module()/fresh_module(). Even if types.SimpleNamespace is kept I do like the idea. Loaders could shift to working only off of the object and have their __init__ method standardized to take a single argument so what import is told about and what loaders work with is the same. Basically it becomes a caching mechanism of what finders can infer so that loaders can save themselves the hassle without complicated init call signatures. -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/import-sig/2013-August/000660.html
CC-MAIN-2014-10
refinedweb
488
61.06
Opened 7 months ago Last modified 5 days ago #14391 patch task Make the simplifier independent of the typechecker Description (last modified by ) I noticed that the simplifier module depends on all of the type checker, and HsSyn stuff, and renamer stuff, which I found strange. After a little investigation, it seems that the simplifier depends on CoreMonad, and that pulls some very few type-checker related things: import TcRnMonad ( initTcForLookup ) import {-# SOURCE #-} TcSplice ( lookupThName_maybe ) forthinstance… Simon says: Both of these code paths go through initTcForLookup which is massive overkill, as the comment with TcEnv.lookupGlobalsays. There's clearly a ToDo here to strip off the redundant stuff and do a minimal lookup. I am optimistically marking this as newcomer because it is a refactoring task, and a good way of learning a bit about various pieces, with a reasonably clear notion of “success”. UPDATE (April 2018, Phab:4503): both points described above are addressed to the extent when in order to close the ticket we need to do mere code movement. Namely. lookupThName_maybeand initTcForLookupare eliminated from CoreMonad.hscompletely.)”. CoreMonad.hsstill calls lookupGlobalwhich is no longer bound to the typechecker monad, but still resides in TcEnv.hs— it should be moved out of Tc-land at some point in the future in order to close the ticket. Change History (26) comment:1 Changed 6 months ago by comment:2 Changed 6 months ago by Great! Do let us know if you encounter trouble. comment:3 Changed 6 months ago by Great. I suggest you start with TcEnv.lookupGlobal. - It invokes initTcForLookup(massive overkill) in order to call tcLookupGlobal. We need a versionn of this function that operates in the IO monad, not the TcMmonad. - What does tcLookupGlobalget from the TcMmonad? It'll need to get these things as explicit arguments instead, I guess. For example: consults the tcg_type_env, which was initialised by initTcForLookup. And it uses tcg_semantic_modlikewise. - Then it hands off to LoadIface.tcLookupImported_maybe. That does a bit more IO-ish things before finally deciding to load a new interface decl in tcImportDecl_maybe. tcImportDecl_maybeuses initIfaceTcRnto make an IfMmoand in which to do the loading work. But instesad you can make an IfMfrom scratch, by writing a variant of initIfaceTcRn. Nothing really hard here, but you'll need to carefully tease out what dependencies are where. (The lack of explicit dependencies is, of course, both the blessing and the curse of monadic progrmaming.) Happy to help. comment:4 Changed 6 months ago by Alrighty! First question while I investigate more into performing a minimal lookup instead of using initTcForLookup. (Bear with me, I'm writing some of this out as I understand it myself) We want to refactor thNameToGhcName to no longer be a part of CoreMonad and instead exist in a module to be pulled by GhcPlugins.hs. Do correct me if I'm wrong, but creating a singleton module with just thNameToGhcName in it seems like a naive approach. Is there an existing module that is pulled in by GhcPlugins.hsthat would be an appropriate home for thNameToGhcName? Or should a new one simply be created? comment:5 follow-up: 6 Changed 6 months ago by I suggest you start with TcEnv.lookupGlobal. Doing this will avoid you getting sucked into template haskell stuff right away. We can come back to your question when this is done. comment:6 Changed 6 months ago by Gotcha. Thank you for the guidance! comment:7 Changed 3 months ago by As it seems to stale for a while, I'd like to give it a try. IIUC, the strategy laid by Simon suggests developing a Tc-less version of lookupGlobal. For this we need to identify ties to Tc inside it and then try to cut those. First tie (also spelled by Simon above) is “ tcg_type_env, which was initialised by initTcForLookup”. I looked at initTcForLookup and its dependencies, and it seems to me that tcg_type_envis initialized with emptyNameEnv there. A question: does that mean that corresponding part of the tcLookupGlobal which queries tcg_type_env is not needed at all and can be omitted in the Tc-less version of lookupGlobal? comment:8 Changed 3 months ago by does that mean that corresponding part of the tcLookupGlobal which queries tcg_type_env is not needed at all and can be omitted Yes I think so. comment:9 Changed 3 months ago by One more question. Consider a part of tcImportDecl_maybe: initIfaceTcRn (importDecl name) You said that it is necessary to create a variant of initIfaceTcRn. That sounds fine. But here is another thing: importDecl has IfM in its type. And IfM is defined in TcRnTypes, so leaving it doesn't bring us decoupling from the typechecker. Should we also replace importDecl? This sounds like some more work, because it depends on loadInterface which is >100 LOCs. comment:10 Changed 2 months ago by Ok, after some more thinking it seems to me that importing just TcRnTypes is not big deal. Now I'm wondering if it is legit to deal with initIfaceTcRn by just repalacing it with TcRnMonad.initIfaceLoad. If so, do we need to move it to some less Tc-heavy place? comment:11 Changed 2 months ago by importDecl has IfM in its type. And IfM is defined in TcRnTypes, so leaving it doesn't bring us decoupling from the typechecker. Should we also replace importDecl? No, leave all that. The point is as follows (please document this in your patch): TcEnv.lookupGlobalmay look up an Idthat one one has previously looked up. - If so, we are going to read its interface file, and add its bindings to the ExternalPackageTable, which is a persistent in-memory cache of information about other modules. - Loading that interface file does quite a bit of work, but we don't consider that as "part of the typechecker"; it's essentially just de-serialising interface-file data on disk. For example, any failures are not user errors; they represent messed-up files or GHC bugs, so can legitimately raise an exception. - The entire mechanism of importDecland loadInterfaceis part of this. Don't duplicate it! comment:12 Changed 2 months ago by I'm wondering if it is legit to deal with initIfaceTcRn by just repalacing it with TcRnMonad.initIfaceLoad Yes that sounds just right. If so, do we need to move it to some less Tc-heavy place? We might indeed want to do this. But you might want to keep the moving-code-around work in a separate patch, lest the diffs from that refactoring obscure the main payload comment:13 Changed 2 months ago by I have one more question about tcLookupGlobal (hope the last one for it). Here its part: if nameIsLocalOrFrom (tcg_semantic_mod env) name then notFound name -- Internal names can happen in GHCi else I have trouble with notFound part which essentially does careful error-reporting inside Tc monad. I'm lost on how to port this to IO with the same amount of precision. So far I come up with dumb solution (to be placed in the then branch): pprPanic "lookupGlobal" (ppr name) It is probably not good enough. Or is it? comment:14 Changed 2 months ago by So far I've replaced error-reporting for TcM ( notFound, failWithTc) with pprPanic. Now I have full version of lookupGlobal in IO (link). It doesn't seem to break any test (besides already broken ones). Should I submit it to the Phabricator or proceed with the second part pointed out by Joachim, thNameToGhcName? comment:15 Changed 2 months ago by Actually, I don't see thNameToGhcName used anywhere (on master). So it could be (relatively) freely moved. Maybe TcSplice, which it depends upon, is the right place for it? In that case the return type's monad, probably, should be changed from CoreM to plain IO. comment:16 Changed 2 months ago by thNameToGhcName is useful for GHC plugins, so any module reexported by GhcPlugins (or maybe even that module itself) is a good place. comment:17 Changed 2 months ago by comment:18 Changed 2 months ago by comment:19 Changed 2 months ago by comment:20 Changed 2 months ago by Let's turn to thNameToGhcName now. We want to remove initTcForLookup from it, and for this we need to replace lookupThName_maybe with Tc-less version. The lookupThName_maybe, in turn, depends on lookupGlobalOccRn_maybe which seems to be very Rn-heavy inside. So I'm not sure how to proceed: should I try to rewrite lookupGlobalOccRn_maybe or leave it. In the latter case we need to find a way to run RnM in thNameToGhcName, which, I guess, not far from the dreaded initTcForLookup? comment:21 Changed 2 months ago by Well, initTcForLookupinitialises the tcg_rdr_envto emptyGlobalRdrEnv, and tcl_rdrto emptyLocalRdrEnv. - So in lookupThName_maybe, the lookupLocalRdrEnvis guaranteed to faile; and in lookupGlobalOccRn_maybeonly the lookupExactOrOrigstuff can succeed. - For lookupOrigwe are simply looking in the OrigNameCache, which is available in CoreM. - I think lookupExactis even easier, because I think the name must be an External name. Maybe that can help you get further comment:22 Changed 8 weeks ago by This makes a lot sense, thanks! I've started doing this. For the other, simpler part of the refactoring, namely, the module canocalization thing, I've submitted update to the Phab. I'm not sure where to put that refactored function though. comment:23 Changed 8 weeks ago by Done with TH part closely following your directions. See Phab. comment:24 Changed 3 weeks ago by comment:25 Changed 3 weeks ago by comment:26 Changed 5 days ago by In bb3fa2d1/ghc: Hello. Am newcomer. I'd love to take a stab at this! Will start hacking away.
https://ghc.haskell.org/trac/ghc/ticket/14391
CC-MAIN-2018-22
refinedweb
1,610
64.41
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages. pichukov/LightChart LightChart is a lightweight SwiftUI package with line charts implementation. You can use it when you need only a chart that will perfectly fit into your View. It doesn't have any interaction, titles, different types of diagram or anything else, just a representation of your data set. Currently LightChart have only line type of chart with sharp corners or a curved one. That's how it looks in the real application on currency exchange rates example: Installation It's a Swift Package, so you need to do the following: - Open Filein Xcode menu - Open Swift Packages - Choose Add Package Dependency...option - In the Enter package repository URLfield paste this URL: - Choose any existing version or a masterbranch option Usage Add import LightChart Add LightChartView into your SwiftUI code LightChartView(data: [4, 8, 12, 10, 25]) By default it will draw a red line chart: To customize it you can use several properties: type The type of chart, it's an enum with two cases: .lineis a default type that will draw a chart presented above .curvedwill draw a curved chart, for example: LightChartView(data: [2, 17, 9, 23, 10], type: .curved) visualType The visual part of the chart. An enum with three cases: .outline(color: Color, lineWidth: CGFloat)to specify a colorand lineWidthfor stroke LightChartView(data: [2, 17, 9, 23, 10], type: .curved, visualType: .outline(color: .green, lineWidth: 5)) .filled(color: Color, lineWidth: CGFloat)use stroke color to fill the chart with a gradient LightChartView(data: [2, 17, 9, 23, 10], type: .curved, visualType: .filled(color: .green, lineWidth: 5)) .customFilled(color: Color, lineWidth: CGFloat, fillGradient: LinearGradient)also provides an option to change the fill gradient LightChartView(data: [2, 17, 9, 23, 10], type: .curved, visualType: .customFilled(color: .red, lineWidth: 3, fillGradient: LinearGradient( gradient: .init(colors: [Color.orange.opacity(0.7), Color.orange.opacity(0.1)]), startPoint: .init(x: 0.5, y: 1), endPoint: .init(x: 0.5, y: 0) ))) offset By default the offset is 0 and it means that the chart takes up the entire area of the parent view. You can move the chart line up with changing the offset value. For example if you will use the offset: 0.2 you chart line will move up and take only 80% of the parent view LightChartView(data: [2, 17, 9, 23, 10], type: .curved, visualType: .filled(color: .green, lineWidth: 3), offset: 0.2) currentValueLineType There is an option to add a horizontal line that will point the last value of the data set. A currentValueLineType is an enum that has three cases: .noneis a default value that doesn't show any line .line(color: Color, lineWidth: CGFloat)adds a line with colorand lineWidthfor a stroke LightChartView(data: [2, 17, 9, 23, 10], type: .curved, visualType: .filled(color: .green, lineWidth: 3), offset: 0.2, currentValueLineType: .line(color: .gray, lineWidth: 1)) .dash(color: Color, lineWidth: CGFloat, dash: [CGFloat])adds a dashed line LightChartView(data: [2, 17, 9, 23, 10], type: .curved, visualType: .filled(color: .green, lineWidth: 3), offset: 0.2, currentValueLineType: .dash(color: .gray, lineWidth: 1, dash: [5]))
https://swiftpack.co/package/pichukov/LightChart
CC-MAIN-2021-10
refinedweb
524
64.91
A Complete Guide to Specflow and Behavior Driven Development (BDD) Tutorial: What is Specflow? Specflow is a testing framework supporting BDD practices in .NET framework. It’s an open source framework hosted on GitHub. It aids in using ATDD (Acceptance test driver development) for .NET Applications. With this, we can define scenario in plain English defined by Gherkin language that is clearly understandable by anyone. There are various tools for writing tests in the BDD approach like Cucumber/JBehave for Java, Lettuce for Python, Jasmine for Javascript, Specflow for .NET. BDD (Behavior Driven Development) is a set of practices or an approach similar to TDD (Test Driven Development), which aims to bridge the communication gap between different stakeholders like Product, Developers, and Testers. The end goal of the BDD approach is to create business requirements that could be understood by the entire team so as to avoid misunderstandings, and helps to ship the feature being developed in the most acceptable way. A Complete Specflow Tutorial Series: Read through the Complete Specflow Training Series for better understanding of the concept. Tutorial #1: Introduction to Specflow BDD Tool (This Tutorial) Tutorial #2: Specflow and Selenium Example Tutorial #3: Specflow Binding & Advanced Concepts Tutorial #4: Step Argument Transformations & Specflow Tables Tutorial #5: Specflow Living Documentation with Pickles Tutorial #6: Specflow Report Generator Tutorial #7: Specflow Interview questions A Brief Overview of Tutorials in the Specflow Series: Let's start with the first tutorial in this series. What You Will Learn: Introduction to Specflow BDD Tool Watch the Video Tutorial: Here is a video tutorial on Specflow and Behavior Driven Development: Features of BDD The key features of BDD are briefed below: #1) It tries to define the behavior of the system or feature being developed through an example or scenario. For instance, if you are building a simple Calculator Application then the different behaviors include addition, multiplication, division, etc. Hence through BDD, all the stakeholders will first meet to decide the behavior of the application like Addition and will have scenarios as shown below. Given, I have 2 numbers 30 and 50 as input When I add these 2 numbers Then I should get an output of 80 If you see the above representation it’s a scenario in plain English that is clearly understandable by anyone and makes the requirements for a feature clear (as per the acceptance criteria). Hence the first step is to articulate these requirements. #2) Now with a set of these scenarios, the QA writes tests against these and this will initially fail as the feature is not yet developed. #3) Now, the developer writes a feature code and executes these tests again. #4) The tests may pass or fail. If they fail – refactor code and repeat the process #5) Once code refactoring is complete all the scenarios/tests should pass. Hence, in essence, BDD uses TDD approach and takes it to the next level by having some common easily understandable specifications in the form of scenarios. They also represent the feature documentation in itself. There are various tools for writing tests in the BDD approach like Cucumber/JBehave for Java, Lettuce for Python, Jasmine for Javascript, Specflow for .NET. In this tutorial, we will be focusing on Specflow. Also Read => Top BDD Tools and Testing Framework The Keywords – Given, When & Then From the unit testing world, most of us are familiar with 3 A’s i.e. Arrange, Act and Assert. Now, Given, When and Then are the replacements for these in the BDD world. Let’s take an Example for understanding each of these. Suppose you are listing down a scenario for validating a product that gets added to the shopping cart of an e-commerce application which requires you to be logged in as a pre-requisite. The specification can be written as follows: Scenario: Products get added to cart for a logged in customer Given I have a logged-in customer on my application When I add 2 quantity of a product to my shopping cart Then the shopping cart should get updated and have the right product and quantity Given: This is used for describing a set of pre-conditions for the scenario being defined. For instance, in the example, the scenario’s pre-requisite is a logged-in customer. Hence comparing to the Arrange analogy in a unit test, the step implementation will need to ensure that there is a logged in customer. When: This is used to describe an action or execution step. In the example, it shows that the customer is trying to add a product to his shopping cart. Hence the step implementation for this step will take care of the simulation code to add a product to the cart. This can be compared to the Act step in the Unit tests. Then: This is used to describe the Outcome of the scenario and essentially where the validations should be placed in. It can be compared to the Assert step in the Unit testing world. In the example here, the step implementation will assert whether the product got actually added and the quantity is the same as that was chosen by the customer. The Feature File The feature file is essentially a grouping of multiple scenarios for the application under development or test. It can also be simply thought of as different modules of the application by which the application can be logically separated. For Example: An e-commerce application can decide to have different high-level feature files like: - Login/Logout functionality - Shopping Cart - Payment etc. What is Specflow? Specflow is a tool supporting BDD practices in .NET framework. It’s an open source framework hosted on GitHub. It aids in using ATDD (Acceptance test driver development) for .NET Applications. Binding business requirements for an application using Specification By Example paradigm helps in a better understanding of the application behavior by all the stakeholders and thereby results in shipping the product with correct expectations. It makes use of Gherkin syntax for creating features & scenarios. It also has an active discussion/developer forum. Specflow – Getting Started In this section, we will explore installing specflow in the Visual Studio IDE and creating feature files for a simple String Utility Application. About Sample Application We will be illustrating different features of the Specflow framework in this tutorial using a Calculator Application which has functions/interfaces to provide different operations like: - Adding 2 numbers. - Subtracting 2 numbers. - Dividing and Multiplying 2 numbers. - Finding the Square root of the given number. Specflow Installation Guide Specflow installation is a 2 step process #1) Installing the required plugins in the Visual Studio IDE. - To install the specflow plugin navigate to Tools -> Extension & Updates. - Now click “Online” on the left panel. - Now search for specflow in the right panel. - From the search results select “Specflow for Visual Studio 2017”. #2) Setting up the project with feature files and step definitions. - Create a simple new project in Visual Studio. We can create any kind of project like Class Library / Console Application / Unit test project etc. For simplicity, we are taking up a Class Library project. Name the project as “SpecflowBasic”. - In order to run the Specflow scenarios that we are going to create, we need a test runner. Specflow provides a runner out of the box called Specflow + Runner (which is a paid version and the free version introduces a delay). (Other runners are also available for NUnit and MsTest which we will see in the further articles in this series). To install Specflow + Runner – Navigate to Tools -> NuGet Package Manager -> Package Manager Console. Once the Package Manager Console opens up – Run the command. Install-Package SpecRun.SpecFlow - Also, in order to Assert the values, we will need the help of a test framework. NUnit can be one of the options and the others include MsTest, etc. To install the NUnit framework to the application, open the Package Manager Console and type command. Install-Package NUnit #3) Create a new class named “CalculatorApplication” which will become our application under test. This is a simple class having functions to perform addition/multiplication/division/square root etc., for the given input. This is how the CalculatorApplication class looks like. #4) Once the package gets installed, create 2 folders in the project and name them as Features and Step Definitions for storing the feature files and step bindings respectively. We will discuss in detail the reason for this folder organization for Feature & Step definitions. #5) Now in the features folder, add a new Feature file and name it as CalculatorFeature. You would see that by default the feature file has some description in Feature and Scenario. Replace that with what we are going to test. Feature: CalculatorFeature In order to test my application As a developer I want to validate different operations of the application Scenario: Add two numbers Given I have provided 70 and 20 as the inputs When I press add Then the result should be 90 Scenario: Substract two numbers Given I have provided 70 and 20 as the inputs When I press substract Then the result should be 50 Scenario: Multiply two numbers Given I have provided 70 and 20 as the inputs When I press multiply Then the result should be 1400 Scenario: Divide two numbers Given I have provided 70 and 20 as the inputs When I press divide Then the result should be 3.5 Scenario: SquareRoot of number Given I have provided 70 as input When I press squareroot Then the result should be 8.37 #6) Generating Step Definitions: Specflow provides an automated way to generate bindings/implementation for the different steps in feature file scenarios. This can be achieved by right-clicking on the feature file and clicking “Generate Step Definitions”. This step does not guarantee an implementation for all the steps, but it tries its best to group the common steps in scenarios and re-use as many bindings it can. However, it makes the job of avoiding boilerplate code every time when a scenario step needs to be implemented. After clicking “Generate Step Definitions”, A window will show up listing the identified step implementations that the processor has detected. One can select or de-select as per the requirements. In the later sections, we will look into more details about the Style dropdown shown in the above screenshot. For now, let’s keep all of them selected with default settings. Clicking on the Preview will show a snapshot of how the implementation will look like. After creating Step definitions, still, if there are some unimplemented steps, the Feature files have a visual way of identifying the un-implemented applications. It shows those steps in a different color by making it absolutely simple to know that there are some steps which don’t have an implementation yet (or are having any ambiguous step definitions). A Sample Screen Depicts that Below: Note: The Step definitions can be created manually as well – Any .cs file having [Binding] Attribute is a Step implementation class and the Gherkin syntax will look for matching the implementation of the given scenario step Execution As we have already added Specflow+ Runner in the above section, executing the Scenarios is pretty straightforward (since it’s an evaluation version of Specrun, it introduces a variable delay of 10-20s before the scenarios execute. , This delay is not present for registered variants and other flavors of Specrun runner like NUnit and MsTest). If all the steps have not been implemented and if there are still bindings that have a pending state. Then the output will show as pending. Let’s try to run these tests/scenarios at this point when there is no implementation for the bindings, and the scenarios are all pending. Now let’s try to implement the CalculatorApplication class with the methods that we want to test i.e. add, subtract, multiply, divide and sqrt. Given below is a code sample of how our CalculatorApplication class looks like:; } } } Once the application is ready, let’s try to figure out the ways to implement the bindings for each of the scenario steps. Let’s see the step by step approach to implement these: - First, we need to have an instance of the application that needs to be tested. For simplicity, we can instantiate the AUT (Application Under Test class) in step bindings and use the instantiated instance to actually call different methods/functions as per the step that’s implemented. - To capture the input and output we are declaring variables to hold these values in order to call functions on the Application instance. Let’s see the end to end implementation for all the bindings involved in validating the Add functionality (Rest of the scenarios are simply extending this). The Add scenario looks as shown below: Scenario: Add two numbers Given I have provided 70 and 20 as the inputs When I press add Then the result should Let’s see the step implementation for each of these individual steps. For use of all the step implementations, we are declaring an instance of Application under test as well as variables to hold input and output variables as shown below: // instantiating application instance CalculatorApplication app = new CalculatorApplication(); // variables to hold input values and the intermeditate result int input1, input2; double output; Let’s see the implementation of scenario steps one by one. Step 1: Given I have provided 70 and 20 as the inputs. [Given(@"I have provided (.*) and (.*) as the inputs")] public void GivenIHaveProvidedAndAsTheInputs(int p0, int p1) { input1 = p0; input2 = p1; } Here, we have just initialized the input variables with the values passed in from the scenario steps. p0 and p1 are the values that are passed in from the scenario step and will be initialized as 70 & 20 respectively. Step 2: When I press add. [When(@"I press add")] public void WhenIPressAdd() { output = app.add(input1, input2); } This is the Execution (or Act) step where the actual method is called on the Application under test. Notice that since the input variables input1 and input2 already contain the values passed in Step1 the application instance can call the method with these variables. Step 3: – Then the result should be 90. [Then(@"the result should be (.*)")] public void ThenTheResultShouldBe(double p0) { Assert.AreEqual(p0, output); } This is the Validation (or Assert) step where the output is generated by the method call on and the Application instance is validated against the expected output. Notice, that the Assert keyword used is from NUnit Framework, which returns true or false depending on the validation/expectation that is set. In case it returns false, it will cause the Step implementation to fail and that will show the scenario result as fail. Also, please note that the output variable gets the value from the previous step where the actual method was called on the application instance. Similar to the above, Step implementations for rest of the scenario steps are performed in the same way, the difference is in calling different methods on the application instance and asserting different output values. Once all the Scenario steps are implemented, the tests can be executed. The resultant output will look as shown below: You can also view the output of the individual scenario which lists down the output of individual steps as well: Conclusion Hope this article would have given you a basic understanding of what BDD is and what are the tools that support BDD for .NET where we covered Specflow. We also discussed installing and executing Specflow feature files with the help of a sample application. Code Files The code files used in the application are shown below: CalculatorFeatureSteps.cs using System; using TechTalk.SpecFlow; using NUnit; using NUnit.Framework; namespace SpecflowBasic.StepDefinitions { [Binding] public class CalculatorFeatureSteps { // instantiating application instance CalculatorApplication app = new CalculatorApplication(); // variables to hold input values and the intermeditate result int input1, input2; double output; [Given(@"I have provided (.*) and (.*) as the inputs")] public void GivenIHaveProvidedAndAsTheInputs(int p0, int p1) { input1 = p0; input2 = p1; } [Given(@"I have provided (.*) as input")] public void GivenIHaveProvidedAsInput(int p0) { input1 = p0; } [When(@"I press add")] public void WhenIPressAdd() { output = app.add(input1, input2); } [When(@"I press substract")] public void WhenIPressSubstract() { output = app.subsctract(input1, input2); } [When(@"I press multiply")] public void WhenIPressMultiply() { output = app.multiply(input1, input2); } [When(@"I press divide")] public void WhenIPressDivide() { output = app.divide(input1, input2); } [When(@"I press squareroot")] public void WhenIPressSquareroot() { output = app.squareRoot(input1); } [Then(@"the result should be (.*)")] public void ThenTheResultShouldBe(double p0) { Assert.AreEqual(p0, output); } } } CalculatorApplication.cs; } } } packages.config <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net461" /> <package id="NUnit" version="3.11.0" targetFramework="net461" /> <package id="SpecFlow" version="2.4.0" targetFramework="net461" /> <package id="SpecRun.Runner" version="1.8.5" targetFramework="net461" /> <package id="SpecRun.SpecFlow" version="1.8.5" targetFramework="net461" /> <package id="SpecRun.SpecFlow.2-4-0" version="1.8.5" targetFramework="net461" /> <package id="System.ValueTuple" version="4.3.0" targetFramework="net461" /> </packages> Our upcoming tutorial will brief you on End to End example of using Specflow and Selenium Webdriver!
https://www.softwaretestinghelp.com/specflow-tutorial/
CC-MAIN-2019-47
refinedweb
2,861
53
09.30.2008 10:24 Astroscam Antarctica Digging through the archives... This picture was taken at the ANI basecamp next to the Patriot Hills, Antarctica during summer 1997-1998. 09.30.2008 09:40 python ctypes and geodjango I have a new draft package for geodjango on fink. There are a number of rough spots. First, I wish that the fink python would know about the default location of fink libs, so that it would find libgeos3. % ipython >>> ls /sw/lib/libgeos_c.1.4.1.dylib /sw/lib/libgeos_c.1.4.1.dylib >>> from ctypes.util import find_library find_library('libgeos_c') # Nothing >>> find_library('libgeos_c.1.4.1') # Nothing >>> find_library('libgeos_c.1.4.1.dylib') # Nothing >>> find_library('/sw/lib/libgeos_c.1.4.1.dylib') # Nothing >>> find_library('/sw/lib/libgeos_c.1.4.1') '/sw/lib/libgeos_c.1.4.1.dylib'Then the libgeos2 package is trouble. Postgis links against libgeos2's libeos_c.1.dylib. psycopg2.OperationalError: could not load library "/sw/lib/postgresql-8.3/liblwgeom.so": dlopen(/sw/lib/postgresql-8.3/liblwgeom.so, 10): Library not loaded: /sw/lib/libgeos_c.1.dylib Ben (RangerRick) suggested to put all the libs into %p/lib/libgeos3 for libgeos3 so that they do not conflict with libgeos2. That makes sense. libgeos3 really should have a different major version number. 09.30.2008 09:29 Delicious social bookmarking I've been meaning to try delicious for a long time and Capt Ben just pushed me over that edge, so I have an account: 09.29.2008 19:28 Google Earth KMZ image troubles Is there some trick to putting images with popups/placemark/thumbtacks within the KMZ zip file structure? If I do a save as KMZ and then open what works, one image will work while the rest do not. If I unzip the generated kmz, the doc.kml will work just fine. What am I doing wrong in the kml? Here is the file: GeoEndNote-20080514.kmz What am I doing wrong in the kml? Here is the file: GeoEndNote-20080514.kmz 09.29.2008 14:35 Martian upward looking lidar Phoenix recently took images of the lidar in action. These images have been combined to get the color. Today's press conference released this as a movie. These images have been combined to get the color. Today's press conference released this as a movie. 09.29.2008 13:37 Science on a sphere - Colin's flow visualizations Last week, Colin went to the opening of his Science on a Sphere demo at the Smithsonian National Museum of Natural History in D.C. I have to check it out in person next time I swing through the city. Diving Into a New World [NY Times] Diving Into a New World [NY Times] 09.29.2008 12:36 Fall begins at UNH I got a short break out to College Woods last week. Fall is beginning, but construction is just beginning on the new wind tunnel. Looking out over the reservoir... Somewhere in College Woods... Looking out over the reservoir... Somewhere in College Woods... 09.29.2008 09:14 Firefox background color printing Here is how in Firefox, to get the background colors to print. Pictured here is Firefox 3. It looks a bit different in Firefox 2. 09.28.2008 21:58 Octave (works like Matlab) If you need a subset of Matlab, Octave may be the program for you. And no license keys to worry about. plotting from this Octave tutorial_14<< plotting from this Octave tutorial 09.28.2008 13:07 Government data Government Data and the Invisible Hand, Robinson et al. [Social Science Research Network]. 09.27.2008 12:09 Playing with Zotero, GeoEndNote/GeoCite Zotero just got sued by EndNote. This makes me think more about creating a Django app for references complete with GeoDjango geometry. Not that I have time to try that, but it seems like a good basic Django app. Going back to the GeoEndNote stuff that I did with Rochelle and Neil, here is a stripped down version of what EndNote puts out as xml: Going back to the GeoEndNote stuff that I did with Rochelle and Neil, here is a stripped down version of what EndNote puts out as xml: <>Hirano, Naoto</author> <author>Ogawa, Yujiro</author> <author>Saito, Kazuo</author> </authors> </contributors> <titles> <title>Long-lived early Cretaceous seamount volcanism in the Mariana Trench, Western Pacific Ocean</title> <secondary-title>Marine Geology</secondary-title> </titles> <periodical> <full-title>Marine Geology</full-title> </periodical> <pages>371-379</pages> <volume>189</volume> <number>3-4</number> <keywords> <keyword>Pacific Ocean</keyword> <keyword>seamount</keyword> </keywords> <dates> <year>2002</year> </dates> <abstract>An alkaline volcanic rock sample, peralkaline rhyolite pillow lava, ...</abstract> <image>0247644805Hirano.gif</image> <caption>Fig. 2. Multi-narrowbeam map of the study area. ...</caption> <urls> <related-urls> <url></url> </related-urls> </urls> <custom1>POINT(147.67,15.5)</custom1> <!-- This is WKT --> <custom2>1/1</custom2> <custom4>Neil / Rochelle</custom4> </record> </records> </xml>But if you look at the full original (plus I cleaned up the formatting), you will see all sorts of strange style tags that should not become part of a GeoCite GeoDjango application. <> <style face="normal" font="default" size="100%">Hirano, Naoto</style> </author> <author> <style face="normal" font="default" size="100%">Ogawa, Yujiro</style> </author> <author> <style face="normal" font="default" size="100%">Saito, Kazuo</style> </author> </authors> </contributors> <titles> <title> <style face="normal" font="default" size="100%">Long-lived early Cretaceous seamount volcanism in the Mariana Trench, Western Pacific Ocean</style> </title> <secondary-title> <style face="normal" font="default" size="100%">Marine Geology</style> </secondary-title> </titles> <periodical> <full-title> <style face="normal" font="default" size="100%">Marine Geology</style> </full-title> </periodical> <pages> <style face="normal" font="default" size="100%">371-379</style> </pages><volume> <style face="normal" font="default" size="100%">189</style> </volume> <number><style face="normal" font="default" size="100%">3-4</style> </number> <keywords> <keyword> <style face="normal" font="default" size="100%">Pacific Ocean</style> </keyword> <keyword> <style face="normal" font="default" size="100%">seamount</style> </keyword> <keyword> <style face="normal" font="default" size="100%">Ar-Ar age</style> </keyword> <keyword> <style face="normal" font="default" size="100%">alkali-basalt</style> </keyword> <keyword> <style face="normal" font="default" size="100%">rhyolite</style> </keyword> <keyword> <style face="normal" font="default" size="100%">post-shield volcanism</style> </keyword> <keyword> <style face="normal" font="default" size="100%">Cretaceous</style> </keyword> </keywords> <dates> <year> <style face="normal" font="default" size="100%">2002</style> </year> </dates> <abstract> <style face="normal" font="default" size="100%"±2.</style> </abstract> <image> <style face="normal" font="default" size="100%">0247644805Hirano.gif</style> </image> <caption> <style face="normal" font="default" size="100%">Fig. 2. Multi-narrowbeam map of the study area. The dive site is shown by an arrow. Contour interval is 100 m. Referred to Ogawa et al. (1994). </style> </caption> <urls> <related-urls> <url> <style face="normal" font="default" size="100%"></style> </url> </related-urls> </urls> <custom1> <style face="normal" font="default" size="100%">POINT(147.67,15.5)</style> </custom1> <custom2> <style face="normal" font="default" size="100%">1/1</style> </custom2> <custom4> <style face="normal" font="default" size="100%">Neil / Rochelle</style> </custom4> </record> </records> </xml>BTW, I am now just using source-highlight for my blog... source-highlight -i geoendnote.xml -s xml --doc --out-format=html -o geoendnote.html 09.26.2008 14:56 Congress on Open Source software Open-source software gets a plug from Congress [GCN] IT'S RARE TO see a concept as technical as open-source software in a federal funding bill. But the House's proposed National Defense Authorization Act for Fiscal Year 2009 (H.R. 5658) (GCN.com, Quickfind 1209) includes language that calls for military services to consider open-source software when procuring manned or unmanned aerial vehicles. ... report states, "The committee encourages the department to rely more broadly on [open-source software] and establish it as a standard for intra-department software development." ... 09.26.2008 13:20 Google Earth KML in Research Competition Welcome to the KML in Research Competition. 09.26.2008 13:19 NSF Visualization Contest results announced 2008 Visualization Challenge Winners or better yet, slide show. ...Thanks to Art T. for telling me the results are out. 09.26.2008 10:19 Mac software updates - 10.5.5 and X11 2.3.1 I heard some troubles here and there on the net, but I just went through the Mac OSX 10.5.5 update and X11-2.3.1 updates and my machine seems to be okay and build X11 apps okay. 09.26.2008 09:12 Open source voting software Counting. ... 09.26.2008 08:23 Invalid MMSI Ben at Panbo has an article that mirrors the troubles we have been seeing with AIS data: Invalid MMSI numbers, a real problem For additional discussions, there is: Automatic Identification System (AIS): Data Reliability and Human Error Implications by Harati-Mokhtari et al, THE JOURNAL OF NAVIGATION (2007), 60, 373-389. For additional discussions, there is: Automatic Identification System (AIS): Data Reliability and Human Error Implications by Harati-Mokhtari et al, THE JOURNAL OF NAVIGATION (2007), 60, 373-389. This paper examines the recent introduction of the AIS to the ship's bridge and its potential impact on the safety of marine navigation. Research has shown that 80 to 85% of all recorded maritime accidents are directly due to human error or associated with human error. Safety is an important element of marine navigation and many people at different levels are involved in its management. The safe and efficient performance of joint systems, is heavily dependent upon how functions are allocated between the human and the machine. This paper investigates different regulations, supervision for proper use, training, and management of AIS users. It uses previous research and three separate AIS studies to identify problems. The potential of the AIS to cause problems is analysed. The classic human factor "Swiss Cheese" Model of system failure has been modified for the AIS to investigate a possible accident trajectory. The paper then concludes with recommendations and suggestions for improvements and further work.I my work with NOAA, we've seen that anything that requires human data entry is going to have errors in addition to things like the Nauticast reset issue that cause an MMSI reset to factory defaults. Other things I've seen include things likes names that are all spaces, quotes in the name, complete empty names, mmsi's of 0 or 1, dimensions that are the wrong units or swapped (there are 4 you enter: A, B, C, D), fields not updated (destination, draught, etc), and so forth. Then there are fields on units that you are not sure what they are used in a particular area (number of persons on board - used in London). 09.25.2008 15:02 Tomorrow's CCOM seminar - 1-2 slides per person Tomorrow is the first CCOM seminar for the 2008-09 season. We've been asked to provide 1-2 slides to summarize our research. My work is sufficiently diverse to make this task difficult. Here is my attempt. I have an advantage in that I'm giving the CCOM seminar talk next Friday on Oct 3rd, where I will talk about working on the Phoenix Mars Lander. Depicted here topics that include: polar exploration, marine conservation, 3D computer vision, Mars exploration, AIS, blogs, wikis, GoogleEarth, global seafloor mapping, and field work at sea and on land. In the center is one of my all time favorite projects where I made 3D stereo models of Yellowstone hot springs and geysers. I threw in python and fink for good measure. I'm having funny flashbacks to NASA project quad-charts. I'm having funny flashbacks to NASA project quad-charts. 09.25.2008 06:34 09.24.2008 20:37 How can this shared library problem happen? What happened to my fink pysqlite2 package? This is the same library. What? This works: In [1]: import pysqlite2So what is going on that this does not work? In [2]: import pysqlite2.dbapi2 ====================================================================== ImportError Traceback (most recent call last) /Users/schwehr/projects/src/noaadata/scripts/<ipython console> in <module>() /sw/lib/python2.5/site-packages/pysqlite2/dbapi2.py in <module>() 25 import time 26 ---> 27 from pysqlite2._sqlite import * 28 29 paramstyle = "qmark" ImportError: dlopen(/sw/lib/python2.5/site-packages/pysqlite2/_sqlite.so, 2): Symbol not found: _sqlite3_enable_load_extension Referenced from: /sw/lib/python2.5/site-packages/pysqlite2/_sqlite.so Expected in: dynamic lookupAfter an hour and a half bouncing things off of pogma and akh, I've got it figured out. Turns out that extension handling for sqlite3 in fink is turned off. Might be a tcl build issue. I haven't tried the latest sqlite (3.6.2) to see if things are better. The configure script for sqlite3 does not seem very well behaved. perl -pi -e 's,#define HAVE_LOAD_EXTENSION,#undef HAVE_LOAD_EXTENSION,' src/connection.cUpdate to the latest pysqlite2-py25 in fink and all should be well. 09.24.2008 14:23 TeraVision Andy M. pointed me to this. It looks cool, but there is an SGI Octane in the figure... blast from the past. Anyone have comments on using this system? 09.24.2008 13:48 Phx on NPR Science Friday npr_94836803.mp3 Science Friday travels to the home base of NASA's Phoenix Mars Lander in Tuscon, Ariz., to discuss the continuing exploration of Mars. Scientists explain how various robots, both on the surface and in orbit, are mapping and cataloging the Red Planet. 09.24.2008 13:28 Jeff Riffle's new website Just found out that Jeff has a new website: Jeff Riffle. Jeff gave me a tour of the lab at the UofA while I was in town for Phoenix operations. He showed me crazy things like raising hawk moths. This isn't the exact species but it gives you the sense of the type of critter that he is raising for neuroecology studies: [source: wikipedia - Image:Tomato Hornworm Larva - Relic38 - Ontario Canada.JPG] The neurology of sensing is a big topic these days. Someone just won a MacArthur foundation grant for fruit fly work on this: Rachel Wilson. 09.24.2008 10:29 Controlling other computers Update: Val pointed me to this client: Remote Desktop Connection Client for Mac 2 [microsoft]. Works pretty well.:. _25<<:. % fink install rdestop % rdesktop -g 1700x800 192.168.8.182 % rdesktop -g 60% 192.168.8.182 _31<< 09.23.2008 22:52 UNH Construction camera - CCOM from up on high A view of CCOM from up high... 09.23.2008 17:10 FedEx flight control I ran into someone who hadn't seen this visualization of planes going around a storm, so here it is from youtube: Highly Skilled Air Traffic Controller Highly Skilled Air Traffic Controller 09.23.2008 17:02 USCG Maritime Awareness Global Network (MAGNET) Just heard about the USCG MAGNET system, which receives a N-AIS feed. How does this relate to tools like MISLE? [wikipedia] Maritime Awareness Global Network - Wikipedia Maritime Awareness Global Network - Wikipedia ... The United States Coast Guard, an agency of the Department of Homeland Security, developed the Maritime Awareness Global Network (MAGNET) system to use information relating to vessels and activities within the maritime environment to accomplish the Coast Guard's missions in the areas of Maritime Safety, Maritime Security, Maritime Mobility, National Defense, and Protection of Natural Resources. MAGNET replaces the Joint Maritime Information Element (JMIE) Support System JSS. MAGNET processes personally identifiable information (PII). . Coast Guard Intelligence uses MAGNET provides awareness to the field as well as to strategic planners by aggregating data from existing sources internal and external to the Coast Guard or the Department of Homeland Security. MAGNET correlates data and provides the medium to display information such as ship registry, current ship position, crew background, passenger lists, port history, cargo, known criminal vessels, and suspect lists. Coast Guard Intelligence serves as MAGNET's executive agent and shares appropriate aggregated data on a need to know basis with other law enforcement and intelligence agencies. ... 09.23.2008 12:20 Neptune Construction Construction Continues on Neptune LNG Deepwater Port [lnglawblog] LNG almost done; pipeline to be buried next month [Gloucester Times] Workers on the giant barges building and burying pipeline for the Neptune liquefied natural gas port off the Gloucester shore have finished two-thirds of their work and the final phase of construction this year is scheduled to end next month. . The pipeline is part of a $1 billion LNG project being constructed by Suez Energy. Work on it began in July when the 313-foot-long Lone Star Horizon, run by contractor Cal Dive, started laying pipeline from the terminal location 10 miles southeast of Gloucester to a point 3.12 miles from Marblehead, where it connects to the existing Algonquin HubLine. The HubLine runs from Salem to Weymouth, where it connects to overland pipe. . With the completion of the 13-mile pipeline, the Lone Star was replaced by the 420-foot-long Atlantic, which was responsible for digging a 6-foot-deep trench while stuffing the pipeline inside. ... 09.23.2008 12:14 Python Papers - Call for papers Call for Papers, Volume 3 Issue 3 We.If you are a python person, you should consider publishing in The Python Papers. 09.23.2008 11:25 Phoenix Mars Lander remote operations Nice timing on this article. I was just working on my RKSML (Rover Kinematic State Markup Language) converter script. The script takes the robotic arm (RA) motion and produces Lightwave keyframe scene files (lws) and my state stamp markup language (ssml) for the animation teams. A naming convention of one of the teams changed, so my 100 line bash control script needed to know about the new possible source file. This kind of stuff was much easier when I could just wander over to another part of the spacecraft operations center. Now I have to be extra diligent about documentation and emailing everyone who needs to know. Without VPN, ssh, scp, remote desktop, cell phones, email and collaboration web software, we would be in big trouble. Most Phoenix Mars Lander mission scientists have gone home [Tucson Citizen] Most Phoenix Mars Lander mission scientists have gone home [Tucson Citizen] Distance is posing challenges for researchers running the Phoenix Mars Lander mission. . Not only are Phoenix scientists operating a craft 230 million miles away, but most of the 150-member science and engineering team have in recent weeks left the Tucson Science Operations Center to return home. . During the summer more than 100 researchers would pack the SOC's large downlink room to review the previous day's data as it arrived via satellite from the Lander and plan the mission's next scientific activities. . On a recent morning, 11 researchers were in the room, with six times that many remotely attending the meeting using a high-tech networked communications system. ... 09.22.2008 16:14 video standards Not sure what the original source is. Got this via Eric at JPL. A72 [atsc.org] In their press release on AVC, for the first time in public, the ATSC refers to "ATSC 2.0." This concept for next generation services for fixed receivers is part of the ATSC long-term strategic plan for the future of DTV. ATSC 2.0 is currently in the development stage in the ATSC Planning Committee, chaired by NAB Science & Technology staff member Graham Jones, and is a separate effort from the mobile/handheld standard now in preparation. Various new capabilities are envisioned for ATSC 2.0, which is expected to trigger a new generation of receivers potentially including AVC. . "WASHINGTON, September 2008 - The Advanced Television Systems Committee, Inc. has approved and published A/72 which details the methodology to utilize Advanced Video Coding (AVC) within an ATSC DTV transmission. AVC, which was developed by the ITU-T Video Coding Experts Group together with the ISO/IEC Moving Picture Experts Group, is also known as H.264 and MPEG-4 Part 10. The A/72 Standard defines constraints with respect to AVC, compression format restraints, low delay and still picture modes, and bit stream specifications. In addition it specifies how CEA-708 closed captions are to be carried in an AVC bit stream. The new standard is in two parts, Part 1 is titled "Video System and Characteristics of AVC in the ATSC Digital Television System," and "Part 2 "AVC Video Transport Subsystem Characteristics."ATSC ADOPTS STANDARD FOR ADVANCED VIDEO CODING [testfreaks.com] A72 [atsc.org] 09.21.2008 17:06 Arctic mapping on the Colbert Report Colbert Report on the Arctic Mapping. 09.21.2008 12:01 View of from the Healy of Louis St. Laurent Betsy Baker posted a picture in #19 Conflict in the Arctic? The Tenacity of Media Spin where you can see the Canadian ice breaker. I found this one that I like: 20080919-0101.jpeg 20080919-0001.jpeg is also a realy nice image. I found this one that I like: 20080919-0101.jpeg 20080919-0001.jpeg is also a realy nice image. 09.21.2008 11:43 National Academy draft Report on Marine Debris Tackling Marine Debris in the 21st Century Excutive Summary ... In its analysis, the committee identified four overarching areas in which additional emphasis is needed to adequately address the marine debris problem. Broadly, they center on; (1) marine debris management, leadership, and coordination; (2) information and metrics with which to assess effectiveness of current measures or efficiently direct future efforts; (3) port reception facilities for shoreside disposal; and (4) the distinct aspects of managing fishing gear as a source of marine debris. Salient supporting recommendations are presented under each overarching recommendation; additional recommendations and the basis for all of the findings and recommendations are included in Chapters 2, 3, and 4. ... 09.21.2008 09:09 matplotlib and lidar Update 20080926: Thanks to Bror Jonsson for a patch to matplotlib-basemap-data-py. How to ask the path to the data files had changed. There is still likely troubles with libgeos2 lurking. If it is not working, make sure to install libgeos2 in addition to libgeos2-shlibs. There is some bad version number stuff going on with libgeos[23]... libgeos did not increment their version numbers of the dylibs enough in the libgeos2 to 3 update.. Thanks to Jed Frechette for getting me to update the package. He has some open source python software for lidar: TLSpy. Check out his photo gallery I think this one of trees is especially cool.... from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt width = 28000000; lon_0 = -105; lat_0 = 40 m = Basemap(width=width,height=width,projection='aeqd', lat_0=lat_0,lon_0=lon_0) m.drawmapboundary(fill_color='aqua') m.drawcoastlines(linewidth=0.5) m.fillcontinents(color='coral',lake_color='aqua') m.drawparallels(np.arange(-80,81,20)) m.drawmeridians(np.arange(-180,180,20)) xpt, ypt = m(lon_0, lat_0) m.plot([xpt],[ypt],'ko') plt.title('Azimuthal Equidistant Projection') plt.savefig('aeqd.png') Thanks to Jed Frechette for getting me to update the package. He has some open source python software for lidar: TLSpy. Check out his photo gallery I think this one of trees is especially cool... ] 09.21.2008 07:10 Phoenix mission extended My little contribution to Phoenix last week... I assisted with the image release process for Friday. Cloud animated gif Frost in the trench - Fall is coming to NH too. NASA extends Mars lander mission again [Boston.com/AP] Cloud animated gif Frost in the trench - Fall is coming to NH too. NASA extends Mars lander mission again [Boston.com/AP] ... NASA spokesman Dwayne Brown said Thursday the space agency will invest about $6 million to keep the $422 million mission going through December. . It's the second and possibly last extension since the lander may not survive the upcoming Martian winter. ... 09.20.2008 22:21 photo meme Can you read what is on my computer screen from my glasses? Indoors with not enough light. Instructions: Take a picture of yourself right now. Don't change your clothes, don't fix your hair - just take a picture. Post that picture with NO editing. Post these instructions with the picture. Instructions: Take a picture of yourself right now. Don't change your clothes, don't fix your hair - just take a picture. Post that picture with NO editing. Post these instructions with the picture. 09.19.2008 10:39 Cosco busan article Track back: Cosco Busan - Radar Images And NTSB Transcript Pilotage Paradox by Paul Drouin [gCaptain] Cosco Busan radar movie [mp4] Pilotage Paradox by Paul Drouin [gCaptain] .... ...389888.pdf [ntsb] from NTSB Docket Management System - List of Contents 08:26:56 CREW full ahead full ahead. 08:27:10 CREW starboard twenty. 08:27:12 PILOT thank you. 08:27:24 VTS unit romeo traffic. 08:27:29 PILOTVHF traffic romeo. 08:27:37 PILOT ease to ten. 08:27:40 CREW ease to ten. 08:27:43 CREW rudder starboard ten. 08:27:45 PILOTVHF trafic romeo did you call. 08:27:48 VTS unit romeo traffic uh AIS shows you on two three five heading what are your intentions over? 08:27:57 PILOTVHF well I'm comin' around I'm steering two eighty right now. 08:28:02 PILOT starboard twenty. 08:28:02 CREW starboard twenty. 08:28:04 VTS roger understand you still intend ** span? 08:28:06 CREW starboard twenty sir. 08:28:08 PILOT this is the center of the bridge right? 08:28:11 CREW yeah yeah. 08:28:12 PILOT yeah. 08:28:13 PILOT hard starboard. 08:28:14 CREW hard starboard. 08:28:15 PILOTVHF yeah we're still delta echo. 08:28:22 CREW hard starboard sir. 08:28:42 PILOT midships. 08:28:44 CREW midship. 08:28:51 PILOT starboard twenty. 08:28:53 CREW starboard twenty. 08:29:01 PILOT hard starboard. 08:29:02 CREW hard starboard. 08:29:04 CHOFFUHF **. 08:29:06 CAPT what did he say? 08:29:08 CREW hard starboard sir. 08:29:09 CHOFFUHF the bridge column the bridge column. 08:29:11 CAPTUHF oh I see it I see it. 08:29:14 CREW *. 08:29:16 PILOT yeah I see it. 08:29:22 CREW rudder hard starboard sir. 08:29:26 PILOT midships. 08:29:27 CREW midship. 08:29:31 PILOT hard port. 08:29:32 CREW hard port. 08:29:44 CREW hard port sir. 08:29:44 CREW rudder hard port sir. 08:29:55 CREWwheel hard port. 08:30:05 CREW wheel is hard port sir. 08:30:07 PILOT okay midships. 08:30:08 CREW midships. 08:30:10 PILOT dead slow ahead. 08:30:11 CREW dead slow ahead. 08:30:12 PILOTVHF yeah traffic we just touched the delta span I'm gonna go to...I'm gonna try get her anchored anchorage nine- or anchorage seven. 08:30:20 CREW midships sir. 08:30:24 CREWUHF captain captain. 08:30:25 CHOFFUHF there is a leak there is leak. 08:30:27 CREWUHF okay okay it's all right now. 08:30:32 PILOT is the ship all right? is the ship all right? 08:30:34 CAPT no no no it's leaking leaking. *. Cosco Busan radar movie [mp4] 09.19.2008 10:25 More Healy ice breaker stuff on the web Interesting Ship of The Week - USCGC Healy [gCaptain] Monica has posted more pictures from the cruise and an image of the chirp showing the foot of the slope. Monica has posted more pictures from the cruise and an image of the chirp showing the foot of the slope. 09.19.2008 09:24 Global shipping patterns Colin just pointed me to this paper. I haven't redone the literature search on this topic since middle of 2007, so I hadn't run into it. Halpern et al., 2008: A Global Map of Human Impact on Marine Ecosystems [sciencemag] full image Trackback: Maritime Monday 128 [gCaptain.com] Halpern et al., 2008: A Global Map of Human Impact on Marine Ecosystems [sciencemag].The data and more detailed figures are available here: full image Trackback: Maritime Monday 128 [gCaptain.com] Kurt's Weblog has an image mapping "Global shipping patterns". 09.18.2008 17:40 NPR Science Friday - Phoenix Mars Lander Mars . 09.18.2008 10:14 Web-Of-Science star tree The Web Of Science has a tool to visualize references that I haven't used before. Kind of fun. Not sure how useful it will be down the road, but it makes it easy to see what references look to be promissing for finding additional references. 09.17.2008 23:41 Class B AIS in the US Class B AIS here?, but worthless? [panbo] Today two reliable sources told me that all five FCC commissioners have now signed off on Class B AIS for US waters, though neither knows when the Order will become effective. The final step should be an announcement in the FCC Daily Digest. ...For understand use of various waterways, Class B will be a huge step forward. I do most of my analysis on downsampled data where I get at most one report per minute for each vessel. However, read the rest of Ben's articles for issues about collision avoidance. 09.17.2008 20:50 Healy Twitter I though I had written about this, but I don't see anything in my notes. The USCG Ice Breaker Healy has a twitter feed: With posts like this: September 16, 2008 update With posts like this: September 16, 2008 update Greetings from the frozen north. The ship is covered in ice and operations with the Louis are in full swing. Two weeks remain in our operation with the Canadians and things are progressing smoothly. . After flight ops finished on Saturday, we made a beeline for our rendezvous point with the Louis. On Tuesday we met them and commenced flight operations to allow the science parties on both vessels to meet and discuss the plans for the coming weeks. After the meetings were finished, the Louis was able to lower its seismic gear so that we could commence the first transect. ... 09.17.2008 14:15 Google Oceans I hear that Google Oceans will be out in the beginning of November. 09.16.2008 12:04 Data interoperability and integration I was talking to Ru Morrison this morning and he mentioned several additional efforts that I was not aware of. It's time for a summary post. EPA Exchange Network Open Geospatial Consortium (OGC) - OGC Ocean Science IE Report has been submitted to OGC [oostethys.org] See also: EPA Exchange Network The Exchange Network is a partnership among states, tribes, and the U.S. Environmental Protection Agency that is revolutionizing the exchange of environmental information. Partners on the Exchange Network share data efficiently and securely over the Internet. This new approach is providing real-time access to higher quality data while saving time, resources, and money for partner states, tribes, and territories.NASA Global Change Master Diretory (GCMD).Marine Metadata Interoperability Project (marinemetadata.org) CCOM has been working in this group. Open Geospatial Consortium (OGC) - OGC Ocean Science IE Report has been submitted to OGC [oostethys.org] See also: - Global Earth Observation System of Systems (GEOSS) [epa.gov] - National Ecological Observatory Network (NEON) - [neoninc.org] 09.15.2008 21:54 Cape Cod hardware install Today, the Cape Cod National Seashore, USCG, NOAA, and UNH all met out on Cape Cod. The first order of business was an antenna repair: Here is me upstairs on a conference call. The new station after it was installed. The minimum keyboard display (MKD) on the unit. Here is me upstairs on a conference call. The new station after it was installed. The minimum keyboard display (MKD) on the unit. 09.14.2008 14:36 Fall webworms The fall webworms (Hyphantria cunea) have been going strong this year. My yard has escaped them, but UNH has lots. These two pictures show them starting on the south short of Lake Winnipesaukee at the end of July. Webworms or Halloween Decorations? [unh extension] Webworms or Halloween Decorations? [unh extension] ... Those hairy webworms eating your leaves at the moment will live in the soil this winter as pupae, emerging next July as pure white moths. Then the cycle will begin again. . Unlike that spring pest, the Eastern tent caterpillar, the fall webworm isn't very harmful to the plants it feeds on. Unsightly perhaps, but the leaf feeding happens so late in the year that little damage is done to the health of the tree. . Why not think of the nests as early Halloween decorations? I know I've seen worse draped over trees. 09.14.2008 09:01 Mid-September Garden Fall is approaching and it looks like many of my attempts in the garden did not make it this year. There have been many surprises both in terms of successes and failures. The biggest failure has been swiss chard. Last year, I could do no wrong to the chard and all groups of the plant just kept producing like crazy until the frost. On the other side of things, the two tyes of beans that I've got in are not quite there yet, but producing more beans than I thought possible.. 09.13.2008 17:59 Django and JQuery I am too overloaded to go check this out, but sounds like what I have been hoping to try to do: Orderable inlines using drag and drop with jQuery UI [django snipped 1053] Also - exceptions - Builtin error classes [Doug Hellmann] Only recently, have I started trying to get better at using exceptions in Python. Definitely improves my code.. Also - exceptions - Builtin error classes [Doug Hellmann] Only recently, have I started trying to get better at using exceptions in Python. Definitely improves my code. 09.12.2008 09:50 User activated fog signals Coast Guard reminds boaters about remote activated fog signals [Coast Guard News] .... ...Comment from Roland: Cool, small airports have had this for runway lights a long time ago! 09.12.2008 06:42 Delay-Tolerant Networking (DTN) in space DTN in space: UK-DMC satellite first to transfer sensor data from space using 'bundle' protocol [sstl.co.uk] .... ... 09.11.2008 21:48 First non-localhost django site I finally have my first Django site up on the internet beyond using the built in debug server. I'm using apache2 with mod-python. I'd write up the SSL config with apache2, but I did that quite a while ago on my dev server.: <Location "/"> PythonPath "['/home/schwehr/python-2.5/lib/python2.5/site-packages','/home/schwehr/'] + sys.path" SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE dt.settings PythonDebug On </Location> # Alias /media "/home/schwehr/python-2.5/lib/python2.5/site-packages/django/contrib/admin/media" <Location "/media"> SetHandler None # Don't use mod-python on this directory </Location> 09.11.2008 16:41 Coin 3.0.0 released SIM Coin3D - Rewrite of SGI OpenInventor. Coin 3.0.0 "Buffalo" Released . Kongsberg SIM is proud to release version 3.0.0 of the Coin 3D graphics library. Coin 3.0.0 is a major release. It breaks binary compatibility with previous versions of Coin, but is for the most part upward source code compatible with Coin 2.*. A new major release means it was time for doing cleanup-duties. Some dead-end developments were removed, certain ABI-preservation-related hacks were discarded and rewritten properly. Certain bad design choices were improved upon. . Coin 3.0.0 is not a release with a massive roll-out of new features. Resources have at times been stretched, but we have managed to accumulate a decent set of features for a release anyway, and internal to Coin we have many new subsystems to build future features on.Their list of new features: - Scene graph performance profiling subsystem - SoDepthBuffer node for constrolling Z-buffer settings - Shaders: SoVertexAttribute and SoVertexAttributeBinding nodes - Shadows: SoShadowSpotLight node - SoHeightMapToNormalMap texture conversion engine - SoPickStyle: new styles SHAPE_ON_TOP, BOUNDING_BOX_ON_TOP, SHAPE_FRONTFACES - New XML-based GL driver feature database for tagging buggy/slow features in specific drivers - Statechart XML engine (2007-draft based), used to implement examiner viewer mode at the Coin level - Foreign file format support through SoForeignFileKit w. example SoSTLFileKit - Draggers: minTranslation/maxTranslation fields in SoTranslate1Dragger and SoTranslate2Dragger - OS X: Coin has become more bundle-aware and will loads external libs bundled with Inventor.framework or the application bundle (better encapsulation) - SoLineHighlightRenderAction and SoBoxHighlightRenderAction now only supports one SoSelection node (performance and OIV-compatibility) - SoBumpMap will now detect height maps stored as rgb(a) - SoRayPickAction picking precision improvements - Include SoFieldContainer userdata when doing a deep node copy - Anti-aliasing is now done around the center of each pixel - Boost.Test-based testsuitee.g. kogeo seismic toolkit - open source application for 2d and 3d seismic data analysis. 09.10.2008 11:18 Journals with RSS feeds Today, it seems rare to to find journals with RSS feeds. Finally I found one that is intersting to me: ICES Journal of Marine Science. There is just too much going on for me to go look for a journal each month and I can't deal with any more email. e.g. stuff like this: Anderson et al., Acoustic seabed classification: current practice and future directions. e.g. stuff like this: Anderson et al., Acoustic seabed classification: current practice and future directions. 09.10.2008 10:09 List of languages I know based on this and this The exact earlier years are fuzzy in my head... Or how about start of preferred/heavily-used OSes: Trackback: the meme has mutated [dealmeida.net] The exact earlier years are fuzzy in my head... 1979. BASIC 1985. FORTRAN 66 & 77 1990. CSH/TCSH 1991. C++ 1991. ML (painful memories) 1991. LISP 1991. ADA 1991. Make 1991. Prolog 1991. 68K assembly 1991. MIPS assembly 199?. Karol the !@#$%^& Robot - tutoring students with this sucked 1993. HTML (hardly a real language, but it the impact was huge) 1994. Matlab 1996. TCL 1996. Python 1999. BASH 2000. Java 2000. Fortran 90/95 2002. SQL 2008. JavaScriptI've stumbled through Perl and PHP, but I never really programmed in those two. Or how about start of preferred/heavily-used OSes: 1978?. HP Terminal 1984. MS DOS + HP Touch screen 1985. PC-DOS 1989. VMS 1989. TOPS-20 1990. Windows 3.0 1990. SunOS 4.x 1990. Mac OS pre OSX 1992. NeXT 1992. AIX 1992. D-UX / Alpha 64 bit 1993. Linux 1993. AmigaOS (version?) 1993. (Free?) BSD on a PC 1994. IRIX 1999. Windows 98 1996. VmWare 2001. Mac OSXNot shown are the out dates for each OS when I stopped seriously using it. At the moment, I am left with Linux and MacOSX as my primary OSes with occasional use of Solaris and Windows XP. Trackback: the meme has mutated [dealmeida.net] 09.09.2008 17:20 GeoCoastPilot on Panbo Thanks go to Ben Ellison for mentioning the GeoCoastPilot on Panbo to help get people to evaluate our research prototype: GeoCoastPilot, early adopters needed! Make sure to check out the comments for an interesting comparison with MaxSea's TimeZero. . ... Make sure to check out the comments for an interesting comparison with MaxSea's TimeZero. 09.09.2008 17:03 Michelle Weirathmueller's defense on Monday UPDATE: time change! Michelle's defense is at 9 AM now. And I am bummed out that have to miss her defense because I'm traveling for work. ACOUSTIC RANGING IN A DYNAMIC, MULTIPATH ENVIRONMENT by Michelle Weirathmueller ACOUSTIC RANGING IN A DYNAMIC, MULTIPATH ENVIRONMENT by Michelle Weirathmueller An acoustic experiment was carried out in October 2007 in Portsmouth Harbor, New Hampshire, to measure the effects of environmental variability on acoustic range measurements over a distance of 948 meters. A fixed source and receiver measured the one-way travel time and signal level fluctuations over four days. Wind, current speed, and tidal data were collected in order to assess their effects on the acoustic measurements. The environmental data collected during this experiment showed variability at many scales, both temporally and spatially throughout the harbor. The acoustic data revealed the presence of multipath arrivals, with 2-3 strong arrivals visible for each transmitted ping. A simple geometric model was used, along with ray-tracing, to describe fluctuations in arrival time and signal level. Acoustic travel times between a fixed source and receiver were converted to range measurements and compared with GPS-derived ranges. This study provides a basis for understanding the capabilities and limitations of range measurements in Portsmouth Harbor, or similar dynamic multipath environments. . 9:00 AM Monday, September 15, 2008 Chase Ocean Engineering Laboratory CCOM-Admiral's Conference Room 09.09.2008 14:56 Thunderbird consuming massive disk space I was wondering where all of my laptop's disk space had gone. I have a lot on my computer, but did I really fill up my my entire 150GB internal drive in less than a year? And I've even removed my Windows P VMWare image a while ago to get more space. I happened to look in ~/Library/Thunderbird and found that part of the tree on my disk was 19GB!! I discovered that my INBOX file for IMAP was most of that. Nothing I did in the interface that seemed safe did anything to help. I tried to compact the folder, but there was no change. On the server, my $MAIL inbox file is big at 250MB, but that shouldn't be a problem. Finally, I decided to shutdown Thunderbird, back up the INBOX and INBOX.msf elsewhere and then nuke both files from within my Thunderbird Library directory. It took about 10 minutes to start up the mail reader the next time, but my INBOX on my laptop is now only 35MB. More better! 09.09.2008 14:56 Eon Fusion This program looks to have influences of SGI Explorer, GeoZui4D and Fledermaus. Graphical data flow layout, time support, and a pretty package. Pretty pictures. Thanks to Art for telling Roland about this who told me. Eon Fusion by Myriax. They need to explain this one more. How are they blending the photo and the sea level change? Eon Fusion by Myriax. They need to explain this one more. How are they blending the photo and the sea level change? 09.08.2008 07:25 Latex source to seismic-py paper In the spirit of open source software, I've put the LaTeX source to my latest paper online. Here is a little bit of it: schwehr2008-pythonpapers-seismic-py.tex schwehr2008-pythonpapers-seismic-py.tex \documentclass[agupp]{aguplus} \usepackage{graphicx} \usepackage[usenames]{color} \usepackage{hyperref} %\usepackage[draft]{hyperref} \let\cross=\times\lefthead{Schwehr} \righthead{seismic-py, Python Papers 2008} \hypersetup{ pdftitle = seismic-py: Reading seismic data with Python pdfauthor = Schwehr, pdfsubject = Geophysical data processing, pdfkeywords = SEGY Python binary seismic time-series } \hypersetup{ colorlinks = true, linkcolor = red, anchorcolor = red, citecolor = blue, filecolor = red, pagecolor = red, urlcolor = blue } \newcommand{\module}[1]{\texttt{#1}} \newcommand{\pythondict}[1]{\texttt{#1}} \newcommand{\ascii}{\textsc{ASCII}} \newcommand{\ebcdic}{\textsc{EBCDIC}} %cite Barry et al. [1975] %citet Barry et al. [1975] %citep [Barry et al., 1975] %citet* Barry, Cavers, and Kneale [1975] %citep* [Barry, Cavers, and Kneale, 1975] \begin{document} \title{seismic-py: Reading seismic data with Python} \author{Kurt Schwehr} \affil{Center for Coastal and Ocean Mapping, University of New Hampshire} \authoraddress{ K. Schwehr, Center for Coastal and Ocean Mapping, University of New Hampshire, Chase Ocean Engineering 24 Colovos Rd, Durham, NH 03824, schwehr@ccom.unh.edu, \url{} } \begin{abstract} The field of seismic exploration of the Earth has changed dramatically over the last half a century. The Society of Exploration Geophysicists (SEG) has worked to create standards to store the vast ... SVN $Id: seismic-py.tex 10096 2008-08-15 19:19:43Z schwehr $ \end{abstract} \section{INTRODUCTION} Seismic data systems use acoustic pulses to send sound waves through water and the solid earth to map layers within the subsurface. They vary from simple single source and single receiver systems to multiple sources and long arrays of geophones or hydrophones. The processing of the received sound waves requires a range of data storage and signal analysis techniques. Python can support both the data archival and precessing tasks. ... \bibliographystyle{agu} \bibliography{seismic-py} \end{document}The syntax highlighting of the LaTeX source was done not with code2html. I'm trying out GNU source-highlight. It's being maintained and code2html doesn't support as many languages. source-highlight -i short.tex -o short.html -s latex -d --out-format html 09.07.2008 10:17 Making python programs have an importable main I keep trying to make my python code better. Python is a great language, but as with all languages, how you use it strong impacts how well your code works and how maintainable the code is (both by the author and external people who will see the code). I just started switching to making the code behind main as a function. Here is an article that talks about why this is good. It also gives good reason to avoid calling sys.exit() as much as is possible. Why your main program should be importable by Chris Siebenmann. I should look at how I do OptionParser. It is often hard to interact with my code via a shell. Why your main program should be importable by Chris Siebenmann. - For debugging your code with a python shell. - For pychecker, pylint, epydoc, or other system that wants to import your code and and use python to understand the code 09.06.2008 22:57 Science team leaves the Healy The aloftcon camera caught this image of the helocopter offloading the science team from the Healy. Most of the science team is currently in SeaTac waiting for various flights home. Original: 20080906-0301.jpeg The location in Google Earth: Original: 20080906-0301.jpeg The location in Google Earth: 09.05.2008 17:39 Adv Tech to Explore the Oceans and Shallow Survey 2008 Don't for get that Shallow Survey 2008 is Oct 21-24. The conference is just down the road from CCOM. Bennett Symposium Bennett Symposium It is my pleasure to invite you to participate in the upcoming Bennett Symposium on "Using Advanced Technology to Explore the Oceans" to be held on October 9th and 10th of 2008 on the Hattiesburg campus of the University of Southern Mississippi. I will be coordinating this symposium as winner of the 2008-2009 Bennett Professorship which was established to honor the son of Mr. and Mrs. T.W. Bennett, Sr., of Natchez, Mississippi. This endowed professorship is named in honor of their son, T.W. (Buddy) Bennett, Jr., who graduated from The University of Southern Mississippi in 1967, but has been "missing in action" since his plane crashed in Viet Nam in 1972. The symposium takes place every two years to honor Buddy and this year's topic should be of interest to many of you on this mailing list. Speakers from all across the country will make presentations on topics such as: . - manned and unmanned submersibles, including AUVs - autonomous gliders - the latest in ROV technology - seafloor mapping (LIDAR as well as multibeam) - precision navigation - the new NOAA ship and its telepresence technology - deep diving for natural product research - remote seafloor observatories - Microsensors for biological research - advanced sonar systems - satellite-based bathymetric measurements - and other topics! Regards, Vernon AsperAnd Hydro8 [Hydro International] in Liverpool 4-6 November. 09.05.2008 17:32 Building track lines over a region For a CCOM/JHC project, Jim G. needs a series of lines 500m apart over a region. This is a lot of work in a tool like Fledermaus to create this kind of thing. This is something that people normally use HyPack to do.: Python and PostGIS make this task pretty easy. Don't forget to cleanup the 1200 temp files now sitting on your computer after trying this : #!/usr/bin/env python x0 = -77.4589 x1 = -73.2555 # y0 = 29.9144 y1 = 33.1567 # dy = y1 - y0 ny = 1+ int(dy / 0.005) # 500m # poly=))' # for i in range (ny): y = y0 + i * 0.005 line = '(%f %f, %f %f)' % (x0,y,x1,y) linestring = 'LINESTRING(%f %f, %f %f)' % (x0,y,x1,y) print "SELECT AsText( ST_Intersection('%s', '%s') );" % (poly,linestring)It outputs lines that look like this: SELECT AsText( ST_Intersection( ))', 'LINESTRING(-77.458900 29.914400, -73.255500 29.914400)' ) );Now setup postgis on my mac: % fink install postgis83 % sudo -u postgres createuser -U postgres $USER % createdb somedb % psql somedb "CREATE LANGUAGE plpgsql;" % psql -f /sw/share/doc/postgis83/lwpostgis.sql -d somedb % psql -f /sw/share/doc/postgis83/spatial_ref_sys.sql -d somedbNow pipe the results from mklines into PostGIS: % mklines.py | psql somedb | head -4 astext ----------------------------------------------------------------- LINESTRING(-77.0283149893808 29.9144,-77.0282904015892 29.9144) (1 row)That looks good, so grab the coordinates: % mklines.py | psql somedb | grep LINESTRING | cut -c12- > results.txtresults.txt looks like this: (-77.0283149893808 29.9144,-77.0282904015892 29.9144) (-77.031778344859 29.9194,-77.0236815996312 29.9194) (-77.0352417003373 29.9244,-77.0190727976732 29.9244) (-77.0387050558155 29.9294,-77.0144639957152 29.9294) (-77.0421684112938 29.9344,-77.0098551937572 29.9344)From here, we need to get each line of two points into the form that will work with Fledermaus. x0 y0 x1 y1We also need to create a shell script of cmdop commands to write out an sd file for each line. Here is sdfiles.py: #!/usr/bin/env python # script = file ('make-sd-files.sh','w') script.write('#!/usr/bin/env bash\n') # i = 0 # Keep track of the line numbers for line in file('results.txt'): i += 1 line = line.strip('()\n') start,end = line.split(',') out = file('%03d.xy'%i,'w') out.write('%s\n%s\n' %(start,end)) out.close() cmd = 'cmdop mklines -in %03d.xy -out line%03d.sd -data xy' % (i,i) script.write(cmd+'\n')After running the script, we now have make-sd-files.sh that looks like this: #!/usr/bin/env bash cmdop mklines -in 001.xy -out line001.sd -data xy cmdop mklines -in 002.xy -out line002.sd -data xy cmdop mklines -in 003.xy -out line003.sd -data xy cmdop mklines -in 004.xy -out line004.sd -data xy cmdop mklines -in 005.xy -out line005.sd -data xy ...Run the script and watch it create over 600 sd files. From here, open Fledermaus. Then File -> Open Data Object. Then select all the sd files. File -> Save Scene and you are done. Python and PostGIS make this task pretty easy. Don't forget to cleanup the 1200 temp files now sitting on your computer after trying this 09.05.2008 13:40 Maritime Casualty Investigation Association MCIA Maritime Casualty Investigation Association Maritime Accident Casebook has been asked to conduct a survey regarding a proposal for a Maritime Casualty Investigation Association to feel out individuals and various industry sectors about the desirability of such a body. The purpose of this email is to gain feedback on the proposal. . It is intended that the association actively promote maritime/offshore casualty investigation as a profession, act as a 'watering-hole' for the public and private sectors, promote the concept of casualty investigation as an element in safety enhancement and risk reduction rather than liability-focussed, develop a unified set of competencies for maritime/offshore casualty investigation and encourage compliance with relevant IMO codes and obligations. ... 09.05.2008 08:54 Bee in the garden A little something to offset all the code from early this morning: 09.05.2008 07:50 trac with django UPDATE: Template filter implementing the Trac wiki markup language [djangosnippets]. % fink install trac-py25 % mkdir -p ~/Desktop/trac-django/trac % cd ~/Desktop/trac-django/trac % trac-admin `pwd` initenv % htdigest -c .htdigest localhost $USER enter the password you want % tracd -p 9000 --auth="*",`pwd`/.htdigest,localhost `pwd` % open log in with your username and make some changes to the wiki pages and add a ticket or two with some updates. Now kill that tracd webserver. It's time to work with django. % cd ~/Desktop/trac-django % django-admin.py startproject monitor_trac % cd monitor_trac Edit settings.py to have a database of sqlite3 and a database of trac.db % ln -s ../trac/db/trac.db % python manage.py inspectdb > models_autogen.pyThat last inspectdb call will go into the trac database and try to build the python code to represent the tables in the trac database. Time to see what we have. % sqlite3 trac.db .tables sqlite3 trac.db .tables attachment node_change session_attribute version auth_cookie permission system wiki component report ticket enum revision ticket_change milestone session ticket_custom % sqlite3 trac.db ".schema wiki" CREATE TABLE wiki ( name text, version integer, time integer, author text, ipnr text, text text, comment text, readonly integer, UNIQUE (name,version) ); CREATE INDEX wiki_time_idx ON wiki (time);Here is what django thought about that table: class Wiki(models.Model): name = models.TextField(blank=True) version = models.IntegerField(null=True, blank=True) time = models.IntegerField(null=True, blank=True) author = models.TextField(blank=True) ipnr = models.TextField(blank=True) text = models.TextField(blank=True) comment = models.TextField(blank=True) readonly = models.IntegerField(null=True, blank=True) class Meta: db_table = u'wiki'It doesn't look like this will work right. Let's check. % python manage.py startapp trac Error: 'trac' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. % python manage.py startapp dt % rm trac.db # Get rid of the symbolic link to keep the original database intactNow put the above wiki model into dt/models.py. Then edit the INSTALLED_APPS in settings.py to look like this: INSTALLED_APPS = ( 'monitor_trac.dt', )Time to create and view the database table that does with this model. % python manage.py sqlall dt BEGIN; CREATE TABLE "wiki" ( "id" integer NOT NULL PRIMARY KEY, "name" text NOT NULL, "version" integer NULL, "time" integer NULL, "author" text NOT NULL, "ipnr" text NOT NULL, "text" text NOT NULL, "comment" text NOT NULL, "readonly" integer NULL ) ; COMMIT;Looks like there is an extra "id" field as the primary key. Django does not currently understand the UNIQUE(name,version) constraint on the database, but I think that it wouldn't be too much work to dump the trac database and rebuild it with the above table plus the UNIQUE.. 09.04.2008 19:38 seismic-py paper out in Python Papers Just out... this is the first time I've written a peer reviewed paper by myself. A very different experience. This paper is much better thanks to the reviewers. Python Papers vol 3, No 2 Entire Volume 3 Issue 2 in one PDF seismic-py: Reading seismic data with Python by Kurt Schwehr Python Papers vol 3, No 2 Entire Volume 3 Issue 2 in one PDF seismic-py: Reading seismic data with Python by Kurt Schwehr Center for Coastal and Ocean Mapping, University of New Hampshire Abstract.. 09.04.2008 18:41 ORBCOM AIS Sat Data From the USCG RDC Highlights (29 Aug 2008): New AIS Satellite Data The long anticipated launch of the ORBCOMM AIS satellite occurred on 19 June. In all, there were six AIS satellites launched. The first being activated is the USCG funded satellite. Initial indications are that the satellite is operating and does receive AIS signals. ORBCOMM has been provided with all the information needed to send the satellite's live AIS data to the R&D Center's server. The R&D Center received the first data in early August. The initial goal is to have a preliminary assessment of the satellite's coverage performance prior to the Technical Exchange on AIS via Satellite (TEXAS) meeting scheduled for 3 and 4 September in the Washington, D.C. area.This looks interesting... looks like other groups use 'Viz' in their software titles. I need to find out more about their Viz Tools. Interim Viz Tools Assessment Completed The visualization tool system AKA, Viz Tools, obtains, consolidates, manages, shares, and displays information on arriving vessels, situational status and daily operations for use by the Sector Miami Sector Command Center (SCC) watch team. Viz Tools consolidates information from USCG enterprise and commercial sources. The RDC has completed a concept evaluation of the software provided to and accessed by SCC watch standers via their standard USCG workstations. The informal assessment demonstrated that this automation effectively boosts SCC watch standers' situational awareness and response planning activities and thereby enhances SCC's operations. The results of the informal assessment are being used by CG-7412 to reduce performance risks in the new USCG Command 21 Program which is procuring data management capabilities similar to those in Viz Tools. Project: Visualization Tools for Situational Awareness and Emergency ResponseWow... I talked about using commercial airlines for airphotos a couple years ago in my blog and now this: ... Another upcoming white paper will explore the concept of non-traditional surveillance assets (outfitting of commercial airlines) as part of sovereign MDA.I was thinking more about over land, but over water works too. 09.04.2008 10:04 UDP with python We have a weather station in our building sending UDP messages to the network. Here is some quickly thrown together python code to listen to UDP messages. It doesn't have all the fancy features, but it illustrates how easy it is to start getting data. I'm using the USCG N-AIS style logging format with a station name and Unix UTC timestamp at the end of each line. Here are the results: #!/usr/bin/env python import socket import time # host='0.0.0.0' # All interfaces device_address = '192.168.8.35' port=4000 buffer = 10000 # sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind((host,port)) # verbose=True # while 1: data,addr = sock.recvfrom(buffer) if addr[0]!=device_address: if verbose: print 'dropping data from ',addr continue if not data: print "No data." break else: timestamp = time.time() print '%s,r%s,%d' % (data.strip(),addr[0],timestamp)And here is a bit of test code to send out a UDP test message: #!/usr/bin/env python import socket UDP_IP="127.0.0.1" UDP_PORT=4000 MESSAGE="Hello, World!" sock = socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM ) # UDP sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) )See also: Here are the results: % ./log-udp.py Date/Time: 8.09.04 14:21:46 01 Reference 652,r192.168.8.35,1220538575 02 Wind Speed Avg. 0.46 m/s,r192.168.8.35,1220538579 03 Wind Gust 0.93 m/s,r192.168.8.35,1220538583 04 Air Temperature 25.32 Deg.C,r192.168.8.35,1220538587 05 Wind Direction 297.10 Deg.,r192.168.8.35,1220538591 Date/Time: 8.09.04 14:22:46 01 Reference 652,r192.168.8.35,1220538635 02 Wind Speed Avg. 0.62 m/s,r192.168.8.35,1220538639 03 Wind Gust 1.55 m/s,r192.168.8.35,1220538643 04 Air Temperature 25.32 Deg.C,r192.168.8.35,1220538647 05 Wind Direction 269.32 Deg.,r192.168.8.35,1220538651 09.04.2008 08:28 Unknown UNH Unknown UNH AT SEA . As one of 30 sea grant institutions in the country UNH is part of a program Congress created in the 1960s for the purpose of marine-based research and education. UNH focuses most of its attention on the Isles of Shoals off the coast of Maine, where its Marine Program operates the Shoals Marine Laboratory in conjunction with Cornell University. In the summer especially, students and professors from across the country make this unique and fascinating ecological zone their home, conducting research and taking classes on a variety of related topics. UNH has made plenty of enduring contributions to marine research; just last February, the university's Center for Coastal and Oceanic Mapping/Joint Hydrographic Center revealed evidence that Alaska's continental slope extends 100 miles farther than previously believed, which may entitle the U.S. to a larger area of natural resources. AND IN SPACE . The space race may be on hiatus but UNH is rocketing skyward in research. The Institute for the Study of Earth, Oceans and Space (EOS) sits alongside Harvard and Princeton as a "high-impact university" for scholarly citations in the fields of geoscience and environmental science. EOS receives millions annually in research grants from federal agencies to conduct its studies. It is the university's largest research initiative, and it has supplied instrumentation to roughly 22 missions - a unique accomplishment, as universities are rarely granted permission to design such hardware. In July, the university held a three-day meeting commemorating the work of NASA's Federation of Earth Science Information Partners. The Federation, of which UNH is a member institution, oversees the use of satellite data to help create a more sustainable planet. 09.03.2008 19:13 Canadian ice sheet breaks loose Huge ice sheet breaks loose in Canada [USA Today / AP] Update Sep 04: More details: The Arctic's "New Reality": Another Ice Shelf Collapses [wired science] A massive 19-square-mile ice shelf in Canada's northern Arctic has broken away from Ellesmere Island, surprising scientists who say the floating ice shelf is another dramatic indication of how warmer temperatures are changing the polar frontier. . Derek Mueller, an Arctic ice shelf specialist at Trent University in Ontario, said Wednesday that the 4,500-year-old Markham Ice Shelf separated in early August and is now drifting into the Arctic Ocean. Update Sep 04: More details: The Arctic's "New Reality": Another Ice Shelf Collapses [wired science] 09.03.2008 08:35 A flower in the garden The zucchini (?) plant in the garden is really going crazy in the garden. It's grabbing a hold of everything else and growing everywhere it can. Last year, I was never able to get one of these started. This year, it's taking care of itself. The weather has been really dry for the last week or more, so I'm having to water frequently. 09.02.2008 19:32 A little more work with CSS A little bit of playing with CSS:. <html> <head> <title>Making pre blocks stand out and an image with a border</title> <style type="text/css"> pre {background: #CCC; border: 1px solid #888; padding: 2mm} img[withborder] {border: 3px solid red} </style> </head> <body> <pre>A paragraph in a box</pre> <img withborder="true" src="ge-s57.png"/> </body> </html>I now realize how crazy it is that I was putting borders around images when CSS can do it and I can later change it without having to modify the source image. I know this is not advanced CSS, but it gets me out of the dark ages of 1994 style html.. img[withgrayborder] { border: 2px solid #666 } Now I can stop doing borders in Photoshop. I just have to add withgrayborder="True" between img and src for any images that need borders. 09.02.2008 10:18 Northwest passage issues Plan on navigating the Northwest Passage? Plan again. [The Maritime blog] The U.S. tanker MANHATTAN navigates the Northwest Passage in 1969, making it the first commercial ship to make the voyage. 09.01.2008 17:23 Which way are we going? Matt and I had a GPS logging camera and an AIS receiver with a GPS logging for this cruise, but the neither camera had a built in compass. How do we know which way we are looking? How about looking across the ships analog compass? . . . . 09.01.2008 17:05 What's new in Python 2.6 We are one month away from Python 2.6. What's New in Python 2.6 is well worth a read. The "with" functionality is very cool for all sorts of programming where cleanup on exit is necessary, but not fun. C++ programmers often do this by putting an object in a new stack frame and then when the stack frame goes away, the object destructor gets called and cleans things up. I first saw this with Ace/Tao by Schmidt for making sure that you release locks. Read the document for lots of other good features. Read the document for lots of other good features. 09.01.2008 15:51 Phx labor day release of images I had the privilege to day to be the one who hit the release image for the Labor Day set of Phoenix press images. There is a spectacular movie of the clouds going by and an image of the trenching. 09.01.2008 15:44 Garden update Finally, the garden is taking hold (at least some of it). Here is a photo from August 28th. _87<< _89<< 09.01.2008 15:39 Hampster during the day Hamsters are fun at night when they roll around the house in their hamster balls, but what do they look like during the day? This guy finally discovered his new house today after it being in his cage for a month. 09.01.2008 08:28 AIS parsing trouble Loic has found two more trouble spots with noaadata parsing AIS messages. I very much appreciate bug reports. I didn't notice that '"' is a validate AIS 6 bit text value for strings: I didn't notice that '"' is a validate AIS 6 bit text value for strings: " 34 0x22 10 0010That means that my database code (which is not up to the python db standards) will put a double quote ("") before the name. Why people put quotes in their name field, Idonno, but I should handle this case properly and I don't. % ./ais_msg_5.py -v -d '!AIVDM,1,1,3,A,544MVC027obuD<u40028lDdP4pTf1T59A<EJ80168@C;36?h0=SPCU1Dh00000000000000,2*7F' shipdata: MessageID: 5 RepeatIndicator: 0 UserID: 273114700 AISversion: 0 IMOnumber: 8904367 callsign: UCOQ@@@ name: "MEKHANIK YARTSEV"@@ shipandcargo: 70 dimA: 66 dimB: 19 dimC: 11 dimD: 3 fixtype: 1 ETAminute: 35 ETAhour: 30 ETAday: 0 ETAmonth: 0 draught: 5.4 destination: NANTES@@@@@@@@@@@@@@ dte: 0 Spare: 0This is one of those messages where you have to know the size to know how many segments are in the message. Turns out that if you don't fill all the blocks, AIS sends fewer bits than a slot. This reduces the chances that you will have bit errors in your message. Shorter messages are supposed to be a good thing and I've heard people say that 5 slot messages are a really bad idea. % ./ais_msg_15.py -v -d '!AIVDM,1,1,,A,?03OvkiGRP7P000,2*31' Traceback (most recent call last): File "./ais_msg_15.py", line 902, in <module> printFields(decode(bv) File "./ais_msg_15.py", line 186, in decode r['MessageID2']=int(bv[126:132]) File "/Users/loic/Development/Marine/_AISFON/noaadata-py-0.40/ais/BitVector.py", line 1080, in __getslice__ return BitVector( bitlist = slicebits ) #(c6) File "/Users/loic/Development/Marine/_AISFON/noaadata-py-0.40/ais/BitVector.py", line 725, in __init__ raise ValueError("wrong arg(s) for constructor") #(A68) ValueError: wrong arg(s) for constructor 09.01.2008 06:47 USGS Gustav Water Levels Note that red squares are sensors that are not real time. USGS Gustav Hydrologic Impacts map page NOAA Gustav Page USGS Gustav Hydrologic Impacts map page NOAA Gustav Page
http://schwehr.org/blog/archives/2008-09.html
CC-MAIN-2017-30
refinedweb
11,267
66.03
MAY 2012 (Knocking on door). RETRO RELICS POET & WRITER OPEN MIKE Tuesday, May 8, 7 pm MAKING A CONTRIBUTION... The mission of Northern Groove is to get people from in and around our community involved, aware, and connected with all of the amazing things that are happening locally within the world of arts and culture in the North Peace. MEET THE PEOPLE BETWEEN THE PAGES THIS MONTH... If you have an idea for an article, are planning an event, or have an idea or suggestion: editor@northerngroove.com TAKE THE MONEY AND RUN (ADVERTISING): Russell Eggleston | russell@northerngroove.com Ah, who needs friends when you have Facebook: “northern grooveâ€? SHU BA DA DU MA MA MA MA (LAYOUT & DESIGN): Mark Bodner, Image Build Team | info@imagebuild.ca Do Twitters twit or twits Twitter?: twitter.com/ northerngroove BIG BOSS MAN (PUBLISHER): Russell Eggleston | russell@northerngroove.com No icky envelope licking required: publisher@ northerngroove.com PUBLISHED MONTHLY BY: Russell Eggleston Creative Services | RR1 Site 16 Comp. 30 Fort St. John, BC V1J 4M6 Who you gonna call? OK, after the Ghostbusters and escorts, add us to the list: 250.663.8851 Local events, musings, meanderings of the mind and other bits of joy: northerngroove.com Northern Groove Magazine is published monthly and is distributed free of charge in Fort St. John, BC, Canada. Northern Groove Magazine and assume no responsibility for the truth or accuracy in advertisements. Northern Groove Magazine attempts to accurately publish all editorial and advertising content, but errors and omissions may occur. Northern Groove Magazine disclaims any responsibility for such errors or omissions. Statements, opinions, and points of view expressed by the writers and advertisers are not necessarily those of the publisher. All rights reserved, except where expressly waived. The information in this publication is provided as a public service. Although we endeavour to ensure that the information is as current and accurate as possible, errors do occasionally occur. As some information is supplied by third parties and may be subject to change, we cannot always guarantee its accuracy. Where possible, readers should verify the information before acting on it. 4 northerngroove.com Enjoy the entertainment for free. We never have a cover charge - while enjoying great food and a cold beverage. When the show is over, try your luck on the slots. Funny stuff. Join us for comedy monthly direct from Yuk Yuk’s! Ultimate viewing spot! We are your number one spot to watch UFC action! Under the B... Big Bingo. Big Fun. Where music can be appreciated LIVE AT THE BREAKFAST ROOM PETER KATZ FRIDAY MAY 18 & SATURDAY MAY 19 . 7:30PM TIX INFO @ northerngroove.com SUPPORTING MUSIC SUPPORTS OTHERS russell eggleston’s 4 page editorial This previous month seemed to have been jam -acked with some incredible events. To me, it’s been one heck of an inspiring month. From the visuals to the audio, each of these events look and sounded as different as different can get. The music at each of these events ran the gamut from metal, to folk, to 70’s rock ‘n roll, to hip-hop, electronic and everything in between. No kidding. First, imagine you’re at On The Rocks watching Milking Chung (one of Fort St. John’s hardest working metal bands). It is extremely loud, aggressive, and everything that a great metal show should be. Everyone in the room is 100% into it. Fists pump the air. They seriously melted the paint from the walls with their incredibly heavy sound for the Pat Flintoff “No Pitty” fundraiser event. 6 northerngroove.com Next, imagine being instantly teleported to the Taylor Hall to attend the fundraiser for Dylan Moh art. Twin Peaks singing folk music on the ukulele and piano, friends and family are talking and telling stories around tables, and there’s a dance about to begin. Give n the contrast between the two events, you’d probably think that they were on different planets. If I were to find a commonality betw een these two events, it would be in that there is music and there is dancing. I’d say this is a constant for pretty much every event. It’s what people do when they we get toget her. Where there’s a cause to get together for...there is musi c and there is dance. Feet move and fun is had by all. MAY 2012 7 ds extremely The music and dancing looks and soun different from event to event... / celebration feaPat Flintoff’s “No Pitty” fundraiser Milking Chung, like acts local tured all kinds of great and some last Chaotic Justice, Subconscious Pilot, Bobby Swanson, minute performances by Prod Deuce, was up on the yone DJ Ghost, and many more. Ever two-stepping! n’t were inly certa they and , dance floor a good rock / of y energ the like There’s nothing quite metal / hip-hop show! t to check out Recently I’ve also been making an effor s put on by show ronic elect dible incre the ort and supp uctions] Prod Sam ous [Seri ay folks like Sam Stanw Productions]. and Joy Larstone [Wake the Funk Up rd any of these Everyone might have a slight bias towa you’re in the particular styles of music, but next time bit “outside little a be t migh that t even an of vicinity much fun how the of note take ”, of your comfort zone everyone is having! music spectrum. Now...flipping to the other side of the people having a were there r raise fund pel’s Rem At Dan Craig Brooks, of c musi the to ing great time two-stepp t playing all the Kyle McKearney, and Clint Giesbrech classics on acoustic guitars. 8 northerngroove.com Over the last 5 or so years I’ve been able to attend hundreds and hundreds of events. In fact, I’ve loosely been keeping track and (if my math is right) I should be over the one-thousand show mark sometime this year. The most amazing thing about attending so many events is that no matter how different each event looks, they all function and operate basically in the same way. Given every single difference in music, aesthetics, how people dress, and how people dance, all of these events provide the same great feeling of support, community, and celebration. was able to attend this This was true of every single event I for pretty much every comtrue ably prob is previous month, and in Fort St. John. size munity gathering of any sort and ion in this article, it If there is to be any sort of a call-to-act time to participate in take to and t effor an make to be d woul listening. See you on the for ks Than ! these like community events dance floor. Home of Fort St. John’s longest running OPEN MIC with Russell Eggleston every wednesday 8pm live lives where mu sic local SUPER TIMES IN THE SUPER 8 {250 263 9991} MAY 2012 9 sharing the stage with sue popesku Welcoming back a home town boy who has made a name for himself in professional theatre is a proud moment for the Peace River Zone Theatre Festival and the theatre community in Fort St. John. Such is the case with the adjudicator for the theatre festival coming up May 16-20, when Josue Laboucane returns to Fort St. John. Josue will share his knowledge and expertise with participants of the theatre festival at an acting workshop on May 15 before the Festival gets into full swing on Wednesday. Each year a professional actor and/or director is invited to adjudicate the plays in the regional theatre festival which can include plays from the communities of Fort Nelson, Chetwynd, Dawson Creek, Tumbler Ridge, Hudson’s Hope and Fort St. John. Community theatre groups participate in the Peace River Zone Theatre Festival and one play can be chosen to represent the zone at the provincial competition in Kamloops in early July. Josue grew up in Fort St. John taking part in school and community theatre productions. He is now a professional actor and teacher of theatre in Vancouver ,after graduating from Studio 58 theatre program at Langara College in 2005 and Vancouver Film School Acting program in 2001. He is a teacher, director, and mask designer. As a career actor, he is a regular at Carousel Theatre and has worked with Relephant Theatre and Axis Theatre. He spent last summer as King Henry with Bard on the Beach in his fourth season with the popular summer theatre company. Josue has garnered 5 Jessie Richardson Theatre award nominations and shares one Jessie award with the ensemble of The Emperor’s New Threads. He has directed Gerty! Live and In Concert! (BC Buds Festival); Confessions (Alley Theatre); and Letter from a Soldier (Walking Fish Festival). Josue teaches at various institutions around Vancouver including the Vancouver Film School, Theatre Terrific, and Carousel Theatre and Bard on the Beach. The long list of shows and film shorts that Josue has worked in appears to be an amazing amount of theatre work since 2001. He is also a past participant of the Canadian National Voice Intensive. Josue specializes in a number of areas that he shows exceptional talents. Among his honed and natural skills are a baritone voice, mime, mask, mask making, puppetry, stage combat, Shotokan Karate Blue Belt. When you take care of yourself everyone benefits... Give yourself the gift of relaxation by booking your massage, facial or pedicure today! 250-785-0263 I’VE GOT IT COVERED... words fay willis & henry see pix russell eggleston 12 northerngroove.com It begins with the wonderful people in my life,” says Fay Willis as she reminisces about the beautiful leather wrap she made for Johnny Lightnin’. Fay is an accomplished leather worker. She is also passionate about music. Her handiwork adorns guitar straps worn by local musicians as well as some big names in Canada and the US (Shooter Jennings to name but one). Beautiful as they are, it is the wrap that envelopes Johnny’s Gibson Les Paul that best represents Fay’s work and Fay herself. She wrote about it for Northern Groove. I recently covered a Gibson Les Paul in leather for a soul brother of mine, Johnny Lightnin’. My first thought was of my initial “hint” to Johnny about my desire to try my hand at wrapping a guitar (hint, hint) in a Waylon-style, Frazer-style kinda thing. After sorting out my thoughts and feelings on how this guitar wrap came to be, I realized there were many different levels and reasons. Like anything else, it started with an idea, a very general idea. Then it took faith, patience and the complete trust of an amazing soul brother. The actual concept for the guitar was over a year in the making (sorry, Lightnin’). I tossed around many ideas in my mind until I knew exactly what it needed to be: the epic wingman for my friend; a pirate-spirited bad-ass soul held together by the belief of pure freedom; the relentless journey of a truth-seeker. By the end of my challenge it was about inspiration, creativity, trust, love, friendship, patience, challenging oneself and always the love of music. I am truly blessed by the souls that inspire me and fill my world with love and light. Johnny uttered not a word of impatience or criticism the whole time I had his treasured Les Paul. I was so overwhelmed by the thought of having it in my possession, with the big shoes needed for the task of covering such a thing of beauty. With time and thought, I do believe I did it justice. I am proud to have created something my friend can enjoy even more than he has in previous years. Ultimately, one of the favourite parts of my passion for the art of leather craft is watching people enjoy and use the final product. Start to finish, the process makes my soul sing. Make Mom’s day with a visit to Isabelle’s! All bath, giſt�are & nighties on sale. Bra fitting sale! Buy one fashion bra, get a second 40% off ... a Tea Par�� Hat st�ffed with goodies! In the Totem Mall . 250 785 8070 GARDEN MAGIC amy furman My six-year-old son wants to be a farmer when he grows up. His plans include an elaborate irrigation system and a store to sell his organic produce and homemade goodies like pies and jam. He knows it will be a lot of work but is determined to be successful with the help of his “wives”. A mother couldn’t be prouder. Apart from the polygamy, of course. Participating in the family garden has no doubt sparked his interest in producing food. He has sown the seeds, watered, weeded and harvested. He has witnessed firsthand how sunlight, earth, water and poop (super exciting!) transform a seed into fuel for our bodies, as if by magic. As a society, we’ve become disconnected from the land and from the source of our food. Hunting, gathering or growing food is a primal part of being human. Reclaiming that connection can be a stepping stone in redesigning our lives to more fully express our being. Want to begin the journey into producing your own food? If you’re not ready to plow the back forty, here are a few easy options. Every significant lifestyle change starts with one small step. For our family, exploring how to grow our own veggie patch on our own land has led us farther down the path to creating our ideal lives. Just as a seed planted in your garden germinates and grows, the seed of a life changing idea can spark your own magical transformation. REAL-LIVE YOGA. REAL-LIVE LIFE randelle lusk Owning a yoga studio and teaching the majority of the daily classes doesn’t leave me much room to attend class as a student. As an alternative I maintain the majority of my personal yoga practice by following yoga videos lead by some of my favorite teachers from across the continent. These teachers are gifted and the sequencing of the classes and the thought processes behind the production of the videos is genius. However it just doesn’t quite compare to standing in a class full of people, sharing a collective energy and moving under the guidance of a real-time teacher with a real-life voice. With this in mind, I have been making a point of attending the studio’s classes, which I’m not slotted to teach. Stepping into the shoes of a student under the direction of our very own Ashley Barks has been a delightful experience… for the most part ;) Though she has only been teaching for just year now, she has the ability to make me work my mind and body to a point of purging. Having a teacher guiding my practice keeps me in check, reminding me of the technical and alignment elements of each position. She handles her role as a teacher with finesse, calling me out on my moments of laziness. This is where the purging comes in. Sometimes I want to be lazy; I want to cheat and let my ribs flare out. Sometimes, when I’m left in a pose like downward dog, for what seems like a freaking eternity, I regress to my childhood. As beads of sweat pool between my shoulder blades, my mind starts to take over, manipulating my body with emotions of anger and frustration. I want to snap and throw myself onto the floor like a five-year-old in a tempertantrum. I want to pour myself into the corner and sulk for the rest of class. But then, I’m gently reminded of my breath. I listen. I begin to breathe out my emotions and my body settles into the pose. When the signal comes to change positions I feel amazing – lighter, my shoulders feel better than ever; my whole body sings. It is often said that what we experience on the mat prepares to handle life and it’s unpleasant situations off of the mat. In life we sometimes find ourselves in tight spots where we feel vulnerable and uncomfortable; we feel anger and fear. And sometimes we feel like giving up. When we learn to breathe in yoga, we are essentially practicing to breathe in the real world. Breathing is an incredible tool that helps us release nagging thoughts and doubt, it helps us to be calm and present in all situations. We can’t run around avoiding the tough things in life, after all it is discomfort and dis-ease that coaxes us to change and makes us grow. So, stick with it. And breathe. ~Randelle Challenge yourself! Under the Yoga Tree is hosting its next 30-Day Yoga Challenge May 22nd to June 20th. Contact the studio for more information. Next 4-Week Beginner Yoga Program, May 8th – 31st, Tues & Thurs @ 5:45pm $135 Under the Yoga Tree offers and extensive yoga schedule for all levels, with public classes offered 7 days a week. For and up-to-date schedule visit www. undertheyogatree.ca Private and Corporate sessions available. Contact Randelle Lusk, E-RYT 200 for more information: 250.263.5828 | randelle@undertheyogatree.ca The only commercial coffee roaster in the North Peace makes a big splash. At Patch Java Coffee House we feel so good about what we do, we did it again! Come join us at our second location in the North Peace Leisure Pool. We still offer our same fresh, locally roasted coffee, smoothies, ice cream ice capps, and various other beverages! 10430 100th Street SUMMER HOURS: Mon - Fri: 6am - 6pm Sat: 8am - 4pm Sun: 10am - 4pm 250 261 6648 Now at the North Peace Leisure Pool Mon - Fri: 10am - 10pm Sat: 9am - 9pm Sun: 1pm - 5pm We are also offering our sensational panini sandwiches, fresh daily soups, and delectable goodies that you have all come to love. One Last thing. We are open late all week at Patch Java II at the Leisure Pool. 10:00am to 10:00pm Weekdays, 9:00am to 9:00pm Saturday, and 1:00-5:00pm Sunday! Come take a dip and enjoy a fast, fresh lunch today! Follow us on Twitter/PatchJava or Facebook for our daily lunch specials at both locations! Devon Wigglesworth Owner, Patch Java Sunday Monday Tuesday Wedn Special Olympics Regional Qualifier Aquatics Sunday May 6 NP Leisure Pool WICWP Community Cultural Celebration Sun May 6 Lido Theatre 3:00pm - 5:00pm Unto Him with Guests Lori Kachowski and Caroline Napolean Sun May 6 | NPCC 7:00pm doors Hmm. Is Monday really this events boring that we have no to fill up this space? going do you have an event and on that’s not listed here Or should be? an maybe you know about , but you event that isn’t yours list. feel it should be on this Or, Spread the Word - Open Mic for Poets & WRiters Tue May 8 | Retro Relics 7:00pm Egan’s Open Every Wednesd Egan’s Pub | 8: Any way you shake a stick at event, it, we’d like to see your t that their event, or any even on this needs bums in seats Rotary Mother’s Day 5K Run & Walk Sun May 13 Surerus Fields Register @ 8:30am eventlist. northerngroove.com to us know find out how you can let the details, or email ve.com publisher@northerngroo Visit Strawberry Jam Tue May 1 | Lido Theatre 7:00pm doors THINGS YOU NEED TO KNOW THAT WE DON’T CONTROL: THE EXACT FLAVOR OF FLAVOR FLAV, OR IF IT’S “FLAVOUR” TO SOME AND “FLAVOR” TO OTHERS, IF MAMA ACTUALLY KIN, WHO DOESN’T SHOW UP FOR WORK ON 4:21, WHO PICKS THE MUSIC IN ELEVATORS, ANYONE WHO USES “CONVENIENTLY LOCATED” IN THEIR ADVERTISING THAT ISN’T CONVENIENTLY LOCATED RIGHT OUTSIDE YOUR FRONT DOOR (REALLY, THE ONLY THING EVER CONVENIENTLY LOCATED IS THE HOTDOG CART OUTSIDE YOUR FAVOURITE WATERING HOLE AT 2AM). Events are published on a “first come-first put on this list” basis. Make sure you get your event onto the Groove website, too! That way if someone asks us “Hey, do you know if such and such is going on?” We can answer with “It’s probably on the Northern Groove events calendar.” And they’ll say “Wow, that’s awesome. How do I find it?” We reply, “Easy. Just go to northerngroove dot calm and click on Local Events. If the event isn’t there, shame on the organizer for forgetting to tell us since we aren’t all knowing and all seeing. Yet.” Event times and dates are subject to change at any point, check with venue to ensure accuracy of information. For the most current event list: northerngroove.com A Name Unhe Tour 2012 Wednesday Ma Egan’s Pub | 8: Municipal Gov Buddy Wasisname Other Fellers Tue May 8 | NPCC 7:30pm doors and the Wednesday May Centennial Park 4:00pm-8:00pm nesday Thursday Friday The Led Zeppelin Show Thurs May 3 Lido Theatre Doors 7:00pm Show 8:00pm Legally Blonde - The Musical: Stage North’s Death & the Walter & Zipcuts Thurs May 3 NPCC | 7:30pm Fri May 4 Egan’s Pub 8:00pm open auditions Fri May 4 & Sat May 5 NPCC | 6:00pm maiden Mic Karaoke Spring vernment Day Stage North’s Death & the maiden Sat May 5 NPCC | 7:30pm Peter Katz at the Breakfast Room Fri May 4 NPCC | 7:30pm Sat May 19 Pomeroy Hotel 7:30pm doors Sean Hogan Friday May 11 NPCC | 7:30pm Lee Aaron with guest Darcy Bailey Families Thurs May 10 Lido Theatre 7:00pm doors Fri May 11 | Duncan Cran Elementary School 6:00pm in Special Olympics Regional Qualifier Aquatics Saturday May 5 NP Leisure Pool Stage North’s Death & the maiden SD60 Band Spring Concert Thurs May 10 | NPCC 7:00pm ay 9 :00pm y 30 k m at the Stonebridge Every Wednesday Stonebridge Hotel 8:00pm day :00pm eard Night the Saturday Motion Harlequin Peter Katz at the Breakfast Room Thurs May 24 Lido Theatre 7:00pm doors Fri May 18 Pomeroy Hotel 7:30pm doors Comedy Detour with Scott Belford and Dave Dempsey Fri May 25 Lido Theatre 7:00pm doors Comedy Detour with Scott Belford and Dave Dempsey Fri May 25 Lido Theatre 7:00pm doors Bluey Day Sat May 26 Ambulance Bays BE DISTURBED... BE ENLIGHTENED sue popesku Live theatre is meant to inspire, amuse, provoke and disturb. Theatre festivals are often designed so that each entry relates to a pre-described theme. The Peace River Zone Theatre Festival has never designed the annual zone festival to follow a theme in the past but this year’s entries seem to adhere to a common thread of human misery caused by human social and political ills. The audiences first reactions will be “disturbing” toward each of the stories told through the plays at this year’s Peace River Zone Theatre Festival May 16-20. Bullying, violence and torture are part of our lives through personal experience or daily news reports. How we cope with bad things in our lives is what makes us human, gives us strength and renews our hope that others may not have to suffer what we have endured. Each of the plays tells an emotional story drawing us into the fear and sadness of the suffering but leads us through a maze of emotions to a glimmering of hope and salvation. ART SALES & TATTOOS BY PAIGE JOHNS AND AMY GOTHARD. TATTOOS $100/HR 250-263-1196 ! endurance89@hotmail.com ! 303-9711 100th Avenue in the Re/Max Building Tues. May 15 Acting Workshop with Adjudicator Josue Laboucane 6 -9pm NPCC Wed. May 16 Hockey Mom, Hockey Dad, Director Launching the Festival Dallas Ashdown 7:30pm Coffee Critique 10am Thurs on Wednesday, May 16 is Hockey Mom, Hockey Thurs. May 17 Dog Sees God, Director Chalene Scot Dad by Michael Melski. t 7:30pm Coffee Critique 10am Fri. Two single parents, Donna and Teddy engage Fri. May 18 Death and the Maiden, Director Rob in the courtship game Laventure 7:30pm Coffee Critique 10am Sat while cheering their eight year old children on at the Sat. May 19 Annual General Meeting for Peac hockey rink. Teddy is a e River Zone 7:30pm 12:30 -2pm NPCC voluble extrovert who encourages his son’s losing Sat. May 19 Meet and Greet NPCC, 6:00pm - 7:30p team to hit first and think m 7:30pm Awards Evening and NPSS Showcase later, and he coaches Play Social at Who le Wheat and Honey after the show Troy from the stands to be the “enforcer”. Sun. May 20 Winning Play Workshop with Josu Donna, shell-shocked e Laboucane 1pm-5pm from a violent marriage, is appalled by the physical violence on the ice. This romantic comedy takes a serious look at violence On Saturday, May 19, the gala evening begins with a in the hockey rink. This show is directed by Dallas Meet and Greet 6:00-7:30pm followed by the North Ashdown and is a Stage North club entry. Peace Secondary School drama class showcase play. \ A new theatre club, dubbed the Spectacular Chair Rounding out the evening are the festival awards Factory, entered Dog Sees God by Bert V. Royal on presented for best actor, actress, set, costumes and Thursday, May 17. When Charlie Brown’s dog dies more. One play may be selected by the adjudicator from rabies, Charlie Brown begins to question the to represent the Peace River Zone at the provincial existence of an afterlife. His best friend is too burnt theatre competition at Mainstage in July in Kamloops. out to provide any coherent speculation; his sister has A social gathering at Whole Wheat and Honey Café gone “goth”; his ex-girlfriend has recently been institops off the evening. tutionalized; and his other friends are too inebriated to give him any sort of solace. But a chance meeting Come out to a great week of plays at this year’s Peace with an artistic kid, the target of this group’s bullying, River Zone Theatre Festival! offers Charlie Brown peace of mind and sets in motion a friendship that will push teen angst to the very limits with drug use, suicide, eating disorders and teen violence. Chalene Scott is directing this show. Rob Laventure is directing Death and the Maiden by Ariel Dorfman on Friday, May 18.ine’s husband is torn between his wife and the law, ad Dr Miranda is forced to endure captivity while the husband and wife seek out the uncertain truth about the clouded past. This dramatic play is extremely intense and emotional with the characters unrepentant and believing the perceived verdict of guilty beyond a reasonable doubt. The truth, however, lies in the balance. This show is a second Stage north entry. AVAILABLE TWICE MONTHLY...CHECK YOUR MAILBOX REAL ESTATE MARKETPLACE serving fort st john & surrounding area | presented by Terry Isenbecker Terry Isenbecker Energy Realty Ltd. 250.261.6111 . whatuneed.ca Each office is independently owned and operated. RUNNIN’ DOWN A DREAM too old for what? dale hillman Have you ever heard people say, “You should have started on this when you were a kid!” “Anyone who is any good started on a dream like this in their early years, or at least in their teens.” “It’s too late for that, what are you thinking?” In my case, the “dream” refers to music, something that has been a part of my life as far back as I can remember. I’m sure I knew who Hank Williams, Hank Snow and Johnny Horton - loved by my parents - were while I was still in the womb floating around formulating who I would become. Ironically, I’m not the world’s greatest country music fan, but the love for all kinds of music has been inside of me since I came to be. From memorizing the song lyrics out of the Hit Parade magazines that flourished when I was a kid, to being part of the Junior and Senior High School bands, playing music was a huge part of my life. That is, until I had to enter the “working” world, when there only seemed to be time to listen to music but not play anymore. A sad mistaken belief that I still reflect on with some regret today. wicked sometimes you need to NORTHGATE MALL . MARCJOSEPHONLINE.COM . 250 261.6367 In 1975, at the age of 28, my life took a turn from being in a longtime relationship, to becoming a newly singled young man. Given that it was the 70’s - I immediately bought a guitar, thinking I could learn to play and put some music to the thoughts that had been running around inside my head. I was going to become a singer/songwriter! Ya, that’s the ticket...a singer/ songwriter! I think back and wonder how good I would be now if I had but practiced at least one hour a day every day since then. Of course, work stepped in again as I needed to take care of myself and once again, music took a back seat. So as not to bore you with another 35 years of a pretty incredible life, and to actually get to the point of this tale, it is never too late for anything! While I have worked more with music over the last ten years, it is only now after being retired for just over a year, that I have become more serious about this “dream” that began so many years ago...singer/ songwriter! Through the support and love of family and friends who make you believe in yourself, it has become apparent that this music dream is a very real possibility. It is something to be taken outside the back bedroom/music room and to more ears than my kids and best friends! At the age of 65 and with the most incredible opportunity offered to me by the amazing Dayna Manning, I opened for her and Ryan McMahon at a recent Whole Wheat & Honey show. It has begun! I have a sense of direction and know what needs to be done. You can run down a dream if you just follow your heart, never forget where you came from and cherish your friends and family, always letting them be a part of that dream! While we never know how long life will keep us around, I know that the rest of my time will be enriched with the creativity of music. I am thankful to so many, not all of whom will know that they somehow inspired and encouraged me. What is your dream? No, you are never too old to realize it, age being a chronological thing only, compared to your state of mind. My friend Jenn said it best, “DO IT”! 2012 Rockin' the Peace winners Twin Peaks FRIDAY MAY 25 | MUSIC @ 8PM CARE TACTICS tony warriner In a world full of people who couldn’t care less, be someone who couldn’t care more. ~Author Unknown As a church community, we have been processing what it means to love your neighbour as yourself (Jesus’ words), or maybe better put, we’ve been haunted by those words. When asked why we do events like Candy Planet or programs like the backto-back creative arts workshops we’ve been hosting (most recently with Rik Leaf on spoken word), our response is that we just want to “love on our city”, or make it the best place to live. We have a dream for this place that includes selfless love, overflowing joy, deep contentment, relentless kindness - need I go on? And getting there is about serving one another, practicing selfless generosity - loving our neighbour. And I’m reasonably pleased with how we express this loving-our-neighbor-as-ourselves in our own community. But the concept of caring for our neighbour is definitely expanding for us. In some ways, it feels like our insides are being ripped out for the great need in our planet (some call that compassion). Our community, it seems, is being exposed over and over again to the hurt, pain, hunger, and hopelessness of millions of people that share this little corner of the galaxy we call Earth. Most recently, we sent a group of 25 to Vicente Guerrero, Mexico to build a couple of homes for otherwise homeless families. It was awesome, like a mini-version of Extreme Home Makeover, except these people weren’t relatively comfortable Americans with pretty nice homes already. One family of six was living in an old car, the other in a one bedroom shack made of miscellaneous materials including tarps, shed doors, and plastic wrapping. No water, electricity, or plumbing. When we handed each family the keys to their new home, it was pure ecstasy for us on one hand, but seeing these people living off about $10 or less per day, was just breaking us apart. Some of our team could barely hold it together, as we seemed to connect to the pain of our “neighbours” on a whole new level. Beautiful friendships were formed with these Oaxacan people, though we did not know one another’s languages. We want to be people that truly care for our neighbour, whether next door or next-continent. Many of us took the Below the Line challenge to raise awareness of the 3 billion people in our world that struggle to live off $2 per day or less. Proceeds saved from living below the line for three days went directly to battling global poverty. One of the highlights for me was when a young guy (16 years of age) went and bought a water buffalo for a family in northern India! In a society like ours that is increasingly turning inward, completely caught up with trying to survive, becoming less and less concerned about the welfare of others, and consumed with personal comfort, safety and well-being, the 400 people that call Evangel their church are having their eyes turned to the world around them. First Fort St. John, then all the way to world’s end, places like Visag, India or Vicente Gurerro, Mexico. And this movement-to-action is certainly not limited to our church. I love what’s happening in our local high school, as a group of students under the leadership of my friend Derrick Laychuk, just recently ventured into Ghana, recognizing that those people, on the other side of the planet, are our neighbours and that we are responsible to care for them, to look out for them, and to use our wealth and resources to alleviate their suffering and poverty. Or how about Mike Friesen from MC Rehabilitation and Wellness, where they can’t settle for simply running a thriving business, but want to use their abilities and resources to help people in the most impoverished countries of Africa (a future trip is in the works to teach the people there how to do what MC Rehab does here in FSJ). Others in our community are make a difference with local activities like the “pass it on” initiative or the upcoming Bluey Days (May 26) to raise support for people with cancer or other serious illness. Another idea that’s cropped up is the “unbirthday” where you turn the concept of having a birthday party inside out and give away rather than receive. I like it. And I hope this is just the beginning of a new way of living for us. For more info on The Below the Line Challenge or to discover some of the ways Evangel is reaching out to the world, visit evangelfsj.com. If you want others to be happy, practice compassion. If you want to be happy, practice compassion. ~Dalai Lama peace river north L A V I T FOFETS HE ARTS margaret may volunteers conwith teachers, families and cers and musicians, along Peace River dan the for ers, d sing 22n of to h eds 15t ndr ril Hu l Centre the week of Ap tura Cul ce Pea . rth nity No mu verged on the ing arts in our com s, a celebration of perform North Festival of the Art nt y the festival is so importa s, we remember again wh zer and ani g, org nin and trai s and eer e unt For festival vol e after months of practic ished perperformers take the stag pol ng into you rm see sfo we tran en n wh ldre us to vous chi spotlight. We watch as ner when a performance have their moment in the smiles of pride and relief see We e. stag the e etime do. tak y formers as soon as the s, as, inevitably, they som intment when it stumble ppo disa of s tear few a l, goes wel gling off the little pianist with legs dan ry size and age¸ from the soned performeve of sea ers ady form alre per are o see wh We first festival, to teenagers y ver ir the years old, to in r g fou yin y pla onl piano bench dancer who was ir skills; from the tiny tap her last Peace River in er ght dau his ers amazing us all with the h wit dance so he could perform d our first ever classes in the dad who learned a tap no of all styles. We enjoye pia rful nde wo rd h the adjudicator, hea We North Festival. g” after a few minutes wit s that turned into “amazin We were treated l. iva fest the in n isio banjo, “good” violin solo in the fastest growing div tar gui r of the Light ula rge pop Cha and l the and classica ring recitation of sing band music and a stir h. ngt stre and uty bea to beautiful singing, rou ce, gra h physically impossible wit Brigade. Dancers did the , talented performa sample of the wonderful e Best of the Fest”, just for next year’s ing par pre rk, wo at And then, at the end, “Th k, who will soon be hard wee the ugh thro saw ers that we festival. EXCITEMENT BUILDS as construction nears completion on hospital and residential care project written by joanne macdonald & mike bebbington | As the opening of the new Fort St. John Hospital and Peace Villa Residential Care draws near, Mike Bebbington, Senior Project Manager, Acciona Infrastructures Canada Inc., says it seems like only yesterday when they first learned that the Acciona/Stuart Olson Dominion Joint Venture team won the competition to design and construct the new facilities. Construction began on the $301.8 million project in June 2009. Bebbington noted that 36 months later, “We are now in the final phases of commissioning prior to handing the facility over to Northern Health ready for use.” The project, which includes $98.0 million in capital funding from the Peace River Regional Hospital District, is being built on a 40-acre parcel of land donated by the City of Fort St. John. The project is a public-private partnership between Northern Health and ISL Health, the private sector partner leading the consortium of architects, designers and builders, including the Acciona/Stuart Olson Dominion Joint Venture and HCP Social Infrastructure (Canada) Ltd., that have partnered with Northern Health. ISL Health was selected to deliver the project by Northern Health with assistance from Partnerships BC. pictures by tom sparrow During the month of May, the facility’s landscaping will be completed, final signage will be installed, and the temporary construction offices will be taken off-site. The hospital and residential care facilities have been: Designed and built to Leadership in Energy and Environmental Design (LEED) Gold standards; Built to post-disaster building standards, which means the facilities will continue to function independently after a disaster; and Built to operate at a guaranteed energy consumption level. Bebbington said the project was unique in many ways. “We had to schedule construction activities around weather conditions, select products for the exterior of the building that could handle the weather extremes of plus 30 to minus 50, and also take into consideration the location for deliveries and for workers’ travel, in and out of the site,” said Bebbington. The $301.8 million Fort St. John Hospital & Residential Care Facility is on track to open in the summer of 2012. 28 northerngroove.com “With most builds, any contractor can build and most designers can design to ensure that the end product is satisfactory to the client. However, at Fort St John, we set up a unique design user group process and local neighbourhood community meetings which allowed ISL Health to involve all the expert specialists available at Northern Health as well as the community. This ensured that the facility was custom-built for its purpose and meets the needs of the local community. I believe we all have something to celebrate.” said Hurlbut. He added that during the project’s busiest periods, there were more than 360 workers engaged on the site, with more than one million man hours worked on the project. “The first winter, we had to protect all of the foundations against frost and frost heave. To do this we heated the ground and covered it with insulation tarps for the entire winter. We also had particular transport problems. Nobody ever accounted for incidents involving trucks and moose that resulted in five-day delays in deliveries twice within the project period.” Gareth Hurlbut, General Manager, ISL Health, said he believed the special partnership between ISL Health and Northern Health also contributed to make the project unique. “I would particularly like to thank Mike Bebbington our Senior Project Manager from Acciona Infrastructures Canada Inc., and Glen Kelsey, our Design Manager from Stuart Olson Dominion, who have both been with the project from the start and have shown great dedication to building wonderful new facilities for the community of Fort St John.” Bebbington added that the facilities’ state-of-the art construction standards will support Fort St. John and the surrounding communities for years to come. “Our joint consortium group would like to thank the people of Fort St. John for their help, hospitality and friendship,” he said. “This was a truly international project with people coming to work from Australia, Spain, Mexico, the United Kingdom, Hong Kong, the Philippines, Poland, Switzerland, Sweden, and the United States. Some of the people were introduced to minus 40 for the first time in their lives!” isl health FORT ST JOHN-ISMS EXPLAINED j. adam kelderman Hi! My name is John Adam Kelderman (I go by Adam) and I’ve lived here in the North Peace, for going on six years. I moved here with my wife and daughter from Halifax, Nova Scotia in 2006 and have always enjoyed writing prose fiction. I have a Bachelor of Arts degree in Creative Writing from St. Mary’s University where, in 2004, I was chosen to attend a Canada-wide summit of young writers in St John’s Newfoundland. There I had the pleasure and privilege of working with several veteran Canadian writers like Leo McKay Jr, Bernice Morgan and Boyd Chubbs. (100) In the past I’ve attended many workshops where postcard or flash-fiction stories were always great practice for tightening up a narrative. Fitting an entire story into one or two paragraphs can be difficult. One must rescale: it’s not a novel, where there is endless room to flush out full backstories and to explore dynamic character development. I’ve learned that although the goal is to be clear and succinct, you must also leave some blanks for your reader to fill. For example, Ernest Hemingway was asked to write a six-word story and he replied, “ For sale: baby shoes, never worn.” (100) To supplement the monthly printed material we’ve set up a sister site where contributors can see their submissions posted online. If by the 15th of each month there are enough submissions, the website will post them all, and the best ones will be chosen to be printed in the magazine. Also, we’ve established an email address specifically for this program, so anyone who wants to can send feedback, drafts of future submissions for review, and especially your final contribution. Please understand this project is in its infancy and so it may take a few months for it to take shape. (100) The project goal is to bring together as many different perspectives into a literary portrait of Fort St. John. We are extremely flexible on the format. Any genre, position, approach is accepted. If for example you have a great sci-fi story, that could only happen in Fort St John and it’s exactly one hundred words, we’ll read it, post it and possibly print it in the ‘zine! As working editor, I have to make sure each contribution is exactly one hundred words and if they are not, you will be notified: no one’s going to edit your story for you. (100) The FORT ST JOHN-ISMS project presents a great opportunity for writers to connect with their community, and share what they know. Which reminds us that we also have to take time to mention locally related events, and links to this project. Make sure to join the Writer’s Workshop held on the second Tuesday evening of every month at the Rabbit Hole Book Store, hosted by Henry See; and drop by Unforgettable Memories to see what inspirations you can find there for your craft! Dawn at the Northern Lights College has more information about creative writing as an academic pursuit, too. (100) BADVERTISING ite s we bs WE MA KE .g rap h ics OU .b RM roc hu res AR KI .p os Was your website designed when dialup modems were “fast” and floppy disks were high tech? You can’t afford not to. info@imagebuild.ca . 250 663 8839 an ter s NT .b HE ne FO A simple brand “refresh” may be all you need. Or maybe it’s time to rethink that logo that was developed in an era when bellbottom pants were all the rage. rs . .o rad io LL OW the r ING co Need a fresh look for your business? A new marketing angle that reflects how awesome you are and why your competitors pale in comparison? Don’t buy into hype, trends, or the latest e-myth. Buy into your image, your products, your people. In turn, you will be investing in your clients. ff ol AR st u EA S Sometimes advertising gets noticed for the wrong reasons. Don’t let that happen to your business.
https://issuu.com/northerngroove/docs/2012-04-mag
CC-MAIN-2016-30
refinedweb
7,852
68.6
> uip-0.6.zip > uip_arp.h /* * Copyright (c) 2001-2002,: uip_arp.h,v 1.2 2002/01/11 18:54:35 adam Exp $ * */ #ifndef __UIP_ARP_H__ #define __UIP_ARP_H__ #include "uip.h" struct uip_eth_addr { u8_t addr[6]; }; struct uip_eth_hdr { struct uip_eth_addr dest; struct uip_eth_addr src; u16_t type; }; #define UIP_ETHTYPE_ARP 0x0806 #define UIP_ETHTYPE_IP 0x0800 /* The uip_arp_init() function must be called before any of the other ARP functions. */ void uip_arp_init(void); /* The uip_arp_ipin() function should be called whenever an IP packet arrives from the Ethernet. This function refreshes the ARP table or inserts a new mapping if none exists. The function assumes that an IP packet with an Ethernet header is present in the uip_buf buffer and that the length of the packet is in the uip_len variable. */ void uip_arp_ipin(void); /* The uip_arp_arpin() should be called when an ARP packet is received by the Ethernet driver. This function also assumes that the Ethernet frame is present in the uip_buf buffer. When the uip_arp_arpin() function returns, the contents of the uip_buf buffer should be sent out on the Ethernet if the uip_len variable is > 0. */ void uip_arp_arpin(void); /* The uip_arp_out() function should be called when an IP packet should be sent out on the Ethernet. This function creates an Ethernet header before the IP header in the uip_buf buffer. The Ethernet header will have the correct Ethernet MAC destination address filled in if an ARP table entry for the destination IP address (or the IP address of the default router) is present. If no such table entry is found, the IP packet is overwritten with an ARP request and we rely on TCP to retransmit the packet that was overwritten. In any case, the uip_len variable holds the length of the Ethernet frame that should be transmitted. */ void uip_arp_out(void); /* The uip_arp_timer() function should be called every ten seconds. It is responsible for flushing old entries in the ARP table. */ void uip_arp_timer(void); #endif /* __UIP_ARP_H__ */
http://read.pudn.com/downloads2/sourcecode/embed/3512/uip-0.6/uip/uip_arp.h__.htm
crawl-002
refinedweb
320
70.43
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site. using System; using Substrate; //) { if (args.Length != 3) { Console.WriteLine("Usage: BlockReplace &--#60;world&--#62; &--#60;before-id&--#62; &--#60;after-id&--#62;"); return; } string dest = args[0]; int before = Convert.ToInt32(args[1]); int after = Convert.ToInt32(args[2]); // Open our world BetaWorld world = BetaWorld.Open(dest); // The chunk manager is more efficient than the block manager for // this purpose, since we'll inspect every block BetaChunkManager cm = world.GetChunkManager(); &--#60; xdim; x++) { for (int z = 0; z &--#60; zdim; z++) { for (int y = 0; y &--#60; ydim; y++) { // Replace the block with after if it matches before if (chunk.Blocks.GetID(x, y, z) == before) { chunk.Blocks.SetData(x, y, z, 0); chunk.Blocks.SetID(x, y, z, after); } } } } // Save the chunk cm.Save(); } } } } Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate ... public void ApplyChunk(NBTWorld world, ChunkRef chunk, int[] fallBlock) { IBlockManager blockm = world.BlockManager; // Check all blocks in the chunk for (int y = 0; y <= 127; y++) { for (int x = chunk.X; x <= chunk.X+15; x++) { for (int z = chunk.Z; z <= chunk.Z+15; z++) { // Skip most blocks double r = rand.NextDouble(); if (r > 0.15) { continue; } // Attempt to replace block //int oldBlock = chunk.GetBlockID(x, y, z); BlockRef oldBlock = blockm.GetBlockRef(x, y, z); // ERRORS IN THIS LINE foreach (int i in fallBlock) { if (oldBlock.ID == i) { ... using System; using Substrate; // FlatMap is an example of generating worlds from scratch with Substrate. // It will produce a completely flat, solid map with grass, dirt, stone, // and bedrock layers. On a powerful workstation, creating 400 of these // chunks only takes a few seconds. namespace FlatMap { class Program { static void Main (string[] args) { string dest = "F:\\Minecraft\\test"; int xmin = -20; int xmax = 20; int zmin = -20; int zmaz = 20; // This will instantly create any necessary directory structure BetaWorld world = BetaWorld.Create(dest); ChunkManager cm = world.GetChunkManager(); // We can set different world parameters world.Level.LevelName = "Flatlands"; world.Level.SetDefaultPlayer(); // We'll create chunks at chunk coordinates xmin,zmin to xmax,zmax for (int xi = xmin; xi < xmax; xi++) { for (int zi = zmin; zi < zmaz; zi++) { // This line will create a default empty chunk, and create a // backing region file if necessary (which will immediately be // written to disk) ChunkRef chunk = cm.CreateChunk(xi, zi); // This will suppress generating caves, ores, and all those // other goodies. chunk.IsTerrainPopulated = true; // Auto light recalculation is horrifically bad for creating // chunks from scratch, because we're placing thousands // of blocks. Turn it off. chunk.AutoRecalcLight = false; // Set the blocks FlatChunk(chunk, 64); // Reset and rebuild the lighting for the entire chunk at once chunk.RebuildBlockLight(); chunk.RebuildSkyLight(); Console.WriteLine("Built Chunk {0},{1}", chunk.X, chunk.Z); // Save the chunk to disk so it doesn't hang around in RAM cm.Save(); } } // Save all remaining data (including a default level.dat) // If we didn't save chunks earlier, they would be saved here world.Save(); } static void FlatChunk (ChunkRef chunk, int height) { // Create bedrock for (int y = 0; y < 2; y++) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { chunk.SetBlockID(x, y, z, (int)BlockType.BEDROCK); } } } // Create stone for (int y = 2; y < height - 5; y++) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { chunk.SetBlockID(x, y, z, (int)BlockType.STONE); } } } // Create dirt for (int y = height - 5; y < height - 1; y++) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { chunk.SetBlockID(x, y, z, (int)BlockType.DIRT); } } } // Create grass for (int y = height - 1; y < height; y++) { for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { chunk.SetBlockID(x, y, z, (int)BlockType.GRASS); } } } } } } //This function goes through all blocks in every chunk. Useful if you want to replace all blocks with something else, or similar things. public void RunAllBlocks() { // Get a chunk manager IChunkManager chunkMan = world.GetChunkManager(); // Go through all chunks foreach (ChunkRef chunk in chunkMan) { // And through all blocks for (int y = 0; y <= 127; y++) { for (int x = 0; x <= 15; x++) { for (int z = 0; z <= 15; z++) { int id = chunk.GetBlockID(x, y, z); // At this point, you have x, y, z and id variables. } } } } } Substrate is a .NET/Mono SDK written in C# for reading, writing, and manipulating data in Minecraft worlds. Substrate isolates the different levels of map data such as blocks, chunks, and regions, and natively supports modifying Alpha and Beta worlds using the same block and chunk interfaces. Substrate also provides interfaces for other data such as Entities, players, and general level data. --- Requirements Substrate requires .NET Framework 2.0 or higher, or Mono, to run. Compiling Substrate source code requires a compiler that supports C# 3.0 or higher (Visual C# 2008 Express or higher, or comparable Linux tools). For convenience to developers, Substrate ships with separate .NET-2.0 and .NET-4.0 assemblies, so that you can include the assembly that best matches your application's target framework. --- Download Latest Version: 1.3.8 If you are interested in the development of Substrate, follow or fork the project on the Github Project Page --- Additional Information See the Introduction wiki page for more information on important classes provided by Substrate: Introduction Largely complete API documentation is included with the Substrate download. A number of example projects are also included in the download, and available in the source tree. Substrate is provided under the permissive MIT license. If you find this project useful in your software, consider mentioning it in the credits or about box of your application, but this is not required. Of course, any feedback, ideas, bug reports, etc. are welcome either in this thread, or on the project page. --- Examples --- Projects Using Substrate - NBTExplorer - A graphical NBT data editor. - MACE - Random cities generator. - Teeth of Time - Simulates effects of weather and time on worlds. - Eedit - A simple graphical editor for item enchantments. - Avanti! - A Paint-like Minecraft world editor. - SeeSharp - A Minecraft map exporter / renderer. If you've published a tool using Substrate and would like it listed, post your request. --- Update History [1.3.8] - Fix: Item enchantments no longer reset on tree load. - Fix: TagNodeString will now accept null values. - Fix: Casing error in 'playerGameType' tag. - Fix: Initialize Source properties in INbtObjects. - Fix: Region Loader no longer tries to pad out non-4KB-aligned files. - Fix: Setters in FusedDataArray. - Fix: Crash when parsing TAG_END in an NBT List type. - Internalized Ionic.Zlib. - Updated item and block info for MC 1.5 and 1.6. - World classes now accept dimensions specified as strings. - Allow setting TileEntity data on blocks not registered as Tile Entities. - Regions are now sorted by y,x coordinates on enumeration (contrib. by Sukasa). - Added support for GeneratorName setting (contrib. by cry-inc). - Added many more attributes to Level (contrib. by snoopen). [1.3.7] - Fix: Wrong tag name for additional block IDs ("AddBlocks" instead of "Add") - Fix: Anvil worlds can now handle block IDs >255 - Fix: Empty chunk sections below heightmap were not written - Fix: NBT Tree discarding root node name on load - Fix: Various Entity and TileEntity issues - Raw NBT tree exposed on more objects (Entities, TileEntities, Items...) - Generic TileEntity objects will be created if specific types are unknown - Region files multithread safe - MobSpawnerTileEntities have updated data fields [1.3.6] - Fix: Bug in index calculations of Anvil composite byte/nibble arrays, causing incorrect block updates. - Block updates for Minecraft 1.4. [1.3.5] - Minor changes to RegionFile to make it easier to extend (e.g. for Cubic Chunks). (not released) [1.3.4] - Fix: Bug in unicode handling of NBT strings which could result in inconsistent NBT binaries being written. [1.3.3] - Fix: Bug in player loading that could cause Anvil 1.2 worlds to not load. Was introduced in 1.3.2. [1.3.2] - Fix: ChunkManager.SetChunk did not set chunks at the requested location correctly. - Fix: ResetLava in BlockFluid could possibly convert lava blocks into water. - Fix: BlockManager could not set blocks above 127. BlockManager is now abstract and split into two concrete classes for Alpha and Anvil. - Block, item, and player data updates for Minecraft 1.3. [1.3.1] - Fixes bug in chunk creation causing the Z coordinate to be used for both X and Z. [1.3.0] - Unified Anvil map support - Multiple breaking changes for Anvil support - Block and item updates through Minecraft 1.2 [1.2.0] - Anvil beta (not officially released) [1.1.0] - Adds TileTick management throughout most of the API - AutoTileTick property in AlphaBlockCollection for automatically managing TileTicks. [1.0.3] - Fixes a bug where clearing the player spawn would have no effect - Fixes a bug where deleting a chunk would correctly update the cache, resulting in lost work [1.0.2] - Fixes a bug reading items with enchantments - Fixes a bug enumerating entities not registered with EntityFactory - Fixes a bug setting text on sign TileEntities - Exposes more direct access to the Chunk cache [1.0.1] - Fixes a serious bug where entities were written out with invalid data, causing chunk regeneration - Several block data enums where updated with fixes - Animal entity types are now subclasses of EntityAnimal [1.0.0] - Ionic.Zlib integrated into the Substrate assembly - Project split into .NET2/.NET4 output - Added full Enchantment API for items - Player and Mob classes updated with additional data - Entity/TileEntity registires are enumerable - ChangeValueType added to TagNodeList class [0.9.0] - Data resource / map (item) editing - Conversion utilities for map editing - NbtFile updated to handle differing compression requirements [0.8.4] - Fixes TileEntity data not being copied with chunks - Unknown/Nonstandard NBT tags are now round-tripped in most objects [0.8.3] - Fixes painting entities not being updated correctly when their chunk is relocated - Entities and TileEntities support MoveBy method for special relocation handling [0.8.2] - Fixes a bug where Entity/TileEntity coordinates were not updated with chunk [0.8.1] - Fixes a bug where chunk modified chunk coordinates are not saved [0.8.0] - 1.9pre5 block, item, and entity types - Fixed several bugs in Entities, including an exception caused by Enderman - Entity/TileEntity architecture updated to support inheritance, avoid future bugs - Optional cache size parameter in OpenWorld/CreateWorld [0.7.3] - Fixed crash when encountering XPOrb while enumerating entities [0.7.2] - 1.8 Entity types - Added missing properties to Arrow and all Mob entities - Fixed lighting bug with Chest blocks [0.7.1] - 1.8 Block and Item types [0.7.0] - Major refactoring. You will need to tweak your projects - CHM documentation for most of the common APIs - Intellisense XML file for the same - 1.7 Block and Item types - Schematic import and export support - CLS Compliance - Enumerable PlayerManager - Timestamp data exposed - NBT Validator event support - Numerous bugfixes including cache and TileEntity bugs [0.6.2] - Fixes bugs with some entities and tile entities [0.6.1] - Fixes bug with TileEntity updates [0.6.0] - Added fluid simulation for water and lava - AutoFluid property (disabled by default) [0.5.3] - Fixes performance regression - Fixes additional lighting bugs [0.5.2] - Lighting bugfixes and performance improvements - TileEntity fixes - Beta 1.6 block and item types - 'State' property to BlockInfo (solid/nonsolid/fluid) - Chunk copying / setting - ItemInfo classes and supporting data enums - Re-exposed the PlayerManager - All missing examples added [0.5.1] - Numerous lighting fixes including possible crashing bug - Added Beta 1.5 level attributes [0.5.0] - Major refactoring of Chunk/ChunkRef breaks compatibility, but should be easy to repair - Fixes missing Player attributes and bug in level.dat generation - Fixes more lighting bugs. Now correctly lights half steps, stairs, and other special blocks - Updated chunk caching back-end [0.4.1] - Lighting fixes for manual chunk relighting - Performance fixes for lighting [0.4.0] - Fixes cache consistency bug, among others - Adds manual chunk relighting - Example code [0.3.0] - Adds automatic blocklight and skylight recalculation for all setblockid operations via ChunkRefs or the BlockManager. [0.2.1] - Fixes serious bug in creating TileEntity or Entity objects. [0.2.0] - First public release Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Download: ... loads/list Source: ... S%2FSource Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Would be a shame if something were to happen to it.It's a great help to me, I have tried tackling map editing before, but it was always an epic fail. Now, excuse my crappy C# skills, but I have a question for you. I have copied part of the code from your second example, but it shows me errors no matter what I do. To me, it looks like the examples are from version 0.1.0 and in ver 0.2.0 things are done in a different way. Error 1 The call is ambiguous between the following methods or properties: 'Substrate.ILitBlockContainer.GetBlockRef(int, int, int)' and 'Substrate.IPropertyBlockContainer.GetBlockRef(int, int, int)' Error 2 Cannot implicitly convert type 'Substrate.ILitBlock' to 'Substrate.BlockRef'. An explicit conversion exists (are you missing a cast?) In the example code, change IBlockManager blockm to BlockManager blockm (actually, I don't think I ever used IBlockManager directly in that code?). Due to changes in the interface hierarchy, directly using IBlockManager doesn't make sense anymore unless you're requesting an IBlock (which exposes access to ID and data fields, nothing else). This might come into play if I write in a support class for mcschema files or creative classic files, although for the later I need Java interop support so maybe that won't happen. This part of the design is still under review. If you think something is overly weird or difficult to use, please mention it. I'll try to either justify it or come up with something different. If you would like something explained in more detail, I can also do that. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Error 1 Cannot implicitly convert type 'Substrate.IBlockManager' to 'Substrate.BlockManager'. An explicit conversion exists (are you missing a cast?) It's why I tried IBlockManager in the first place. I haven't looked at relighting yet, is there any (relatively) simple way to do it? BlockManager bm = world.BlockManager as BlockManager I'm missing a couple overrides in the alpha block container interface, once I put them in place the cast should not be necessary anymore. Relighting is .. interesting. I don't really have an easy solution for it but it's next on my list of things to tackle. But as a general idea, you could do an initial sweep of a chunk you modified, and make sure that any block with a luminosity value greater than 0 (can be checked in each block's blockinfo) is set to that light level. Then repeatedly sweep through the chunk looking for blocks that are not set to max-1 of all the neighbor's light values, and update them. Repeat the process until the chunk converges. Edge cases may be tricky as you'll need to inspect neighboring chunks as well. This is one task that can't easily be accomplished with a global block view because of memory constraints, unless you want to thrash your disk. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Every time I try placing a chest, my app crashes. Placing normal blocks at the same location works great, but chests, dispensers and similar always crash. Here you can see a cobble block (id 4) being placed, and then a chest (54) being placed at the same spot. While cobble is fine, the chest crashes the app instantly after being placed. ... loads/list The crash occurred on chests, furnaces, and similar because they have TileEntities attached. The routines to update block IDs automatically enforce TileEntity consistency, so if you create a furnace, it will create a reasonable default TileEntity record for it as well. Likewise when you change it back to cobblestone, the records will be removed. You can also update TileEntities if, for example, you wanted to fill the new chest block with some items. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate However, if you don't mind grabbing the source tree, I committed some block relighting code. Calling SetBlockID on a ChunkRef will immediately recalculate blocklight (but currently, not skylight). Actually, since BlockRef uses ChunkRefs, it will probably recalculate light as well. Eventually I will include some way of toggling this behavior, since realtime lighting recalculation will be too expensive for some use patterns. There's still some problems calculating light past region boundaries. That will get patched later. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate ... loads/list This fully incorporates automatic blocklight and sunlight recalculation whenever a block is updated. It seems to do a pretty good job, but it's possible that it violates some of the lighting rules. If you can identify a lighting pattern that occurs in Minecraft but is not faithfully reproduced by Substrate, please post a picture of it. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate I've also pushed the first purpose-built, well-commented example, generating a flat map. On a powerful workstation, this generated 1600 solid, lit chunks in under 10 seconds. Of course, it represents a lower bound. (Note, the API for World objects has been changed) Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate The map generator example will come in handy in the future, too. BTW, finally got something to show. Before: After: The universal griefer tool :biggrin.gif: Still have to fix some bugs with TileEntities and add some customizeability (currently everything is hardcoded, even world path), maybe an alpha release after that. I would recommend trying to identify and remove the water. If you're feeling enterprising, you can attempt to do the simulation yourself, and manually set the data value on the water blocks to set their flow value (or rather, create the flow blocks that currently aren't there). Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate Version 0.4.0 is another pre-release version (I expect at least a couple more of these to follow before I'm happy enough to bless this project). It rolls up numerous bugfixes, some of them serious. It includes manual chunk relighting, and some example code. Mods I Develop: Garden Stuff -- Storage Drawers -- Hunger Strike Tools I Develop: NBTExplorer -- Substrate I couldn't figure out, how to go through all existing blocks of a map and read their ID and Coordinates, and also how to select a block by coordinates. Could you please give me a short codeexample on both? Greetings, Tatonka You can use this in your app: I don't quite understand what you mean by "selecting a block by coordinates". Does it mean you want to access a block at a certain location? Edit: I absolutely forgot the same thing is even in the OP, only better documented /facepalm
http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-tools/1261313-sdk-substrate-map-editing-library-for-c-net-1-3-8?cookieTest=1
CC-MAIN-2016-36
refinedweb
3,252
57.27
In the current, fast-changing JavaScript scene, there are two projects I am following more closely than the rest: Elm and Ember.js. Recently I had the opportunity to experiment with both at once, as I worked out how to use Glimmer (Ember.js’s rendering engine) as a view layer for Elm code. This is a write up of my solution. It is actually divided in two parts: - Using an external view layer with Elm. - Messaging to/from a Glimmer application. This will not be a comprehensive walkthrough, but rather will cover the most important details of how to build the “glue” between these two pieces. You can check out the complete example on Github if you want to know more or simply play with the result. Using an external view layer with Elm Elm’s own view layer Something that can be surprising to Elm newcomers is how to work with its view layer. Instead of writing the HTML templates that are commonplace in other environments, developers and designers are expected to use the Elm language itself to describe the output. For example, where we normally would have something like the following: <tr> <td class="item-id">#{{item.id}}</td> <td class="item-name">{{item.name}}</td> </tr> With Elm we would define the following function instead: itemView : Item -> Html Msg itemView item = tr [] [ td [ class "item-id" ] [ text ("#" ++ item.id) ] , td [ class "item-name" ] [ text item.name ] ] This gives our templates the benefits of Elm’s compile-time type checking, helping us to identify many errors in our code immediately. On the other hand, it is a bit more verbose, arguably inconvenient, and it can be difficult to handle when converting existing HTML, or generally liaising with members of the team implementing the views. Whether the tradeoff is acceptable or not is for your team to decide. It is worth pointing out though that Elm’s type checking is a major boon of the language, and you should not disregard it lightly. Having said that, are there alternatives to this? Is it possible to work with Elm while keeping our “classic” HTML-based templates? The answer is yes. At least two options, actually. Alternative view layers The first option would be to write an Elm library to handle this. For example, the core library elm-lang/html implements Html.program. This expects (among other things) a view argument that is the basis of Elm-based templates like the one in the example above. A custom library would handle things differently, capturing DOM events, notifying the update function, and refreshing our view layer when the model changes. We could call it foobar/template and provide Template.program. The problem with this approach is that it requires certain knowledge of Elm’s internal APIs, or at least enough to write a library of this type. I do not possess this knowledge, so I had to look for another, simpler option. This second option is: instead of using Html.program, completely eschew the HTML library and create a “headless” program using Platform.program, which takes the usual arguments except for view. You can then communicate with your view layer using Elm ports. Example headless Elm program Let’s try put something together. This would be an example Elm program without a view layer. It expects messages to come in through a port. When the model changes, the program will send it out via another port: port module Main exposing (main) import Json.Decode -- A bug in Elm forces us to explicitly require this type alias Model = Int port increment : ( Int -> msg ) -> Sub msg port reset : ( () -> msg ) -> Sub msg port render : Model -> Cmd msg type Msg = Increment Int | Reset subscriptions : Model -> Sub Msg subscriptions model = Sub.batch [ increment (\amount -> Increment amount) , reset (\_ -> Reset) ] update : Msg -> Model -> (Model, Cmd Msg) update msg model = let newModel = case msg of Increment amount -> model + amount Reset -> 0 in (newModel, render newModel) main : Program Never Model Msg main = Platform.program { init = (0, Cmd.none) , subscriptions = subscriptions , update = update } This program exposes these ports: render(outbound): will be passed the model when this changes. reset(inbound): will set the model to 0. increment Int(inbound): will increment the model by the given amount. We can now write some HTML and JS that load the above Elm program and interacts with it. For a simple start, let’s just not render anything. We can use the browser console for now. If the Elm code is compiled into a file called elm.js, we can load it as follows: <html> <head> <title>Elm experiment</title> </head> <body> <script type="text/javascript" src="elm.js"></script> <script> var elmApp = Elm.Main.worker(); window.elmApp = elmApp; elmApp.ports.render.subscribe(function(model) { console.log("RENDER", model); }); function actionIncrement(value) { elmApp.ports.increment.send(value); }; function actionReset() { elmApp.ports.reset.send(null); }; actionReset(); </script> </body> </html> We open this on a browser (as a file:// is ok) and get a beautiful, exciting… blank page. But remember we were not rendering anything yet. We will work with the console. Opening the inspector will reveal some output present already: RENDER 0. We can interact with the Elm program using the interface we created. This is an example session: RENDER 0 > actionIncrement(1) RENDER 1 > actionIncrement(2) RENDER 3 > actionIncrement(-7) RENDER -4 > actionReset() RENDER 0 We now have a clear interface to send messages to Elm, as well as for Elm to tell us about changes in the model. We can integrate this with any JavaScript code, including templating libraries. Time to wire one up. Communication to/from a Glimmer application. A basic Glimmer setup I will not go into detail on how to build an Elm and a Glimmer applications side to side on the same project. You can check the example app to see a simple way of doing it. For now, let’s just assume we have a working project where both applications are building correctly. At a minimum, it will involve altering the HTML above with a change like the following, where app.js is the Glimmer code, which in turn expects a container element with id app where results will be rendered: <body> + <div id="app"></div> + + <script type="text/javascript" src="app.js"></script> <script type="text/javascript" src="elm.js"></script> Messaging At the time of writing, standalone Glimmer (as opposed to integrated into Ember) is beta software and there are some outstanding issues. The one that is important to us now is that Glimmer does not provide a way for external code to communicate with its components: we cannot pass data or notify of changes that occurred in the outside. This should be addressed at some point this year, and in fact there’s a pull request in the works as I write these lines. But until such time that this makes it into mainline Glimmer, there is a web API that we can use for this purpose. To work around Glimmer’s limitation, I have been using window.postMessage successfully. If you are familiar with this Web API, you will know that it is commonly used to send messages to other frames or windows in the app, but it can also be used to send messages within the current window, to any code that may be listening to them. From Elm to Glimmer Let’s see how it would work for us. First, from our HTML glue code we can send the model to the template when Elm notifies us of a change: elmApp.ports.render.subscribe(function(model) { - console.log("RENDER", model); + var msg = { + origin: 'core', + target: 'view', + action: 'update', + payload: { model }, + }; + window.postMessage(msg, window.location.origin); }); Then, in the top-most component of our Glimmer app, we can set a listener for postMessage notifications: import Component, { tracked } from '@glimmer/component'; export default class ModelDisplay extends Component { @tracked model = null; // ...other component code here... didInsertElement() { window.addEventListener('message', (evt) => { if (evt.origin !== window.location.origin) { return false; } let data = evt.data; if (data.origin !== 'core' && data.target !== 'view') { return false; } let { action, payload } = data; if (action === 'update') { this.model = payload.model; } }); } } This is enough to get a first render. If your Glimmer component has a representation for the initial model of the Elm app, it should appear on screen now. From Glimmer to Elm Next, we enable communications in the opposite direction: from the Glimmer component to the Elm app. To do this, we use very similar code, only reversed. For example, if our Glimmer component has two actions increment and decrement, these will look like follows: // ... increment() { this.postIncrement(1); } decrement() { this.postIncrement(-1); } postIncrement(amount) { let msg = { origin: 'view', target: 'core', action: 'increment', payload: { amount }, } window.postMessage(msg, window.location.origin); } // ... As you trigger the actions (pressing buttons or whatever is appropriate), the “glue” code will receive these messages. From there we will forward them to the Elm app through its inbound ports. The code will mirror the one receiving messages in the component: window.addEventListener('message', function(evt) { if (evt.origin !== window.location.origin) { return false; } var data = evt.data; if (data.origin !== 'view' && data.target !== 'core') { return false; } var action = data.action; if (action === 'increment') { actionIncrement(data.payload.amount); } }); That is enough to get the increment/decrement actions going. Implementing the reset is very similar and left as an exercise to the reader ;-) Performance I wondered about how efficient this would be, sending these messages across using an asynchronous API and all. For a simple benchmark, I built a simple app that shows a large table and updates random rows at the push of a button. I actually wrote three different simplementations: pure Elm, pure Glimmer and hybrid. Check it out and compare yourself. From what I can see, there is no significant difference between the Elm and hybrid versions, but the Glimmer-only version performs way better. But take all this with a pinch of salt anyway.
https://thoughtbot.com/blog/elm-glimmer
CC-MAIN-2021-17
refinedweb
1,660
56.66
This article has been excerpted from book "A Programmer's Guide to ADO.NET in C#".As you can see, working with different data source means nothing except changing the connection string. Listing 5-27 shows the connection string for the MySQL database. You access a MySQL database through odbc data providers. (I'll discuss My SQL databases connectivity and show how to install an ODBC driver for MySQL with a step -by-step example later article). As you can see from Listing 5-27, you can use a similar database as Northwind. To provide similar sample, I exported the Access 2000 Northwind database as a MySQL database. You can use any database. Just replace the database name and change the SQL statement. To test this application, create a Windows application, drop a data grid to the form, add a reference to the System.Data and Microsoft.Data.Odbc namespaces, and type the following code in Listing 5-27 on the Form_load event. Listing 5-27. Reading data from a MySQL database using ODBCprivate void Form1 _Load(object sender, System. EvetArgs e){ string ConnectionString = "Driver={MySQL};SERVER = localhost; " + "DATABASE= NorthwindMySQL; "; OdbcConnection conn = new OdbcConnection(ConnectionString); conn.Open(); OdbcDataAdapter da = new OdbcDataAdapter ("SELECT CustomerID, ContactName, ContactTitle FROM Customers", conn); DataSet ds = new DataSet("cust"); da.Fill(ds, "Customers"); dataGrid1.DataSource = ds.DefaultViewManager; conn.Close();}ConclusionHope this article would have helped you in understanding Connecting to a MySQL Database in ADO.NET. See my other articles on the website on ADO.NET. Connecting to a MySQL Database in ADO.NET How Do I Choose a Data Provider? there is error in the connection plz guide clearly Sir ! your article is small even published here...i think its a great article and excerpted from a book .
http://www.c-sharpcorner.com/uploadfile/mahesh/connecting-to-a-mysql-database-in-ado-net/
crawl-003
refinedweb
293
60.31
imNew 0 Posted January 14, 2007 AdlibEnable("_error_check") ;============================= ;main script _start_application() while 1 mousemove(1, 1) mousemove(1, 2) mousemove(1, 3) mousemove(1, 4) mousemove(1, 5) mousemove(1, 6) mousemove(1, 7) mousemove(1, 8) mousemove(1, 9) mousemove(1,10) WEnd ;============================= func _error_check() if excel.exe crashed then _start_application();restart the application goto mousemove(1, 1);<<=============Can this be done in AutoIT?===================== ;if the main loop is @ mousemove(1, 4) at the moment, I need the loop to stop there, skip mousemove(1, 5) to mousemove(1, 10), ; and then go back to the beginning of the loop endif EndFunc func _start_application() run excel.exe EndFunc two things I have learnt so far that I can do: 1. use a flag in front of every line, add if-else in front of every "mousemove()", so if I have 1000lines of "mousemove()" then 1000 if-else 2. compile the while loop into a separate exe file, and call that exe from the main script I need more ideas, please help. Share this post Link to post Share on other sites
https://www.autoitscript.com/forum/topic/39425-can-this-be-done-in-autoit/?tab=comments
CC-MAIN-2019-47
refinedweb
182
65.15
Hello, readers! Here, we will be learning How to Scrape Google Search Results using BeautifulSoup in Python. In this article, we will be having a look at one of the most interesting concept in Python — Scraping a website. So, let us begin! Table of Contents What is Web Scraping? At times, when we surf through the web, we come across some user-related data that we believe would be beneficial for us in the future. And, then we try to copy it and save it to clipboard each time. Now, let’s analyze the next scenario We often need data to analyze the behavior of certain factors in terms of data modeling. Thus, we begin creating a dataset from scratch by copy-pasting the data. This is when, Web Scraping or Web Crawling comes into picture. Web Scraping is an easy way to perform the repetitive task of copy and pasting data from the websites. With web scraping, we can crawl/surf through the websites and save and represent the necessary data in a customized format. Let us now understand the working of Web Scraping in the next section. How Does Web Scraping Work? Let us try to understand the functioning of Web Scraping through the below steps: - Initially, we write a piece of code that requests the server for the information with regards to the website we want to crawl or the information we want to scrape on the web. - Like a browser, the code would let us download the source code of the webpage. - Further, instead of visualizing the page in the manner that the browser does, we can filter the values based on the HTML tags and scrape only the needed information in a customized manner. By this, we can load the source code of the webpage in a fast and customized manner. Let us now try to implement Web Scraping in the upcoming section. Bulk Scraping APIs If you are looking to build some service by scraping bulk search, chances are high that Google will block you because of an unusually high number of requests. In that case, online APIs like Zenserp is a big help. Zenserp performs searches through various IPs and proxies and allows you to focus on your logic rather than infrastructure. It also makes your job easier by supporting image search, shopping search, image reverse search, trends, etc. You can try it out here, just fire any search result and see the JSON response. Implementing steps to Scrape Google Search results using BeautifulSoup We will be implementing BeautifulSoup to scrape Google Search results here. BeautifulSoup is a Python library that enables us to crawl through the website and scrape the XML and HTML documents, webpages, etc. Scrape Google Search results for Customized search Example 1: import requests from bs4 import BeautifulSoup import random text = 'python' url = '' + text.text, 'lxml') for info in soup.find_all('h3'): print(info.text) print('#######') Line by line explanation of the above code: - Importing the necessary libraries In order to make use of BeautifulSoup for scraping, we need to import the library through the below code: from bs4 import BeautifulSoup Further, we need the Python requests library to download the webpage. The request module sends a GET request to the server, which enables it to download the HTML contents of the required webpage. import requests 2. Set the URL: We need to provide the url i.e. the domain wherein we want our information to be searched and scraped. Here, we have provided the URL of google and appended the text ‘Python’ to scrape the results with respect to text=’Python’. 3. Setting User-Agent: We need to specify the User Agent Headers which lets the server identify the system and application, browsers wherein we want the data to be downloaded as shown below–", ) 4. The requests.get(url, header) sends the request to the web server so as to download the requested HTML content of the web page or the search results. 5. Create an object of BeautifulSoup with the requested data from ‘ lxml‘ parsing headers. The ‘lxml‘ package must be installed for the below code to work. soup = BeautifulSoup(r.text, 'lxml') 6. Further, we use object.find_all('h3') to scrape and display all the Header 3 content of the web browser for the text=’Python’. Output: Welcome to Python.org ####### Downloads ####### Documentation ####### Python For Beginners ####### Python 3.8.5 ####### Tutorial ####### Python Software Foundation ####### Python (programming language) - Wikipedia ####### Python Tutorial - W3Schools ####### Introduction to Python - W3Schools ####### Python Tutorial - Tutorialspoint ####### Learn Python - Free Interactive Python Tutorial ####### Learn Python 2 | Codecademy ####### Scrape Search results from a Particular Webpage In this example, we have scraped the HTML tag values from the website as shown: Example 2: import requests from bs4 import BeautifulSoup import random url = ''.content, 'lxml') title = soup.find('title') print("Title of the webpage--\n") print(title.string) search = soup.find_all('div',class_="site") print("Hyperlink in the div of class-site--\n") for h in search: print(h.a.get('href')) Further, we have scraped the title tag values and all the a href values present in the div tag of class value = site. Here, the class value differs for each website according to the structure of the code. Output: Title of the webpage-- Python predict() function - All you need to know! - AskPython Hyperlink in the div of class-site-- Conclusion By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question. For more such posts related to Python, stay tuned and till then, Happy Learning!! 🙂 Great thank you for the article and the code. I need help suppose i have to find about a place how can i create a code which can search through the google and get the all the relevant information about that place and save it in a excel file. Did you get a solution for this? I am just missing something. I copied your source code and I got the following msg: Traceback (most recent call last): File “C:\py_prjs\googlescrapping.py”, line 15, in r = request.get(url, headers=headers) AttributeError: module ‘urllib.request’ has no attribute ‘get’ Any suggestion? There was an error in the code, we need to import requests package. I have fixed it. in first example : line 1: from urllib import request **** there is one mistake in word request is actually requests Thank you… Thanks for the catch, I have fixed the wrong import issue in the code.
https://www.journaldev.com/44755/scrape-google-search-using-python-beautifulsoup
CC-MAIN-2021-21
refinedweb
1,084
63.49
Before you read on, please note that this tutorial covers a pretty advanced topic. To properly understand it, you need: - Proper understanding of Functions - Proper understanding of Pointers - Basic understanding of Structs (optional) As a C programmer, you probably know that pointers play a major role in your life. If you've ever used an other programming language, you probably encountered classes, which probably could hold functions in them. As you might have noticed, C does not let you have a function inside a struct... Well, at-least not in a conventional way. Functions, just like variables, are too stored in memory. Thus, they can be reffered to by adress, so a variable to store and adress that adress can be used. Thus, a pointer to a function is possible. Here's a fun fact: C has absolutely no problems with pointers inside Structs. You know already that in C, you work with pointers by using the '*' thingy. How-ever, it can get tricky; like in the case of a pointer to a function. Take a look at that: int* Func()What is this? That's a function returning a pointer to an int. int *Func()That too is a function returning a pointer to an int. How would you then "fool" the language into making a pointer to a function? int (*Func)() If you haven't been exposed to the influence of other languages, you might ask: "How could that be useful?" The answer is quite simple. Abstraction (design), convenience, and proceduralism. Ever wondered how atexit() worked? Ever wondered what's atexit anyway? atexit is a function which takes, as a parameter, a pointer to a function; which is called when the exit(0) or abort() functions are called. Here's another example: Say you want to make a framework. You define the program flow, you write utility functions, etc.. But there's no point to all of that. The programmer using your framework can not get what he wants without modifying your framework, or at-least the main function. However, by providing him a way to push a function he had written himself into a queue which you then execute, you solve that issue and make his life easy. Yet another example: VIDEO GAMES!! Even in older games, you've got different kinds of objects. Heck, even in pong! Every object has it's own logics behind it. What does it do upon collision? What does it do every frame? Sure, you could fall for it and write explicitly all of the logics for all the objects, but there's yet another way: You can just call the, say, automation function of each object. It makes the code look a-lot simpler, feel way more natural, and be way more clear; and obviously, flexible. Here's an actual example: #include <stdio.h> #include <stdlib.h> struct Obj { void (*Func)(); struct Obj* Next; } Queue; int PushFunc(void (*Function)) { static struct Obj* Cur = &Queue; static char IsFirst = 1; if(IsFirst == 1) { Cur->Func = Function; IsFirst = 0; } else { Cur->Next = malloc(sizeof(struct Obj)); if(Cur->Next == NULL) /* malloc failed */ return 0; Cur = Cur->Next; Cur->Func = Function; Cur->Next = NULL; } return 1; } void DoLogics() { puts("Doing the logics... Like a sir!"); struct Obj* Cur = &Queue; while(Cur != NULL) { Cur->Func(); Cur = Cur->Next; } } void SayHi() { puts("Hello there!"); } int main() { if(!PushFunc(SayHi)) return 1; DoLogics(); return 0; /* Note: There's no freeing of the linked list */ } /* NOTICE: THE CODE ABOVE HAS NOT BEEN TESTED */Sure, the above code is useless; but use your imagination! You can probably see how this in-valuable part of the language be useful. OPEN FOR POLISHING / MODIFICATION / REVISION
http://forum.codecall.net/topic/69312-pointers-to-functions/
CC-MAIN-2019-04
refinedweb
614
75.2
Static single assignment analysis. Contains all the functionality to implement variable renaming on a given program. For this class, we do not actually transform the AST directly, rather we perform the analysis and add attributes to the AST nodes so that later optimizations can access the results of this analysis while still preserving the original AST. Definition at line 100 of file staticSingleAssignment.h. #include <staticSingleAssignment.h> A compound variable name as used by the variable renaming. Definition at line 109 of file staticSingleAssignment.h. Describes the defs or uses at each node. This is for local, rather than propagated, information. Definition at line 112 of file staticSingleAssignment.h. A filtered CFGNode that is used for DefUse traversal. Definition at line 115 of file staticSingleAssignment.h. A filtered CFGEdge that is used for DefUse traversal. Definition at line 118 of file staticSingleAssignment.h. A map from each variable to its reaching definitions at the current node. Definition at line 123 of file staticSingleAssignment.h. The first table is the IN table. The second table is the OUT table. Definition at line 126 of file staticSingleAssignment.h. Map from each node to the variables used at that node and their reaching definitions. Definition at line 129 of file staticSingleAssignment.h. Run the analysis. If interprocedural analysis is not enabled, functionc all expressions (SgFunctionCallExp) will not count as definitions of any variables.. Get the table of definitions for every node. These definitions are NOT propagated. Definition at line 380 of file staticSingleAssignment.h. Returns the definitions of all the variables right after the given node has executed. This function does not work correctly for "container" nodes such as SgBasicBlock, SgCommaOp, SgExprStmt. If there is a definition at the node itself, e.g. SgAssignOp, it is included in the outgoing defs. Returns the definitions of all the variables immediately before the given node has executed. If there is a definition at the node itself, e.g. SgAssignOp, it is not included in the reaching defs. Returns a list of all the variables used at this node. Note that uses don't propagate past an SgStatement. Each use is mapped to the reaching definition to which the use corresponds. Returns a list of all the variables defined at the given node. Note that this will return an empty collections for nodes that do not modify any variables. Compare this function to getReachingDefsAtNode. Returns a set of all the variables names that have uses in the subtree. Given a node, traverses all its children in the AST and collects all the variable names that have definitions in the subtree. Given a node, traverses all its children in the AST and collects all the variable names that have original definitions in the subtree. Expanded definitions are not included - for example if p.x is defined, p is not included. Returns the last encountered definition of every variable. Variables go out of scope, so quering for reaching definitions at the end of a function doesn't return the last versions of all. Finds the scope of the given node, and returns true if the given variable is accessible there. False if the variable is not accessible. Get a string representation of a varName.
http://rosecompiler.org/ROSE_HTML_Reference/classStaticSingleAssignment.html
CC-MAIN-2021-10
refinedweb
536
51.95
AWS SDK for JavaScript in the browser and Node.js yarn add aws-sdk-jsinstead? upload()function and the input as { ..., Body: fs.createReadStream(filePath), ... }. import AWS from 'aws-sdk';, I don't have access to AWS.Signers or AWS.HttpClient since they are not exported by the sdk I can import in JS fashion i.e. var aws = require('aws-sdk')but then I lose the type checking of typescript. Are these modules intentionally left out or is it just a miss? Any recommendations on how to proceed now? NextContinuationTokentoken is missing in the data object in the listObjectsV2callback when using the S3 client. Is there already someone working on this? so, I feel like I'm missing something obvious. I have a simple lambda setup that just does a little image manipulation, and then I"m wanting to return the new image. So I'm returning return { statusCode: 200, headers: { 'Content-Type': `image/${info.format}` }, body: data.toString('base64'), isBase64Encoded: true }; from my lambda. However, when I curl the attached gateway, I receive just the proper base64, but not a binary response, and if I try to load the image up in a browser, it fails. I am also setting the binaryMediaTypes: ['image/*'] in my proxy gateway. Am I missing something obvious here? Thu Feb 13 13:24:40 UTC 2020 : Endpoint response body before transformations: {"statusCode":200,"headers":{"Content-Type":"image/jpeg"},"body":"=","isBase64Encoded":true} Thu Feb 13 13:24:40 UTC 2020 : Method response body after transformations: = Thu Feb 13 13:24:40 UTC 2020 : Method response headers: {Content-Type=image/jpeg, X-Amzn-Trace-Id=Root=1-5e454e17-c7a5b28ca2972c408be0c83d;Sampled=0} Looking for some advice on accessing Cognito user details from an AccessToken in node js. I know that I can use CognitoIdentityServiceProvider to get what I need, but this requires using a callback. My goal is to provide the user values in an Express context, so async/callbacks aren't going to work for me. Is my only option to manually validate the JWT access token and extract values?
https://gitter.im/aws/aws-sdk-js?at=5e4564eeb612cc7bb1655f8d
CC-MAIN-2022-40
refinedweb
345
50.02
Control keyboard ui Hi - I'm building a special calculator. I use textviews to enter and display data. I would like to have the keyboard disappear, after I press a UI button (my calculate button). When I enter data into a textview, the keyboard covers the lower half my calculator UI and it does not disappear, after I press the calculate button. Also, I'd like to have the keyboard pop up as a numeric keyboard, when I tap a textview., since I'm building calculators. I use a buttons to call a functions. Do I have to make the keyboard control code part of the function(s) or should it be located at the end of the script? Thanks, Forrest textfield.end_editing()to hide the keyboard when you do not need it textfield.keyboard_typeset to one of the following, experiment which is best for your use case: - ui.KEYBOARD_DECIMAL_PAD - ui.KEYBOARD_NUMBERS - ui.KEYBOARD_NUMBER_PAD I'd like to have the keyboard pop up as a numeric keyboard If you really want a numeric keyboard only, see here @mikael It would be great if you could show a little snippet of code showing the context of the methods. textfield.end_editing() I got the textfield.end_editing() to work and it's a big help! The keyboard_type code has me stumped. I have googled it extensively and haven't found a syntax that works. @FDT, mostly, do not google, but highlight the class name and select Help... from the popup options to see attributes like these. Here’s a quick sample: import ui v = ui.View() tf = ui.TextField( placeholder='First number', keyboard_type=ui.KEYBOARD_DECIMAL_PAD, width=200, height=40, center=v.bounds.center(), flex='RTBL', ) v.add_subview(tf) v.present()
https://forum.omz-software.com/topic/6116/control-keyboard-ui
CC-MAIN-2022-05
refinedweb
287
68.57
CEFA 2003/2004 LECTURE NOTES Mats Hansson Svenska handelshögskolan Contents 1.TU UT FIXED INCOME SECURITIES - AN INTRODUCTION TU UT 1 1.1.TU UT What’s so special about fixed income securities? TU UT 1 1.2.TU UT The risks of investing in debt and why everybody always talks about the yield TU UT 2 1.3.TU UT The money and bond markets TU UT 3 1.4.TU UT Market size TU UT 4 1.5.TU Factors affecting the level of the nominal return UT TU UT 5 1.5.1. The real return TU UT TU UT 5 1.5.2. The inflation rate TU UT TU UT 6 1.5.3. The risk premium TU UT TU UT 7 2.TU UT BOND AND INTEREST RATE MATHEMATICS TU UT 8 2.1.TU The frequency of compounding UT TU UT 8 2.1.1. Effective money market yields TU UT TU UT 10 2.2.TU Building blocks: zeros and forwards UT TU UT 11 2.2.1. Zero-coupon bonds TU UT TU UT 11 2.2.2. Forward rates TU UT TU UT 13 2.3.TU Zero-coupon pricing of coupon bonds UT TU UT 15 2.3.1. The coupon rate TU UT TU UT 15 2.3.2. The present value of a coupon bond TU UT TU UT 15 2.3.3. Yield to maturity for a coupon bond TU UT TU UT 17 2.3.4. The par yield TU UT TU UT 20 2.4.TU The yield: common misconceptions UT TU UT 21 2.4.1. The yield is not the return TU UT TU UT 21 2.4.2. Yields are not additive TU UT TU UT 22 2.5.TU UT From coupon bonds to zeros: bootstrapping TU UT 23 2.6.TU UT Spot and forward rates with semi-annual compounding TU UT 25 3.TU UT DAY COUNTS AND ACCRUED INTEREST TU UT 27 3.1.TU UT Day count basis TU UT 27 3.2.TU UT The money market TU UT 28 3.3.TU UT Zero-coupon bonds: annual compounding TU UT 29 3.4.TU UT Zero-coupon bonds: semi-annual compounding TU UT 30 3.5.TU Coupon bonds UT TU UT 30 3.5.1. Dirty prices and clean prices TU UT TU UT 31 3.5.2. Behavior of dirty and clean prices over time: convergence towards par TU UT TU UT 32 ii 4.TU UT MEASURING INTEREST RATE RISK: DURATION AND CONVEXITY 34 TU UT 4.1.TU UT The yield-price relationship for bonds TU UT 34 4.2.TU Duration UT TU UT 35 4.2.1. Macaulay duration TU UT TU UT 36 4.3.TU Modified duration and PVBP UT TU UT 37 4.3.1. The duration of a bond through time TU UT TU UT 38 4.3.2. Key rate duration TU UT TU UT 39 4.4.TU Convexity UT TU UT 40 4.4.1. Duration matching and the value of convexity TU UT TU UT 42 4.5.TU UT Bond portfolio duration and convexity TU UT 44 4.6.TU Butterfly trades: A critical assessment of yield, convexity and duration UT TU UT 45 4.6.1. Weighting a butterfly TU UT TU UT 45 4.6.2. A critical assessment of yield, convexity, and duration TU UT TU UT 47 FUTURES UT 49 5.1.TU UT Forward Rate Agreements TU UT 49 5.2.TU Bond futures UT TU UT 51 5.2.1. Futures pricing: The general approach TU UT TU UT 51 5.2.2. Repo transactions in the bond cash and futures markets TU UT TU UT 52 5.2.3. Coupon payments TU UT TU UT 53 5.2.4. Notional bonds and delivery options TU UT TU UT 54 5.2.5. Futures pricing using quoted prices and accrued interest TU UT TU UT 55 6.TU UT APPLICATIONS OF BOND MATHEMATICS II: SWAP CONTRACTS 58 TU UT 6.1.TU Interest rate swaps UT TU UT 58 6.1.1. The swap rate TU UT TU UT 59 6.1.2. The swap rate and FRA-rates TU UT TU UT 60 6.1.3. Interest rate swap valuation TU UT TU UT 61 6.2.TU Currency swaps UT TU UT 62 6.2.1. Currency swap rates and currency forward rates TU UT TU UT 63 6.2.2. Currency swap valuation TU UT TU UT 64 7.TU UT PRICING CREDIT RISK TU UT 65 7.1.TU UT Credit ratings TU UT 65 7.2.TU UT The traditional approach to pricing credit risk TU UT 66 7.3.TU UT Using option theory to price credit risk TU UT 67 7.4.TU Default probabilities, rating transitions, recovery rates and how to use them to estimate UT TU bond returns UT 69 7.5.TU UT Selected empirical results on spreads TU UT 72 1 Debt instruments or fixed income securities are financial instruments that commit theissuer to a series of fixed payments (for example a series of coupons and principal).Examples are treasury bonds and bills, corporate bonds and loans, certificates of deposit,and interest rate and currency swaps. The issuer of these securities promise a certain cashflow at certain specified times in the future, hence the definition “fixed income”. Also,fixed income securities typically have a finite maturity. A fixed income security follows the same basic principles of valuation as for e.g. stocks:future cash flows are discounted to present time. Fixed income securities, however, havea number of special features that make a separate treatment of these instrumentswarranted: 1. Fixed cash flows. Most bonds pay fixed interest (altough floating rate notes are also common), which is also paid on specified dates. Thus, cash flows are known both with respect to size and maturity, except in the case of default.2. Finite and known maturity. Except for some rare cases (perpetuities), fixed income securities have a limited maturity, which is known in advance. Item 1) and 2) makes it possible to construct special risk measures for bonds, like duration and convexity.3. Only downside with respect to promised cash flow. The cash flow received from a straight bond can never exceed its promised coupons and face value.4. A wide variety of instruments are available. A wide range of maturities (1 day to 30 years or more), cash flow structures (zero-coupon bonds, coupon bonds, annuities etc.), issuers (corporations, governments, municipalities etc.), and derivatives (swaps, bond and money market futures, forwards, options etc.). Since a bond or a loan is a legal contract between borrower and lender, the payoff and risk structure (payment schedule, covenants etc.) of the bond/loan is determined in this contract, and hence there is no limit to where product development can go in the debt markets.5. Lower risks, lower returns. The financial risk associated with fixed income is lower than with equities. This means lower expected and, on average, lower realised returns. This in turn calls for more precision in the pricing process, since if returns are low, every basis point counts. Since upside potential is low, paying too much (mispricing) usually means that the investor’s return is ruined for good, while on the stock markets one can always hope for a more substantial increase in value.6. The term structure of interest rates is used for valuation. When valuing stocks, a single discount rate is used to discount all cash flows. In doing this we assume that all cash flows are equally risky and that the time value of money is the same for all maturities. The wide diversity of instruments available on fixed income markets makes a more precise valuation of debt instruments possible. In the ideal case, we can find information on the interest rates for many different maturities, making it possible to value each cash flow of a bond using a separate interest rate that reflects the risk of that maturity.7. Arbitrage. The variety of instruments with very low credit risk (interbank market) or in practice no credit risk (Treasury markets) makes arbitrage and arbitrage pricing possible and links prices of instruments to each other. 2 8. Volatility is a function of time. As we will later see, the volatility of a fixed income security depends on 1) changes in the interest rate level, and 2) the duration of the bond. Thus, even if interest rate volatility is constant, the volatility of the bond will decrease with time.9. Changes in the interest rate level is the most important source of risk. The nature of debt instruments implies that the valuation process is to a large extent concerned with the time value of money. Time value of money is closely related to the level of interest rates, and hence debt instruments could also be labeled interest sensitive assets.10. Institutional details. The practice of expressing prices as interest rates (yields), or ”clean prices”, different day count conventions and compounding frequencies etc. Covenants Credit risk YIELD BENCHMARK Seniority YIELD (Default risk free yield) Real interest rate Inflation risk • many of the risks contributing to total yield are difficult to measure and price• excess return is the expected excess return from investing in corporates over Treasuries after taking into account all the risks incorporated in the spread that can materialise• excess return must be must be positive in the long run, otherwise a risk-averse investor will not invest in corporates 3 Fixed income securities can be classified in as many sectors as one likes, but the mostcommon categories are by maturity: This classification comes from the similarity of the pricng technique within one category,short term debt usually pays no interest (zero-coupon bonds, discount bonds), so there isonly one cash flow at maturity, and simple interest is used when discounting. Long termbonds usually pay interest, and compound interest is used for discounting. The government sector is usually more liquid than the corporate sector due to largermarkets, and in many countries the bulk of corporate borrowing is still mainly routedthrough bank loans, altough this has been changing in Europe since the Euro. Loans oflarge corporations are usually syndicated loans, a group of banks divides the loanbetween themselves for diversification. Most bonds and loans are "bullets", whereinterest is paid annually or semiannually, and the principal is paid back at maturity. Inmany countries, a substantial part of the government bonds are so called benchmarkbonds (or serial bonds), for example the Finnish benchmarks are: 4 • many bonds are listed at an exchange, but trading is (so far) mostly OTC• global markets by country of issuer: 20000 15000 USD billions 10000 5000 0 USA Germany France Japan Finland Government 9697 867 791 5316 77 Corporate 8805 2190 887 1606 41 Total 18502 3057 1678 6922 118 • risk management and the desire to explore cost-effective borrowing through swaps has lead to enromous global fixed income derivatives markets: 5 100000 USD billions 80000 60000 40000 20000 0 OTC OTC OTC FX Ex. FX Ex. Interest Ex. Equity Interest Equity Forwards 10723 8792 364 72 13444 422 Swaps 4509 79161 0 0 0 0 Options 3238 13746 1944 33 22024 2307 Total 18470 101699 2308 105 35468 2729 Why are interest rates not equal for all time-periods, and why is the term structure ofinterest rates usually (but not always) upward sloping? To answer these questions weneed to have a look at what factors affect required returns, and why these factors neednot be equally large for all time periods. The return for any asset can be decomposed into three factors: • the real return and expected inflation affect the returns on all assets in an economy• the magnitude of the risk premium is asset specific • first suppose there is no inflation and the investment is risk-free: the return consists solely of the investors perception of time value of money, or real return• thus, the real return says how much the investor wants his purchasing power to increase when investing• investing is delaying consumption to the future, for doing this the investor requires a compensation• if this compensation is equally large for each time period (e.g. each year), the yield curve will be flat (compensation proportional to time)• in the simplest setting, the level of the real return depends on money supply and demand: 6 • for example, suppose that investment opportunities improve and firms are willing to invest more at any interest rate level • then, interest rates must rise to induce investors to save more ⇒ investors require a higher compensation to postpone a larger amount of their consumption • if there is inflation in the economy, investors will require a premium over the real rate equal to the expected inflation rate for the investment horizon • if inflation is constant, this will result in a still flat, but higher yield curve • thus, still ignoring risk premiums, the required nominal interest rate (rn) on a riskless B B security depends on: 1) the real required return (rr). and 2) the expected inflation B B [E(i)] is approximately: rn ≈ rr + E (i ) Example: An investor is investing for 1 year, and wants the purchasing power of hisU U money to increase with 3% over the next year. This is his required real return, acompensation for postponing his consumption 1 year. Also, the investor expects theinflation to be 2% from today to 1-year ahead. Thus, his nominal required return is • a security that has no default risk is considered riskless with respect to default risk• for example government securities are considered free of default risk (or at least have the lowest possible level of default risk)• a risk premium must be added on top of required real returns and expected inflation for issuers that have default risk• but even in the treasury markets we typically observe that interest rates (for example yields) increase with maturity• interest rate risk (typically measured by duration) increases with maturity 8 • in this chapter we assume there is no credit risk, such that money can be moved back and forth in time without caring about the riskiness of future payments• nobody has ever claimed that bond calculations are fun or interesting, but given the size of the market and the amount of money potentially lost because one simply didn’t know, one cant’t ignore the subject• let’s have a look at a some numbers we can use to describe a coupon bond: We can make some observations: first, we note that the PV is higher than the face value.Second, we note that the coupon rate (10%) is higher than the yield to maturity (what is ayield to maturity anyway?). Third, we note that the zero-coupon rate (what’s that again?)is higher than the yield. Fourth, we have something called par yield (what?) which isdifferent from all previous interest rates (coupon, zero, yield). Fifth, we note that we areconfronted with four different interest rates: the coupon rate, the yield, par yield, and thezero-coupon rate. The final blow is that none of these is the return of the bond, despiteits ”fixed income” features. All these relations are not an accident: the price and face value are relatedthrough coupon rates, yields, and zero yields. This example should make it clear that theexpression ”interest rate” can mean a variety of things. In the following chapter(s) we willexplore these concepts in detail. • stock returns and standard deviations are usually expressed as percent per year• a stock return in the US has the same interpretation as a stock return in Finland• interest rates, however, come in many varieties and are usually not directly comparable• each market and currency has its own agreed upon rules of how to convert a discount rate into a price or the other way around: 1. when should one use simple interest, and when compound interest? 2. if compound interest is used, what is the frequency of compounding? 3. how should one count days to arrive at a fraction of a year (one unit of time in finance is 1 year)? • rules about how to discount and to define fractions of a year are important in fixed income markets because prices can be given both as discount factors (yields) or prices• these are not as important on stock markets, since there is anyway great uncertainty about the timing and size of cash flows, and since prices are never given as yields 9 FV = PV * [1 + (r * t )] FV and PV = [1 + (r * t )] FV = future valuePV = present valuer = interest rate expressed as decimals on a per annum basist = maturity in years • compound interest is used when interest is paid and added to the principal FV FV = PV * (1 + r ) t and PV = (1 + r ) t • the usual rule is that short-term rates (money market) are treated as simple interest rates, while long-term rates are treated as compound interest rates• bonds pay interest before maturity, and the “opportunity cost” can be seen as a long- term deposit that pays interest m times a year and is added to the capital• this is standard when analysing returns on any market, for example long-term returns on stock markets always assume dividends are reinvested (= compound interest)• all interest rates are expressed as annual rates (unless stated otherwise) Example: A bank offers a 3-month deposit rate of 3.50%. If you deposit EUR 1 000U U today, how much cash do you have after 3 months? (For simplicity, assume 3 months is0.25 years) • note that the actual return earned over 3 months is only 0.875% Example: A bank offers a 2-year deposit rate of 4.25%. The deposit pays interestU U annually. If you deposit EUR 1 000 today, how much cash do you have after 2 years? • note that the actual return earned over a 2-year period is 8.68%• note that the time t, is seldom an integer value (this happens once a year), hence the need to convert a number of days to a fraction of a year by some defined rules• converting all rates to annual rates makes comparison easier• converting actual returns over N years to a one-year return (using the previous example): 10 [ r = (1 + rActual ) 1/ N ]− 1 = [(1 + 0.0868) ]− 1 = 0.0425 1/ 2 • suppose that the compounding frequency (m) is not 1 year but 0.25 years instead (interest is paid quarterly): t *m 2*4 ⎡ r⎤ ⎡ 0.0425 ⎤ FV = PV * ⎢1 + ⎥ = 1000 EUR * ⎢1 + = 1088.23EUR ⎣ m⎦ ⎣ 4 ⎥⎦ • an interest of 4.25/4 = 1.0625% is paid each 0.25 years and compounded 8 times • the higher frequency of compounding increases the return to 8.82% if the annual rate remains unchanged since interest can be added to principal more frequently • in the limit: continuous compounding when the interval of frequency becomes very small: • money market rates are simple yields and cannot be directly compared due to differences in compounding frequency• 1 month deposit can be rolled over 12 times during a year, but a 2 month deposit only 6 times• conversion to annual effective yields is required: ⎡⎡ rSIMPLE ⎤ 360 / t ⎤ Yield EFF = ⎢ ⎢1 + ⎥ ⎥ −1 ⎢⎣ ⎣ (360 / t ) ⎦ ⎥⎦ Example: Both the 30-day and the 60-day simple annual interest rates are 4%. What areU U ⎡⎡ 0.04 ⎤ 360 / 30 ⎤ Yield EFF = ⎢ ⎢1 + ⎢⎣ ⎣ ( 360 / 30) ⎥ ⎦ ⎥⎦ [ ⎥ − 1 = [1 + 0.003333] ] 12 .00 − 1 = 0.040742 = 4.0742% 11 ⎡⎡ 0.04 ⎤ 360 / 60 ⎤Yield EFF = ⎢ ⎢1 + ⎥ ⎢⎣ ⎣ (360 / 60) ⎦ ⎥⎦ [ ⎥ − 1 = [1 + 0.006666]]6.00 − 1 = 0.040673 = 4.0673% • if the simple rates are at level, the 30-day effective yield is higher because it can be rolled over more frequently• note also that the roll-over of the 30-day investment is risky, since the second 30-day rate was unknown at the beginning of the 60-day investment period • when analyzing fixed income securities, sooner or later one will be confronted with zero coupon rates (also called spot rates)• a zero coupon rate is the discount rate (yield) for a zero-coupon bond, that is for a bond paying a single cash flow received at time t• zero rates are the building blocks of all fixed income analysis, and as we will see later, using the yield of a coupon bond for valuation can lead to severe mispricing• since the zero coupon rate is the only unambiguous interest rate for a particular maturity, everything else needed can be calculated using zero rates: discount factors, coupon bond prices and yields, par yields, forwards, swap rates etc. 6.00 5.00 Spot rate (%) 4.00 3.00 2.00 1.00 0.00 0 1 2 3 4 5 Maturity (Years) • all interest rates are expressed on an annual basis (p.a.) to be more easily compared• because most securities with maturity of over 1 year pay interest, the convention is to express all interest rates for maturities over 1 year as annually or semi-annually compounded rates• thus, even if a zero-coupon bond pays no interest, we like to compare it with interest paying securities, and do this by expressing them as annually compounded rates Example: The 3-year zero-coupon rate is 4.55%. This does not mean that if you investU U U U 100 today in a 3-year zero-coupon security, you get 104.55 back after 3-years. Since thespot rate is expressed as an annually compunded rate, your investment yields: which corresponds to an actual interest over the 3-year period of 14.28%. But comparingthis figure for example with a 3-year deposit that pays 4.5% p.a. is not very meaningful.Hence, the conversion of the spot rate to an annually compounded rate. 1 1 Df 3 = t = = 0.8750 (1 + r ) (1 + 0.0455) 3 • the discount factor is the PV of one unit (1) of currency received at time t • the discount factor reflects both 1) time and 2) the discount rate • discount factors are decreasing with maturity and always between 0 and 1: 13 1.00 0.95 Discount factor 0.90 0.85 0.80 0.75 0 1 2 3 4 5 Maturity (Years) • the discount factor is also the price (in % of face value) of a zero-coupon bond• for example, the price for a 3-year zero quoted at a yield 4.55% with face value 1000 (promises to pay 1000 after 3 years) is of course: 1000 1000PV = = = 875.00 (1 + r ) t (1 + 0.0455) 3 or equivalently: • a forward interest rate is a rate set today for an investment that starts at a specified time in the future• spot rates for different maturities are linked by forward rates• e.g. the interest rate for a 1-year investment that starts in the future is called a forward rate• e.g. the 2-year spot rate, r2 (from period 0 to 2), can be expressed using the 1-year spot B B rate (from 0 to 1) and a forward rate from year 1 to year 2, which we denote f12 : B B r2 B B r1 B f12 B B B 2. invest at the 1-year spot rate r1 and roll over the deposit with the forward. f12 B B B B • since all rates (r1, r2, and f12) are known today the two investments can be compared: B B B B B B (1 + r2 ) 2 = (1 + r1 ) * (1 + f 12 ) • this is an important arbitrage statement: the payoff from the two investments are known today, and must be the same to prevent arbitrage• if, for example: (1 + r2 ) 2 > (1 + r1 ) * (1 + f 12 ) • we could borrow at the 1-year rate, roll over the borrowing with the forward and invest at the 2-year rate for an arbitrage profit (since all rates are known today)• note that the time periods need not be 1 year, they could be e.g. 3 months, and show how 3-month forwards are linked to 3- and 6-month money market rates• the figure below shows how spot rates are built up of one-period forward rates: r1 B B r2 B B r3 B B r4 B B r5 B B (1 + r2 ) 2f 12 = −1 (1 + r1 ) (1 + rt ) tf n ,t = −1 (1 + rn ) n Example: Assume the 1-year spot rate is 4.00%, the 2-year spot rate is 4.30%, and the 3-U U year spot rate is 4.55%. What are the one-year forward rates for year 2 and 3? (1 + 0.0430) 2 f12 = − 1 = 1.046009 − 1 = 0.046009 = 4.60% (1 + 0.040) (1 + 0.0455) 3 f 23 = − 1 = 1.050518 − 1 = 0.050518 = 5.05% (1 + 0.0430) 2 • most bonds pay annual or semi-annual fixed interest payments, called coupons• coupon is paid on the face value, and is thus for fixed rate bonds a fixed value, since the face value of a bullet bond does not change• the interest paid can also be a floating rate, based on some benchmark interest rate (e.g. LIBOR), and is reset at each coupon payment date (FRN= floating rate notes)• the coupon rate is usually set to reflect the current interest rate level, and rounded to the nearest 25 or 12.5 basis points, and the issue price adjusts to reflect the difference between investor’s required yield and the coupon rate • suppose the (rising) term structure previously used applies, and an investor chooses between two bonds by the same issuer: • what return should the investor require from investing in these two bonds?• we know that r3 = 4.55% so this seems a reasonable yield for bond 1 B B • should we require the same yield from bond 2 just because the last cash flow occurs at the same time? 16 • no, there is no reason to let maturity alone determine the discount rate!• these are clearly two different bonds, 4.55% is a yield for one single payment at t = 3, and the second bond provides us with a series of payments in t = 1, 2 and 3• theoretically, a coupon bond is a collection of zero-coupon bonds, where each payment (coupon or principal) can be seen as a separate zero-coupon bond• hence, the price of a coupon bond is the sum of all the individual payments (zeros): where For a bullet bond the cash flow is coupon payments until the last cash flow at maturity T(CFT) which is the last coupon + face value. The time periods (1...T) are usually fractions B B of a year (e.g. the first payment could occur after 0.8 years, the second after 1.8 years etc.) • from the PV-equation, it would seem very odd to use r3 = 4.55% for all payments B B Example: The value of a 3-year bond that pays a 5% annual coupon on EUR 1 000 faceU U value assuming the spot rate 4.00% for one year, 4.30% for two years, and 4.55% forthree years: The coupon bond sells above par (101.283% of the face value), since the couponpayments exceed the current interest rate level (term structure of zeros). A market forzeros guarantees that the bond must be priced using zero rates: otherwise, a bond couldbe stripped and the parts (coupon and/or principal) could be sold at a different price inthe strips market. Or, one could assemble a bond from strips and sell the package as acoupon-paying bond. This arbitrage/replication approach to bond pricing is of course isdirectly applicable where a liquid zero-coupon market exists along a coupon-bondmarket. • what is the yield to maturity for a coupon bond priced using zeroes?• the yield to maturity for a zero is unambiguous: it is the zero-coupon rate• for coupon bonds the yield is the internal rate of return for the bond• thus, once the price of the bond is known, we must solve the present value equation with respect to yield (y): the yield can be found by trial-and-error (for example using a solver-function) and is y = 0.045329 or 4.5329% • note that since the yield is a kind of ”weighted average” of the zero coupon rates, and the largest cash flow (principal + last coupon) is paid at year 3, the yield is close to the longest zero rate• another, less frequently used measure is the current yield: for example: 50 50 1050PV = + + = 47.83 + 45.77 + 919.24 = 1012.83 (1 + 0.045329) (1 + 0.045329) 2 (1 + 0.045329) 3 Coupon bond: Principal Coupon 1 Coupon 2 Coupon 3 18 Stripped bond: Coupon 1 Coupon 2 Principal Coupon 3 0 1 2 3 Time • the law-of-one-price does not hold, since the stripped coupons and zeros do not have the same price if the bond is valued using the yield• now, consider the same spot rates but a bond that pays a 10% coupon: • the yield for this bond is 4.5188% or 0.014% lower than for the the 5% coupon bond• despite the same spot rates and the same maturity, bonds can have different yields: • a tricky (that is, impossible) question to answer is ”what is the yield for 3-year bonds”: there is no unambiguous answer to that question• the only result that prevails is that the only unambiguous interest rate for a certain maturity is the zero-coupon rate• a yield for a 3-year coupon bond is clearly not a true 3-year rate since cash flows are distributed over the time span 1-3 years• even if the yield has limitations in measuring the interest rate level, it is still a convenient “summary” measure, and used as such in practice• one more example of the pitfalls of pricing with the yield: Maturity: 3 yearsFace value: EUR 1 000 000Bond type: Annuity 19 Coupon: 5.00%Annuity: EUR 367 208.56 annual ⎡ r (1 + r ) t ⎤ ⎡ 0.05(1 + 0.05) 3 ⎤Annuity = PV * ⎢ ⎥ = 1000000 * ⎢ ⎥ = 367208.56 ⎣⎢ (1 + r ) − 1 ⎦⎥ ⎣⎢ (1 + 0.05) − 1 ⎦⎥ t 3 You work for the treasury, and your task is to price the bond to decide which treasuryauction bids to accept. You observe some treasury bond yields on the market: 1 year: 4.00%2 years: 5.00%3 years: 6.00% 3 years 5.933% You have never even heard about the CEFA-program, and hence, you are unaware ofterm-structure theory and bond mathematics, and you decide to price the new annuitybond using the 3-year treasury yield for the 5% coupon bond. You find that the priceshould be (you discount the annuities with the yield): Now, your pricing adventures of having applied a 5% coupon bond yield to an annuityhas three consequences: 1) you mispriced (underpriced) the annuity with about 70 basispoints, 2) investors would kill to lay their hands on the annuity, 3) you will lose your jobor alternatively the Treasury will send you to next year’s CEFA program. The following table will highlight the problem of using the yield for a particular cash flowstructure when pricing a different cash flow structure: • we now know that the yield for bonds of a certain maturity will depend on the coupon rate (or more generally the cash flow structure, for example the annuity)• thus, it is impossible to say what the yield is for a certain maturity• a commonly used yield is, however, the par yield• a bond whose price equals its face value is said to sell at par (100% of the face value)• the yield for such a bond is then the par yield• for par bonds: • the par yield for maturity T can easily be calculated using discount factors: (1 − Df T ) Yield Par = T ∑ Df i =1 i which says that you 1) calculate the discount factors for all cash flows upt to T, 2) divide 1 minus the discount factor for maturity T with the sum of all discount factors. Example: Calculate the par yield for 3-year bonds. From previous tables, we know thatU U the discount factors for years 1 to 3 are: 0.9615, 0.9192, and 0.8750. Then: (1 − 0.8759) Yield Par = = 0.045344 (0.9615 + 0.9192 + 0.8750) which is 4.5344%. Thus, if we would issue a 3 year bond with 4.5344% annual coupons, it would trade at par. We can complete the table: 6.00 5.50 5.00 Rate (%) Zeros 4.50 Forwards Par yields 4.00 3.50 3.00 0 1 2 3 4 5 Maturity (Years) • from the previous section, it should have become clear that in some circumstances, the yield to maturity can be a misleading measure for coupon paying bonds• however, since the cash flows for most bonds look similar (fixed coupon payments inside a certain range, no negative cash flows), the yield is a convenient summary measure of the bond price relative to its cash flows as an annual per cent rate• one should, however, be aware of what a yield is and what it is not: • one could easily think that the yield for a bond is the promised return for the bond, since the bond is a ”fixed income” security• the yield = return only for zeros that are held until maturity, in all other cases this will not hold• the yield is a discount rate, not a return!• we will analyze a special case when the yield at the time of purchase actually will equal the return: calculated the yield, y = 4.5329%. Suppose we intend to keep the bond until maturity,and want to calculate the return over this investment horizon (3 years). We have aproblem of reinvesting the 5% annual coupons, but we assume this can be done at areinvestment rate that equals the yield. Then the future cash flows are: 1st Coupon: P P 50*(1 + 0.045329)^2 =56.63572nd Coupon: P P 50*(1 + 0.045329) = 52.2665 22 The price of the bond was PV = 1012.83, so the horizon return is: 1/ 3 ⎡1156.90 ⎤ r=⎢ − 1 = 0.045329 = 4.5329% ⎣1012.83 ⎥⎦ which equals the yield at the time of purchase. Anybody would, however, agree that thisscenario is unrealistic: 1. The bond is seldom held until maturity. The interest rate level at the time of selling the bond is uncertain, and hence the price is uncertain ⇒ price risk 2. The coupons can usually not be reinvested at a rate that equals the yield. This would require a flat term-structure. The reality is uncertainty about the future value of the reinvested coupons ⇒ reinvestment risk • it’s clear that today’s yield cannot capture all these sources of return• of course, let’s not forget that for example treasury bonds usually have higher yields than treasury bills, and also tend to outperform treasury bills in terms of return• the point is that the yield is merely and indication of return, not a promise • what this means is that yields for bond portfolios can not be calculated like returns for stock portfolios Example: Let’s construct a simple bond portfolio that contains one 1-year zero couponU U bond, and one 5-year coupon bond that pays 5% annual coupons. We use the termstructure from previous examples to price the bonds, and assume that both bonds havea face value of 1000: First, let’s try to calculate the portfolio yield by treating yields as returns: NrP = ∑ wi ri = 0.4887 * 0.04 + 0.5113 * 0.048631 = 0.044413 i =1 The only correct way to calculate the yield on a bond portfolio is, however by solving forthe yield for the portfolio, given the portfolio price and cash flows: 1000 50 50 1050 + + +…+ = 1967.49(1 + y ) (1 + y ) (1 + y ) 2 (1 + y ) 5 where, in this example, the first cash flow comes from the first bond, and all other cashflows from the second bond. We solve the yield (y), and find that: y = 0.0471349 = 4.7135% Note the difference (over 27 basis points!) between the true yield y = 4.7135%, and y =4.4413% calculated earlier. • of course, nothing prevents the bond portfolio manager from expressing the yield of his portfolio as a weighted average, but in that case care should be taken to make clear how this figure has been obtained• to a very close approximation, the portfolio yield can be calculated using weights, if the equation is adjusted for modified duration • suppose you need zeros for pricing, but no zeros with the same credit risk exist• zero-coupon or spot rates reflecting a specific level of default risk can be found by: • using observable zero-coupon rates for pricing coupon bonds may be problematic: 1. Liquidity. Lower liquidity in the zero market might lead to higher yields. 2. Taxes. Zeros and coupon bonds might be taxed differently along the whole maturity spectrum, which translates to differences in required yields. 24 maturity, but no zero market exist. Instead, he observes the prices for the followingbonds: 1000 − 1 = 0.04 961.54 Turning to the 2 year zero rate we use the 2 year coupon bond and we now know that: 45 1045 + = 1003.88 (1 + 0.04) (1 + r2 ) 2 Clearly, there is only one solution for the 2 year zero rate (r2) that satisfies the equation. B B r2 B B = 0.043 = 4.30% does the trick. We continue in the same fashion with the 3 year coupon bond: 50 50 1050 + + = 1012.83 (1 + 0.04) (1 + 0.043) 2 (1 + r3 ) 3 r3 B B = 0.0455 = 4.55% (which does not surprise the careful reader, who might have suspected that the couponbonds in the example were priced using the same term structure as before.) • since swaps are priced at ”par” (the swap rate is a par-yield), and a ”price” of 100 can be assumed: 104.50 − 1 = 0.045 100 and 4.70 104.70 + = 100(1 + 0.045) (1 + r2 ) 2 • bonds and swaps may pay semi-annual or even quarterly or monthly coupons, and hence there is a need to handle spot rates and forwards for higher compounding frequencies than 1 years• in general, the present value formula can be expressed: CFPV = mt ⎡ rt ⎤ ⎢1 + m ⎥ ⎣ ⎦ rtB B = the zero coupon rate for maturity tm = the compounding frequencyt = the maturity of the cash flow in years 1Df t = rt t *2 (1 + ) 2 1 1Df t = = = 0.9274 rt t *2 0.0768 1*2 (1 + ) (1 + ) 2 2 ⎡ r3 3 ⎤ ⎢ (1 + 2 ) ⎥f 23 = 2*⎢ − 1⎥ = 0.0771 ⎢ (1 + r2 ) 2 ⎥ ⎢⎣ 2 ⎥⎦ • so far, we have worked in a fairly unrealistic setting: we have analyzed bonds and rates with maturity of integers of one year• the reason for abstracting from details is to make the concepts and technique clear• we will now take a small step from the classroom towards the cruel world of day count conventions and accrued interest• reading stock market quotes is quite clear: you can observe the price at which you buy and the price at which you sell• in fixed income markets, things become a mess: prices are frequently quoted as yields, or in percent of face value less accrued interest, which means that just by looking at bond quotes you can never tell what the price is• further, a yield quote is not unambiguous across the world: 5% in the US treasury markets does not mean the same thing as 5% in the Finnish or German treasury markets: there are differences in day count conventions and compounding frequency• as an example, compare the following zero-coupon bonds: What’s wrong? Shouldn’t the price also be equal? No, since all Bund quotes are based onannual compounding, while US Treasury bond quotes are based on semi-annualcompounding they will have different prices if the yields are the same. • the lesson is that one should always be aware of what market conventions apply to the interest rate you are analyzing • the next section is by no means intended to give a comprehensive treatment of the subject, but merely to introduce the reader to some concepts, and to make the reader aware of the pitfalls that exist • the bond market is like no other place: 31 days can be 30 days, and a year can be more or less than 365 days • recall that all interest rates are expressed on an annual basis • day count conventions deal with how to compute fractions of a year • to give an example of what day count basis means: Example: Suppose you are investing in a 1-month short-term deposit. The financialU U institution promises an interest of 4.00%. This is of course a per annum figure. Since theinterest rate is an annual rate, we must know how large a fraction is this particular monthof 1 year. Suppose we count the days, we find that there are 31 days in that month. Wealso know that there are 365 days in a year, so the maturity of the investment in years is: 28 31 t= = 0.084931 365 ⎡ 31 ⎤ FV = 100 * ⎢1 + 0.04 * = 100.3397 ⎣ 365 ⎥⎦ This day count basis is called ”Actual/Actual”, because all days are counted, in our case ”31/365”. This need not be the case, since there exist many ways of counting days. The most common day count conventions include: Actual/Actual The denominator is the number of days in the coupon period times the coupon frequency. Actual/360 Like Actual/365, but always uses 360 (assumes there are only 360 days in a year). (Euro money market) 30/360 Assumes that there are 30 days in each month and 360 days in a year. In our previous example, we would have measured the time period as only 30 days instead of 31, and divided with 360 (30/360 = 0.083333). There are som further variations for this rule. CF PCD = ⎡ t ⎤ 1 + ⎢r * ⎥ ⎣ 360 ⎦ Example: The maturity of a money market security is 30 days, face value EUR 1 000U U What’s the price? Note that bid and ask are from the dealer’s point of view: the dealerbuys at 3.01%, and sells at 2.96%. Using the bid to find out what the dealer is willing topay for the security: 1000000 1000000 PCD = = = 997497.94 ⎡ 30 ⎤ 1002508 . 1 + ⎢0.0301 * ⎣ 360 ⎥⎦ The ask (2.96%) again corresponds to a price of EUR 997 539.40. That is: • bond prices are expressed as yields or prices as percent of the face value• to calculate the price in currency, one has to know the face value, day count basis, and compounding frequency 1.3.2000: The maturity of the zero is 15.35 years using Actual/Actual day count basis. Further weneed to know that on the Bund market, annual compounding is used. If the face value ofthe zero is EUR 100 000, the bid price in euros is: EUR100000 PV = = EUR 41121.70 (1 + 0.0596)15.35 41121.70 K= = 0.4112 = 41.12% 100000 30 • suppose that the same market quotes (yield and price quote) are observed on the US Treasury STRIPS markets• is the price in currency the same?• no, since US Treasury yields are semi-annual (assuming day count basis is the same): USD100000PV = 15.35*2 = USD 40596.29 ⎡ 0.0596 ⎤ ⎢1 + 2 ⎥ ⎣ ⎦ • if there should have been differences in the day count basis between the markets, this difference would have shown up in the calculation of maturity, and the fraction of a year (0.35) might have been different • bonds are usually quoted in per cent of their face value, e.g. 110.827% or just 110.827• the yield to maturity (YTM) of a bond is another way to express the price• recall that the present value of a bond is simply: n CFtPV BOND = ∑ t =1 (1 + rt ) t Once the yield to maturity is known, one can of course to cut some corners use the yield: n CFtPV BOND = ∑ t =1 (1 + y ) t • in most of the forthcoming examples, we will use the yield to demonstrate the calculations• let’s start our example of dirty and clean prices by pricing a bond: 31 Example: Suppose todays date is 17.1.1997, and a government bond that maturesU U 15.3.2004 and pays a CPN of 9.50%. Assume a yield of 5.55% and, a face value of EUR1 000 000. What is the PV of the bond on 17.1.1997? There are 57 days between 17.1and 15.3 which is 0.1562 years under the Actual/Actual basis so: • note that: 1. the value of the first coupon can, depending on the market conventions, be calculated using simple or, as in this example, compound interest 2. there may not be exactly 1 year between the coupon payment dates if payments occur on weekends or holidays, this has not been taken into account here • the present value is called the ”dirty price”, ”full price”, or ”invoice price” • what are ”clean prices”? • the price that dealers quote is the clean price, not the PV (dirty price): Clean price = Dirty price – Accrued coupon interest since last coupon payment v AI = * rCPN * N 365 PV BOND − AI K= N 32 Example: Using the bond from the previous example we know that:U U (Note again that here, we abstract from taking into account delivery days applied on themarket (usually T +1...+3), that is, the bond and the money does not move today, andyou actually trade 1-3 day forwards). The days of accrued interest v = 365 – 57 = 308 using actual/actual day count basis. We can now compute: 308 AI = * 0.095 * 1000000 EUR = 80164.38 EUR 365 and hence 1307995.13 − 80164.38 K= = 1.22783 = 122.783% 1000000 Remember that the even if the quote is 122.783%, you still pay the dirty price 1 307995.13 for the bond (that’s why the dirty price is also called the invoice price). • the present value (dirty price) will vary according to the number of days to the next coupon payment: immediately after a coupon payment, the PV will fall, and then rise again as the next coupon approaches in time• the clean price, on the other hand behaves more smoothly Example: Consider the same bond that matures 15.3.2004 and pays a CPN of 9.50%.U U Assume a (constant) yield of 5.55% and, for ease of exposition, a face value of only EUR100. Starting from the CPN date 15.3.1996, we calculate the PV for each month. Notehow the PV falls on the CPN date 15.3.1997, just to start rising again. (This example stilluses the 30/360 day count basis). 33 • the clean price (K) of the bond approaches 100 (par) when maturity decreases• the dirty price (PV) of the bond approaches 100 + last coupon when maturity decreases Example: Consider a bond that matures 18.4.2006. Assume the yield remains at 6.00%.U U • a discount bond would have started below par and approached par from below 34 Since cash flows for bonds are usually fixed, a price change can come from two sources: The yield-price relationship is inverse, and we would like to have a measure of howsensitive the bond price is to yield changes. A good approximation for bond pricechanges due to yield is the duration, a measure for interest rate risk. For large yieldchanges convexity can be added to improve the performance of the duration. A moreimportant use of convexity is that it measures the sensitivity of duration to yieldchanges. Similar risk measures are used in the options markets are the delta and gamma. • we again discuss interest rate changes in terms of yield changes: this is more convenient as the yield is the mostly used interest rate measure for coupon bonds• when yields increase, bond prices decrese• when yields decrease, bond prices increase• for small yield changes, the percentage price change is roughly the same whether the required yield increases or decreases• for large yield changes, the percentage price increase is larger than a price decrease Example: On 17.1.1997, the (dirty) price of the RoF2006 Government bond is 114.060,U U and the yield is 6.00%. Consider the impact of an one percent yield increase/decrease: 180.00 160.00 140.00 Dirty Price RoF2001 120.00 RoF2006 100.00 80.00 60.00 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Yield 4.2. Duration i) Macaulay duration/(1 + y) ii) The % price increase (decrease) in the bond price if the yield decreases (increases) by a unit of 1%. CFt * t i 1 ⎡ CF1 * t1 CF2 * t 2 CFn * t n ⎤ (1 + y ) ti n Duration( D MAC ) = *⎢ t1 + +...+ =∑ PV BOND ⎣ (1 + y ) (1 + y ) t 2 (1 + y ) tn ⎥⎦ t = t 1 PV BOND • since the yield is used to discount, the Macaulay duration assumes that the term structure is flat and that yield shifts are parallell• the duration of a zero coupon bond equals its maturity• for example, N = 100, y = 3.54%, PV = 93.28 ⎡ 100 * 2.00 ⎤ * [186.56] = 2.00 1 1 Duration ( D MAC ) = *⎢ ⎥= 93.28 ⎢⎣ (1 + 0.0354) 2 .00 ⎥⎦ 92.28 • Macaulay duration for different maturities (T), yields, and coupon rates (annual): • the approximate percent price change for a 1.00% yield change (100 bps) is given by the modified duration: D MAC Duration( D MOD ) = (1 + y ) The percent price change (dP/P) for any yield change dy: dP = − D MOD * dy P and hence we have the EUR price change (dPV) for any yield change dy: dPV = − DMOD * PV * dy • note the ”-” sign before the expressions, indicating the inverse relationship between yield change and price change D MOD PVBP = * PV 10000 and says how much the value of the bond changes in EUR when the yield changes with 1 bps (0.01%). Example: Calculate the modified duration and the PVBP for the same bond:U U DMOD 1.8417 PVBP = * PV = * 1141635.55FIM = 210.26 EUR 10000 10000 Example: If the yield increases by 1.00% to 4.54%, how much will the price decrease?U U The new price should then be: 1 141 635.55 – 21 026.00 = 1 120 609.55 EUR But recalculating the price using the yield 4.54, we find that the true price should be EUR 1 120 905.42, and the error is EUR 295.87 • the error occurs because duration assumes a linear price-yield relationship when it in fact is convex • between coupon payments duration decreases one-by-one with time if yields stay unchanged• at a coupon payment duration jumps up and increases ⇒ in the long run duration decreases more slowly than time• does this matter in the practical sense?• duration increases after a coupon ⇒ the bond becomes more sensitive to yield changes after a coupon payment• but this is only in % terms, the absolute (EUR) value change is unaffected Example: The RoF2006 bond pays a 7.25% coupon 18.4.1997. Consider what happensU U to duration and volatility due to a 0.10% yield increase immediately before and after thecoupon payment: The % change in value of the bond changes, but the change in EUR value changes onlybecause of the slight duration change from 17.4.1997 to 18.4.1997. • does the duration jump mean that we are suddenly exposed to immunization risk?• the duration of the investor’s portfolio now consists of the bond and 72 500 EUR in cash (cash has zero duration)• but the investor still has to decide: 1. should not invest cash in the same bond (duration will exceed target) 2. if the cash is invested in a security with any significant duration, a part of the bond (portfolio) must be sold and invest proceeds in shorter duration assets • duration can only measure parallell yield changes, and does not tell us where on the yield curve the largest risks are located• for a single bullet bond, the largest risk of course comes from the last payment of face value + last coupon, since it is: • for a bond portfolio or a more complex product than a bullet one can perform a more detailed analysis of interest rate risk along the whole yield curve using key rates• we use the following bond as an example: N = 100Maturity = 5 yearsCoupon rate = 5% (annual) We compute the PV, Fisher-Weil duration, and Key rate durations assuming the termstructure below: rt B B Df CF PV Fisher-Weil Key rate (CF*t)*Df duration1 4.00% 0.961583 5.00 4.8077 4.8077 0.04602 4.30% 0.919245 5.00 4.5962 9.1925 0.08763 4.55% 0.875040 5.00 4.3752 13.1256 0.12484 4.75% 0.830585 5.00 4.1529 16.6117 0.15775 4.90% 0.787268 105.00 82.6631 413.3157 3.9193 100.5952 4.5435 4.3354 For example, the 5 year key rate duration for a +/- 1% zero rate change is calculated: PV+ − PV−DA = 2 * PV0 * drt PV+ B B = the price of the bond if the zero-coupon rate for maturity t decreases with 1%PV- B B = the price of the bond if the zero-coupon rate for maturity t increases with 1% and we have 40 by “common sense”, calculate the average absolute price change for a +/- 1% in rates: which is the price responsiveness if the 5-year zero rate changes 1% and all other ratesremain unchanged. 4.4. Convexity ⎡ n t (1 + t ) * CFt ⎤ ⎡ 1 ⎤Convexity = ⎢∑ t +2 ⎥ * ⎢ PV ⎥ ⎣ t =1 (1 + y ) ⎦ ⎣ BOND ⎦ dP 1 = * ( Convexity ) * ( dy ) 2 P 2 1 dP = * ( Dollar − convexity ) * ( dy ) 2 2 Example: Calculate the convexity of the bond used in previous examples. The coupon isU U Example: If the yield increases by 1.00% to 4.54%, how much of the price decrease isU U due to convexity? which is only EUR 3.78 less the actual decrease of -20 730.13 • note that convexity is always a positive number, correcting the price upward• sometimes convexity is expressed as: • one could argue that convexity has value since the price of a highly convex bond • one might argue that investors should be willing to pay more for a convex bond, particularly when yields are volatile • at an investment horizon equal to the bond’s duration these two effects will (approximately) offset• duration is the balance point between market risk and reinvestment risk• if the investors horizon is h: 1. if h = D ⇒ dW/dy = 0 ⇒ no risk 2. if h < D ⇒ dW/dy < 0 ⇒ market risk 3. if h > D ⇒ dW/dy > 0 ⇒ reinvestment risk • note that all formulas assume a single yield y ⇒ a flat yield curve is assumed• convexity is beneficial for an investor who buys a bond with duration equal to his horizon, and the yield curve shifts once to some arbitrary level − in case of a sudden, large yield change the investor is more protected than with a bond with lesser convexity − in the case of a duration matched to the horizon, and a convex bond, a yield increase will yield a higher end-of-period wealth, since the value of the reinvested coupons exceed the loss of the lower redemption value 43 − a yield decrease will yield a higher end-of-period wealth, since the higher redemption value will more than compensate for the lower reinvested coupon values Example: An investor buys a bond with Macaulay duration of 3.3841, and assume forU U simplicity that the investor’s horizon equals this duration. Thus, the investor isimmunized, and he is going to sell the bond 0.4714 years before maturity, since thematurity is 3.8556 years. Suppose the yield is initially 5.15%, and now consider the effectof a sudden, immediate yield change to 4.15%, and 6.15%, respectively: • note that a flat term structure is assumed (all coupons reinvested at the yield)• the change in the reinvestment values of the coupons just about offset the change in the redemption value of the bond• the more convex the bond, the larger would the return changes have been• convexity is nearly irrelevant if yields change smoothly and continuously rather than in large, sudden jumps − if yields change smoothly in small increments, the investor has the opportunity to adjust for duration changes continuously − thus, no large yield changes like in the previous example will occur• convexity is harmful if there is uncertainty about how the yield curve will change − the effect of changes in the shape of the yield curve on the duration of a bond will be greater, the greater the convexity − this is beacuse convexity implies larger dispersion of cash flows − thus, convexity implies that there is more uncertainty about how the duration of the bond will behave when the yield curve changes 1. duration drift over time not equal to time (duration decreases more slowly than time)2. yield changes will change duration3. Macaulay-duration based: immunizised only if yield curve is flat and changes are parallell Contingent immunization Multiperiod immunization • a stream of obligations• immunize every payment separately Dedicated portfolio • calculating duration, modified duration and convexity for a bond portfolio is easy if one assumes that all bonds in the portfolio has the same yield: N D P = ∑ wi Di i =1 where then: N DMAC = ∑ wi Di = 0.4887 * 1.0000 + 0.5113 * 4.5475 = 2.8138 i =1 45 NDMOD = ∑ wi Di = 0.4887 * 0.9615 + 0.5113 * 4.3366 = 2.6872 i =1 • assume three bonds indexed as i = 1,2, and 3, and that we try to obtain a higher return by selling bond 2 and buying bonds 1 + 3• to satisfy the cost constraint the butterfly requires that Q2 * P2 = Q1 * P1 + Q3 * P3 PVBP = price value of a basis point (in EUR per 1 000 000 face value) ⎡ P2 * PVBP3 − P3 * PVBP2 ⎤Q1 = ⎢ ⎥ * Q2 ⎣ P1 * PVBP3 − P3 * PVBP1 ⎦ ⎡ P1 * PVBP2 − P2 * PVBP1 ⎤Q3 = ⎢ ⎥ * Q2 ⎣ P1 * PVBP3 − P3 * PVBP1 ⎦ 46 Example: (This example is based on actual market conditions on the Finnish TreasuryU U Note that we express P in percent. The PVBP is however expressed based on EUR 1 000000 face value. This scaling is a matter of convenience and does not affect thecalculations. and Thus you should buy Bond 1 to a face value of 532 017 EUR and Bond 3 to a face valueof 560 655 EUR which equals the price of the bond to be sold (Bond 2). This also shows that it isstraightforward to weight the butterfly as PV in EUR, since the face value Q can bemultiplied with the % price P. The values satisfy the risk constraint since which is equal to the PVBP of Bond 2, and equivalent to using modified durations andPV:s: (0.4969*3.2184)+(0.5031*6.1123)=4.6743 47 where 0.4969 and 0.5031 are the weights in the butterfly based on the PV:s. The PV ofthe portfolio is 126.329, and the weights are 62.7732/126.329 = 0.4969 and63.5558/126.329 = 0.5031 • thus, the butterfly gives away 3.58 bp of yield, but increases convexity with 2.11• the change in the value of a bond is dP = − D MOD * PV * dy PVBP * σ * 10000s = D MOD * σ = PV ( PV1 * PV2 * D MOD1 * D MOD2 * Corr1,2 * σ 1 * σ 2 ) + ( PV3 * PV2 * D MOD3 * D MOD 2 * Corr3,2 * σ 3 * σ 2 ) CorrdP = S 2 * S1,3 Example: Suppose the yield change correlation matrix, yield change standard deviations,U U (Yield changes are daily closing quoted bid yields from 2.1.1997 - 7.11.1997) which is slightly lower than the risk of Bond 2. The correlation of the change in value ofthe portfolio and the single bond is: CorrdP = 0.9606 B B • note that We will consider three major fixed income derivative instruments available on mostmarkets: Forward Rate Agreements (FRA:s), swaps, and bond futures. FRA and swappricing are straightforward applications of the term structure of spot rates in theinterbank market. Bond futures pricing relies on arbitrage between cash and futuresmarkets. • FRA:s or Short Interest Rate Futures are used to hedge future short term borrowing or lending in the money market, or to speculate on future interest rates• the future interest rate (FRA or future rate) is fixed today• underlying instrument: usually a 1- or 3-month deposit or borrowing in a certain reference rate, e.g. 3-month LIBOR or EURIBOR or other money market rate• expiration usually on the third Wednesday in March, June, September, and December• the buyer makes a future borrowing in the reference rate (buys money)• the seller makes a future deposit in the reference rate (sells money)• cash settlement• how is the rate for an FRA determined?• recall from the relationship between spot rates and forward rates that: (1 + r2 ) 2(1 + f 12 ) = ⇒ (1 + r1 ) * (1 + f 12 ) = (1 + r2 ) 2 (1 + r1 ) [1 + r * (t 1 1 ] [ ] [ / 360) * 1 + f 12 * (t12 / 360) = 1 + r2 * (t 2 / 360) ] where f12 stands for the FRA-rate, or the forward rate directly: B B ⎡ 1 + r2 * (t 2 / 360) f 12 = ⎢ [⎤ − 1⎥ * (360 / t12 ) ] ⎢⎣ 1 + r1 * (t1 / 360) [⎥⎦ ] Example: Suppose that on January 17, the 2-month (actual: 61 day) money market rateU U is r1 = 2.97%, the 5-month (actual: 152 days) money market rate is r2 = 3.03%, and thus B B B B t1 = 61 and t2 = 152. What is the correct FRA rate for a 3-month (actual: 91 days) that B B B B t2 = 152 B B ⎡ t ⎤ (rR − rFRA ) * ⎢ *N ⎣ 360 ⎥⎦ Gain / Loss = ⎡ t ⎤ 1 + ⎢rR * ⎣ 360 ⎥⎦ ⎡ t ⎤ (rFRA − rR ) * ⎢ *N ⎣ 360 ⎥⎦ Gain / Loss = ⎡ t ⎤ 1 + ⎢rR * ⎣ 360 ⎥⎦ Example: On January 17th, a firm decides to hedge a EUR 5 000 000 future deposit toU U P P be made on March 19th. The depo matures on June 18th, or in 91 days. The firm sells 5 P P P P March FRAs. The bid for FRAs is 3.0548. On March 19th , the 3-month EURIBOR is at P P 2.96. ⎡ 91 ⎤ (0.0306 − 0.0296) * ⎢ * 5000000 ⎣ 360 ⎥⎦ 119817 . Gain / Loss = = = 1189.27 ⎡ 91 ⎤ 1007482 . 1 + ⎢0.0296 * ⎣ 360 ⎥⎦ The gain from the contract is EUR 1189.27. On March 19th the buyer thus deposits EUR P P To check that this really is the payoff at the FRA contract rate of 3.0548: 1. buy the bond today at the cost PV and finance the purchase by borrowing until future expires 2. buy future at the futures price F, and pay F when future expires • implies that: 1. with both strategies 1 and 2 you own the bond at the future time t 2. no net cash outlay today 3. cost of both strategies are known today 4. cost of both strategies must equal to prevent arbitrage 52 ⎡ t ⎤ F = S * ⎢1 + r * ⎣ 360 ⎥⎦ Example: The PV of a Government bond is 1 100. The future expires in 60 days, andU U the 60 day money market rate is 3.50%. What is the futures price F? ⎡ 60 ⎤ F = 1100 * ⎢1 + 0.035 * = 1106.42 ⎣ 360 ⎥⎦ 1. Buy the bond today, and finance it at 3.5% at the cost: 1 106.42 2. Make a futures contract today to sell the bond at F = 1 110 3. After 60 days you deliver the bond to the buyer of the future and get F = 1100 in cash and pay off your borrowing 1 106.42 4. Your riskless arbitrage profit is thus 3.58 • a bond can be purchased by financing the purchase in the sale and repurchase (repo) market (if such a market exists)• in a repo the financial asset is is lent (“repo’d out”) to a second party who in turn as a collateral lends an equal amount of cash to the owner of the asset (in practice the collateral is usually slightly higher than the bond’s PV)• when the repo is terminated, the second party returns the bond to the owner, and the owner returns the cash loan (collateral) plus interest to the second party• the interest rate paid on the cash loan is called the repo rate 1. Short the bond in the repo market (borrow the bond). Pay collateral 1 100, which earns 3.5% interest 2. Finance the collateral by selling bond at market price S = 1 100 3. Make a futures contract to buy the bond back at F = 1 105 4. After 60 days you get the bond from the seller of the futures contract, and deliver to the bond lender in 1). 5. You pay F = 1 105 for this bond, but get 1 106.42 from interest paying collateral. 6. Your riskless arbitrage profit is 1.42 Example: Consider the same bond as before, but now the bond pays a 5% (50 EUR)U U coupon after 30 days. The coupon can be reinvested at the 30 day money market rate (rR) B B ⎡ t ⎤ ⎡ tR ⎤ F = S * ⎢1 + r * − ⎢ + 360 ⎥⎦ CPN * 1 r * ⎣ 360 ⎥⎦ ⎣ R ⎡ 60 ⎤ ⎡ 30 ⎤ F = 1100 * ⎢1 + 0.035 * ⎥ − 50 * ⎢1 + 0.03 * = 1106.42 − 50125 . = 1056.30 ⎣ 360 ⎦ ⎣ 360 ⎥⎦ Why? If you want to hold the bond after 2 months, you can: 1. Buy the cash bond now and finance it at 3.5%. The cost is EUR 1106.42, and the EUR 50 coupon is reinvested at 3.00%: EUR 50.125 which can be deducted from your total costs from buying the bond: EUR 1106.42 - EUR 50.124 = EUR 1056.30 total after 2 months.2. Buy the future. It's now clear that the futures price F must equal the cost in 1., since F is also paid after 2 months in exchange for the bond, and both strategies lead to holding the bond after 2 months. • similar arbitrage positions like demonstrated earlier can be created for a bond that pays a coupon to exploit mispriced futures contracts• one has to remember that when shorting a bond, the coupon payments belong to the owner of the bond, not the arbitrageur holding the bond short 54 Example: A bond futures contract has the (very simplified) following contractU U specifications: Unit of trading: EUR 100 000 nominal value notional Bund with 6% couponDelivery months: March, June, September, and DecemberContract standard: Delivery may be made of any Bunds on the List of Deliverable BundsDeliverable bonds: Any Bund with the following characteristics: • redemption in a single installment not earlier than 4 years, and not later than 6 years • having no terms permitting early redemption • bearing interest at a single fixed rate Further, to more clearly demonstrate the process, we assume that all bonds, whendelivered, have no accrued interest. The PV is as usual found by discounting the bond with the term structure of zeros. Tofind the conversion factor, the bond is discounted with the yield stated in the futurescontract. This value is then divided with the face value to find the conversion factor. 55 Since the future’s contract is for EUR 100 000 nominal value, and all deliverable bondshave a nominal value of EUR 1 000, this means that 100 bonds must be delivered, nomatter which bond the seller decides to deliver. The conversion factor then decides how much the buyer must pay for the 100 bonds tobe delivered, such that: Suppose that the futures contract settles at: F = 105%, and that the seller decides todeliver the 5-year, 7% bond with conversion factor 1.0421, then: Invoice price =EUR 100 000 * 1.05 * 1.0421 + 0 = EUR 109 420.50 Thus, the seller delivers 100 of the 5-year 7% bonds, and the buyer pays EUR 109 420.50 • because a rational investor will deliver the CTD, the futures will be derived from the CTD-bond• the CTD bond may of course change over the life of the futures contract • the previous examples showed how futures contracts are generally priced• in practice, bond futures prices are quoted as clean prices, and we have to take accrued interest into account when calculating the clean futures price• cash and carry pricing: you have two alternative strategies: 1. buy the bond today at K + AI and finance [K + AI] by borrowing until future expires 2. buy future at F + AI today, and pay F + AI when future expires • alternatively you could think that you have the money now and can earn interest on [K + AI] by investing this amount in the money market 56 1. with both strategies 1 and 2 you own the bond at time t (when future expires) 2. cost of both strategies are known today 3. cost of both strategies must equal more compactly • the left-hand side of the equation: cost of K + AIc financed in the money market to B B rearranging Example: On January 17th, a Treasury bond with 10% CPN bond trades at K = EUR 1U U P P 218 000. The 2-month EURIBOR is at 2.96%. Assume there are 122 days since the lastcoupon, and 61 days to the maturity of the future. What is the March 19th futures price? P P • if a coupons are paid between the the contract date and maturity date, the money market rate for investing the coupon must be deducted from K rCPN,t B B = money market rate from the receipt of the i:th coupon to maturity Example: On January 17th, a Treasury bond with CPN 7.25% trades at K = EUR 1 086U U P P 423.26. A coupon is received on 18.4. The 5-month (rt) EURIBOR is at 3.04%, and the B B 2-month (rCPN,t) EURIBOR is at 2.96%. What is the June 18th futures price? B B P P 1. Buy bond on Jan 17th ⇒ price paid is [K + AIc] = 1 140 596.87 EUR, financed at P P B B money market rate, and total cost is 1 140 596.87 EUR*[1 + (0.0304*152/365)] = 1 155 036.51 EUR which is paid on June 18th P P 2. 7.25% coupon is paid on April 18th ⇒ invested at money market rate to yield 72 P P 3. Total cost on June 18th is [1 155 036.51 - 72 858.65] = 1 082 177.86 EUR P P 4. Total cost for future on January 18th must equal 1 082 177.86 EUR [K + AIt] P P B B • with interest swaps, a customer (corporation or bank) can transform floating rate debt to fixed rate or the other way round• swaps are usually semi-annual and the floating rate in swap contracts is usually 6 month LIBOR or EURIBOR Example: Consider a corporation borrowing a floating rate EUR 100 million for 3-years.U U Interest rate payments are annual, and the reference rate is 12 month LIBOR flat (thecompany has a good rating and can borrow at LIBOR without a credit spread). Thecompany fears increasing interest rates, and decides to swap the floating payments to 59 fixed. The current 12-month LIBOR rate is 4.00%, and bank offers a fixed swap rate of4.3885% against 12 month LIBOR. The company agrees to pay the bank an annual4.3885%, and receives LIBOR from the bank. The cash flows are (EUR millions): Note that the payements from the LIBOR debt and the swap LIBOR payments cancel,out and what is left are the fixed rate swap payments. Also note that the first payment ofthe LIBOR debt is known, since the first payment is set at the reference rate, and reset atthe LIBOR rate after each interest rate payment. 1 − Df TPar − yield = T ∑ Df i =1 i where: DfT B B = the discount factor using zero-coupon rates for the maturity TDfi B B = the discount factors using zero-coupon rates up to maturity T 60 Example: Calculate the swap rate if the zero-coupon rates are 4.00% for 1 year, 4.20%U U 1 − 0.8788 Par − yield = = 0.043885 (0.9615 + 0.9210 + 0.8788) • we will now show why this must be the case, since an interest rate swap can be constructed using interest rate forwards (1 + 0.042) 2 f12 = − 1 = 0.044004 (1 + 0.40) (1 + 0.044) 2 f 23 = − 1 = 0.048012 (1 + 0.42) Now, we construct a table where we instead hedge the LIBOR debt with forwards. Webuy 1-year FRA:s up to 3 years, which means that settlement is based on (LIBOR-FRArate). Assume the FRA:s are settled in cash. This means that if the LIBOR exceeds theFRA rate, the difference is paid in cash. Cash flows in EUR millions: The hedged interest rate payments are clearly not the same as the swap cash flows. Howabout the present value of the series of FRA:s versus the swap? That is, even if the individual cash flows are not equal, the PV of the swap paymentsequals the PV of the swap. If the principal of EUR 100 million (PV = 87.8817) isincluded in the calculations the PV is of course EUR 100 million. 61 • a swap is priced at par, such that the NPV is zero to both parties• after this the value of the swap may change• a swap can be valued as either: 1. valued using the same principle as when valuing outstanding forwards: compare the contract rate with the current market rate for the same maturity, and disocunt the difference to present value, the result is a net present value (NPV)2. valued as a bond, the result is a present value (PV), including the principal Ft − F0 Long forward: PV ( F0 ) = (1 + rt ) F0 − Ft Short forward: PV ( F0 ) = (1 + rt ) Ft B B = the new forward rate prevailing at time t, for a forward identical to FT B B • Ft is the new swap rate for the same maturity T as the original swap to be valued (F0) B B B B • note that since there usually are multiple cash flows left, the equation will be extended to a sum of all the differences Ft and F0 B B B B • we also assume that the PV of the floating rate leg is zero at the coupon payment date (not true between coupon payment dates) Example: Suppose that after 1 year, the 1 and 2 year zero-coupon rates are 4.10%, andU U 4.25%. Then the 2 year swap rate is 4.2469%, with maturity T equal to the old 3 yearswap. What is the market value of the old swap now? We are “long” in the swap, sincewe pay the fixed leg, and the bank is “short”. Then F0 B B = 4.3885%Ft B B = 4.2469% and: T Ft − F0 4.2469 − 4.3885 4.2469 − 4.3885 NPV ( F0 ) = ∑ = + = −0.2664 i =1 (1 + rt ) t (1 + 0.041) (1 + 0.0425) 2 which is in this example is in millions, or roughly EUR -266 400. The negative value forthe fixed rate payer is a result of lower swap rates, the fixed rate payer is now payingabove the market rate for swaps with equal maturity T. The bank, who is short the swap,has naturally made an equally large gain. 62 T CFt 4.3885 104.3885 PV ( Bond ) = ∑ = + = −100.2664 i =1 (1 + rt ) t (1 + 0.041) (1 + 0.0425) 2 • the swap can naturally be valued at any time, not only at interest payment dates• then the value of the floating rate leg is not zero ⇒ the first payment should be valued as a money market security • now consider a borrower wishing to swap fixed payments in one currency to fixed payments in another currency• using the previous 3 year EUR 100 debt issue as an example, consider that the issuer wants to swap the debt to USD• the issuer may for example be a US issuer, finding better borrowing terms in EUR, and wishing to hedge EUR outflows or a EUR-based issuer financing its US operations with the debt, and wanting to use the US-revenue to repay the debt• an interest rate swap could be regarded as a sequence of FRA:s• a fixed-to-fixed currency swap can be regarded as a sequence of currency forwards• the swap rates for both legs are set as par yields as before• with interest rate swaps, principals are usually exchanged, and a currency swap then consists of the following steps: NOTE!: In these lecture notes a currency quote S(X/Y) means ”how many units of currency Y does it take to buy 1 unit of currency X”. That is EUR/USD 0.95 means it takes 0.95 EUR to buy 1.00 USD. I know this is frustrating for those used to the conventions used in the foreign currency markets. The reason is that this way of quoting is algebraically correct, and hence more easily lends itself to exercises involving inverting the quote, cross-rates, etc. Example: Consider a corporation borrowing a fixed rate EUR 100 million for 3-years.U U Interest rate payments are annual and the rate is 4.3885%. The company wishes to swapthe debt into USD. A bank offers to swap these EUR payments against a rate of 4.7906% 63 in USD. The spot currency rate is EUR/USD 0.95, and the USD principal is USD105.26 million. Note that the payments from the EUR debt and the swap payments cancel out and whatis left are the USD swap payments. Note the exchange back of the principals. • note that the swap from EUR to USD is identical to a series of FX forwards• the swap is a series of forwards to buy EUR against USD• the exchange rates for three years implied by the swap: • calculate the 1, 2, and 3 years currency forwards using CIRP, assume the USD zeros are 4.50%, 4.65%, and 4.80% for years 1-3: ⎡1 + rd ⎤ ⎡ (1 + 0.040)1 ⎤F = S0 * ⎢ ⎥ = 0.95 * ⎢ 1⎥ = 0.9455 ⎣⎢1 + r f ⎥⎦ ⎣ (1 + 0.045) ⎦ and similarly for the 2 and 3 years forwards: EUR/USD 0.9418, and EUR/USD 0.9392. Year 0 1 2 3EUR debt +100.0000 -4.3885 -4.3885 -104.3885Swap to USD:USD payments 5.0428 5.0428 110.3059PV of USD payments 105.2632 4.8256 4.6046 95.8330FX to USD:Forward rate 0.9500 0.9455 0.9418 0.9392USD payments 4.6417 4.6595 111.1505PV of USD payments 105.2632 4.4418 4.2546 96.5667 64 Both with the swap and the FX hedge, the firms EUR receipts are set equal to the cashoutflow of the debt, and their PV is then EUR 100 m. Note that the PV of the individualcash flows of the swap versus the FX hedge are not equal, but their sums are equal ⇒the value of the swap equals the value of the series of currency forwards. • the currency swap is priced at par, such that the NPV is zero to both parties• we will price the currency swap using the “bond approach”, since now principals matter beacuse they are in different currencies and subject to currency risk• the value of the swap is the difference between the two bonds that constitute the swap: T T CF (Re ceipts) t CF ( Payments) t PV = ∑ − S ∑ i =1 (1 + rR ) t i =1 (1 + rP ) t • note that receipts and payments are in different currencies, and interest rates used should be for that particular currency Example: Suppose that after 1 year, the 1 and 2 year zero-coupon rates in EUR areU U 4.10%, and 4.25%, and in USD 4.60%, and 4.75%. The spot rate is EUR/USD 0.93.What is the market value of the EUR-USD swap made at EUR 4.3885%-USD 5.0428,with principals EUR 100, and USD 105.2632? which in this example is in millions, or roughly EUR 2 291 000 for the USD payer. • like an interest rate swap the currency swap can naturally be valued at any time, not only at interest rate payment dates 65 1. Traditional models. These are not really “pricing models”, since this approach resembles much of equity analysis and there is no theoretically or other established way in which to in a consistent manner combine company-specific information (accounting etc.) into a yield, credit spread, or price. One can of course use empirical information as guidelines, that is compare issuers with similar characteristics and use price and spread information on these to get an idea of what spread should be charged. 2. Models based on option pricing. This approach is strongly based on financial pricing theory. Here, the value of the firm is seen as options, where equity seen as a long call (due to limited liability of shareholders), and bonds as short put options. Hence, bonds can be priced as options. • credit ratings lowers the barrier for an investor to invest in a bond, since most bond investors think that ratings quite accurately reflect the credit risk of the issuer, and hence there is less uncertainty for the bond investor when making the investment decision• ratings are thus a natural starting point for evaluating credit risk• note that ratings are only an assessment of credit risk (repayment risk), not interest rate risk, liquidity risk, call risk or other risks• ratings are not a recommendation to buy or sell a bond, a good rating does not make a bond a better investment in terms of risk/return -> markets price credit risk and ratings, and lower ratings come with higher yields• the ratings and rating agencies have a very strong role in debt markets, since many investors define their investment strategies according to ratings (for example mutual funds), or are prohibited by regulators to invest in certain rating classes (for example insurers)• examples of some Nordic issuers (September 2003): • the most important factors can be summarised into the 6 C:s of credit risk: • the idea of using option theory in bond pricing started with Robert Merton’s article in Journal of Finance (1974), hence, the term “Merton-like” models• Merton’s simple model deals with valuing a default risky zero-coupon bond, but the analysis can of course be extended (with some additional effort...) to coupon paying bonds, realising that a coupon bond is a series of zero-coupon bond• the idea of regarding a bond as an option is the limited upside of the bond: the value of a zero can never exceed it’s par value, but the bond still has downside in terms of default risk• the example below shows the present value (PV), and Recovery Rate (RR) of a 3-year zero-coupon bond relative to total company assets (belong to bondholders in case of default)• the idea is that if asset value is below the bond’s par value (100), and the bond defaults, the Recovery Rate is received and 100 – RR is then the credit loss• the same analysis can be made for each coupon to arrive at a series of present values and adding them up to total bond value 68 100 Value of debt (PV and RR) 80 RR 60 PV 40 20 0 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 Asset value • the difference between the standard Black-Scholes-Merton model for pricing stock options, and Mertons model for valuing risky debt is: A = asset valueB = nominal value of zero-coupon bondr = riskfree rate (Treasury)sA = volatility of firm’s assets (A)T = maturity of bond in years The model as presented in Saunders et al. (2002) and used for the above chart: ⎡1 ⎤ L = Be −rT ⎢ N (h1 ) + N (h2 )⎥ ⎣d ⎦ ⎡1 ⎤ ⎡1 ⎤ h1 = − ⎢ s 2T − ln(d )⎥ /( s T ), h2 = ⎢ s 2T + ln(d )⎥ /( s T ) ⎣2 ⎦ ⎣2 ⎦ • the main difference is that the underlying asset is now the assets of the issuer, and volatility is then the volatility of these assets• this simple model suffers from obvious problems: • extension of this idea include the Black & Cox (1976) model where default can happen before all assets are exhausted (A = 0)• KMV (now a part of Moody’s) have attempted to solve problems 1-4 by: 1. Attempting to model the statistical process of A over time (how does the value of A evolve over time, and what is its volatility). 2. A is modeled by modeling the stock price (E) behavior, and using leverage as a link between the stock price process and asset value process. The less debt, the closely A follows E. 3. Default if A goes below a specified value (makes this a barrier option). • the more realistic the model, the more difficult it becomes to estimate, use and understand it -> significant model risk!• the state of the world today: no accepted model • what is the default probability (DP), recovery rate (RR), or loss given default (LGD)• empirical results on US bond data by Altman & Kishore (1998) on high-yield: 70 Seniority RR(%)Senior secured 58.7Senior unsecured 48.9Senior subordinated 35.0Subordinated 31.7Zeros 20.7 • investing in bonds with high spreads (yields) does not necessarily lead to high returns: the risks priced into the spread might be realised causing a further widening of the spread and price decline and loss of return• rating ans spread changes are an essential part of corporate bond investing• 1-year rating transition probabilities (RTP) by Carty & Fons (1994), using Moody’s ratings 1970-1994: • conclusions: 1. Downgrades more likely than upgrades (fallen angels more likely than rising stars) 2. Spread differences between rating categories widen with lower ratings, adding to return loss due to price decline. 71 • for example, assume a 3-year AA-rated bond that now trades at a 30 bp spread, and you want to estimate the expected return over a 1-year holding period: • using these values, the expected return of a AA-bond is not the initial spread of 30 bp, but 28.9 bp• some figures based on historical averages for different rating classes over different holding periods (highest returns are bolded): • that is for both 3- and 5-year horizons, Baa has the highets returns, but for a 10-year horizon, A is the best rating class• note that all such estimates are based on historical averages 72 Das, Satyajit (1994): Swap & Derivative financing. Irwin Professional Publishing. de la Grandville, Olivier (2001): Bond pricing and portfolio analysis. The MIT Press. Hull, John C. (2000): Options, futures, and other derivative securities. Prentice-HallInternational. Jorion, Philippe (1996): Value at risk: The new benchmark for controlling market risk.Irwin Professional Publishing. Sundaresan, Suresh M. (1997): Fixed income markets and their derivatives. South-Western. Tuckman, Bruce (1996): Fixed income securities: Tools for today’s markets. John Wiley& Sons.
https://fr.scribd.com/document/37920934/Bond-Valuation
CC-MAIN-2019-39
refinedweb
14,599
67.38
Results 1 to 2 of 2 - Join Date - Dec 2013 - 3 - Thanks - 1 - Thanked 0 Times in 0 Posts New to Java, need assistance with code I was wondering if anyone could help me get this code to work the way its intended. public class Main { public static void main(String[] args) { String a = new String("Wow"); String b = "Wow"; String c = a; String d = c; boolean b1 = a == b; boolean b2 = b.equals(b + "!"); boolean b3 = !c.equals(a); if (b1 && b2 && b3) { System.out.println("Success!"); } } } What do I need to change to make this display "Success!" when executed? Any help will be greatly appreciated - Join Date - Sep 2002 - Location - Saskatoon, Saskatchewan - 17,026 - Thanks - 4 - Thanked 2,668 Times in 2,637 Posts Every one of those booleans are false: a != b (strings are immutable) b != b + "!" (this wouldn't ever be true) c = a (c and a are the same object, so checking ! is false) So to get it to show success you can either negate each boolean during assignment or the if check, or you can negate the entire set of conditions after the check.PHP Code: header('HTTP/1.1 420 Enhance Your Calm'); Users who have thanked Fou-Lu for this post: Dragondd320 (12-10-2013)
http://www.codingforums.com/java-and-jsp/313822-new-java-need-assistance-code.html
CC-MAIN-2017-09
refinedweb
213
77.27
Farblondzshet in code. Silverlight 2 is currently in Beta 1 but even in this early stage it has many amazing features. One of these features which I was toying around with today was its ability to integrate with its host page's DOM. What this means is that from Silverlight you are able to call Javascript functions and from JavaScript you can call Silverlight methods. To demonstrate this feature I created a simple but interesting sample: This webpage which can be found here contains two areas, a JavaScript area and a Silverlight area. Each has a small square in it. When you move the square in one area it updates its position in the other. The beauty of this is how simple it is to make this work. I will show how I update the squares position from Silverlight and from Javascript: Calling Javascript Functions from Silverlight This is the simpler of the two. In Silverlight under the System.Windows.Browser namespace there is an object called HtmlPage. This object gives you access to the pages DOM. The code I use to move the square in the JavaScript area is: HtmlPage.Window.Invoke("moveBox", newX, newY); where "moveBox" is the name of a Javascript method I wrote to update the red square's position. That is all I have to do! Calling Silverlight Methods from Javascript This is slightly more complicated. First in the Silverlight application I have to mark which class I want to expose to JavaScript as by giving it a Scriptable attribute: [ScriptableType] public partial class Page : UserControl Then I need to register this class so that JavaScript can see it and give it a name for JavaScript to refer to it as: HtmlPage.RegisterScriptableObject("silverlightMove", this); Next I need to mark which methods to expose to JavaScript by giving them a ScriptableMember attribute. Here I am exposing a method called MoveBox which updates the blue square's position in the Silverlight application: [ScriptableMember] public void MoveBox(int x, int y) With all this setup done I can now move back to JavaScript and get ready to call the method. To do this I need to get a reference to the pages Silverlight control: silverLightControl = document.getElementById("silverlightControl"); Where "silverlightControl" is the id applied to my Silverlight application object tag. Once I have a reference to the Silverlight control I am able to invoke the method which I marked as a ScriptableMember using the object name I registered: silverLightControl.content.silverlightMove.MoveBox(x, y); I have now called MoveBox method from my C# code in the Silverlight application using Javascript! The code for this sample can be found at here at MSDN Code Gallery. You've been kicked (a good thing) - Trackback from DotNetKicks.com I get this question so often when I present information about Silverlight, that I thought I'd just link
http://blogs.msdn.com/matt/archive/2008/04/13/combining-silverlight-2-and-javascript.aspx
crawl-002
refinedweb
477
70.53
- Add Digits of a Number In this article, you will learn and get code in Python, to find and print the sum of digits of a number entered by user at run-time. Here are the list of approaches used to do the task: - Add Digits of a Number using while Loop - Using for Loop - Using Function - Using class For example, if user enters a number say 235, then the output will be 2+3+5, that is 10. Add Digits of a Number using while Loop The program given below receives a number as input from user, and uses a while loop to find the sum of digits of given number: print("Enter a Number") num = int(input()) sum = 0 while num>0: rem = num%10 sum = sum+rem num = int(num/10) print("\nSum of Digits of Given Number: ", sum) Here is the initial output produced by this Python program: Now supply the input say 123 and press ENTER key to find and print the summation of its digit 1, 2, and 3 as shown in the snapshot given below: The dry run of above program with user input 123 goes like: - Since user enters 123, then it gets stored in num. Therefore num=123 (entered by user) and sum=0 (initialized 0 as its initial value) - Now the condition of while loop gets evaluated. That is, the condition num>0 or 123>0 evaluates to be true, therefore program flow goes to its body and evaluates all the three statements - So num%10 or 123%10 or 3 gets initialized to rem. Now rem=3 - And sum+rem or 0+3 or 3 gets initialized to sum. Now sum=3 - And finally int(num/10) or int(123/10) or int(12.3) or 12 gets initialized as new value of num. Now num=12 - Now the condition of while loop again gets evaluated. Because this time also the condition num>0 or 12>0 evaluates to be true, therefore again, all three statements gets executed. This process continues until the condition evaluates to be false - In this way, after exiting from the loop, we'll have a variable named sum that holds 6, the sum of digits of given number - Therefore just print the value of sum as output Modified Version of Previous Program This is the modified version of previous program. In this program, if user enters a number say 124, then output looks like 1+2+4=7 print(end="Enter a Number: ") num = int(input()) sum = 0 print(end="\n") while num>0: rem = num%10 sum = sum+rem num = int(num/10) if num==0: print(end=str(rem)) else: print(end=str(rem)+ "+") print(" = " +str(sum)) Here is its sample run with user input, 130259: Note - The end is used to skip adding an automatic newline using print(). Add Digits of Number using for Loop Now this program uses for loop instead of while to do the same task, that is to find and print the sum of given number's digits. print("Enter a Number: ", end="") num = int(input()) sum = 0 temp = num for i in range(len(str(temp)), 0, -1): rem = num%10 sum = sum+rem num = int(num/10) print("\nSum of Digits of " +str(temp)+ " = " +str(sum)) Here is its sample run with user input, 4052: Note - The third parameter of for loop (-1) is used to loop with loop variable (i) in reverse order. That is, the size of given number to 1 (one greater than 0 (the second parameter)) Since the length of "4052" (a string) is 4, therefore all three statements gets executed three times. Note - The str() is used to convert an int value to a string type value Note - The len() is used to find the length of string. Add Digits of Number using Function This program uses a user-defined function named addNumDig() to find the sum of digits of a given number. The function receives a number as its argument and returns the sum of its digit. def addNumDig(n): sum = 0 while n>0: rem = n%10 sum = sum+rem n = int(n/10) return sum print("Enter a Number: ", end="") num = int(input()) res = addNumDig(num) print("\nSum of Digits of " +str(num)+ " = " +str(res)) This program produces the same output as of previous program. Add Digits of Number using Class This is the last program of this article. The program is created using class and object, an object-oriented feature of Python. class CodesCracker: def addNumDig(self, n): sum = 0 while n>0: rem = n%10 sum = sum+rem n = int(n/10) return sum print("Enter a Number: ", end="") num = int(input()) ccObj = CodesCracker() res = ccObj.addNumDig(num) print("\nSum of Digits of " +str(num)+ " = " +str(res)) Here is its sample run with user input, 1046: Using the following statement: ccObj = CodesCracker() All properties of the class named CodesCracker gets assigned to an object named ccObj. Now this object can be used to access the member function of class CodesCracker using dot (.) operator. Same Program in Other Languages « Previous Program Next Program »
https://codescracker.com/python/program/python-program-add-digits-of-number.htm
CC-MAIN-2022-21
refinedweb
857
57.34
(PLEASE IF YOU LIKED IT, VOTE ON ME IN THE MICROCONTROLLER CONTEST, HELP ME TO BRING MORE USEFUL PROJECTS) platafform you will fell free again. Using two arduinos a signal is launched when someone approach from the door, and close the window that you were seeing, then open a beautiful video. Don't get caught anymore! Step 1: Things You Will Need You will need a few things - Arduino Leonardo - Arduino Uno - PIR DYP-ME003 Sensor module - 2 protoboards - RF 433MHz Transmitter module - RF 433MHz Receiver module - 1 Green led - 1 Red led - Jumpers - 2 paper Clips - 2 little ball of Steel wool 1 resistor of 220 ohms Your pc Step 2: Building the Transmissor It's quite a lot simple doing this one, as I said before, it's easy and you can have some other use of it. You're going to need those items here: - Arduino Uno - PIR DYP-ME003 sensor module - RF 433MHz Transmitter module - 1 green LED - 1 protoboard - Jumpers - 1 resistor 220 ohms - 1 paper Clips - 1 little ball of Steel wool You will assemble like the picture above, i used the paper clip and the ball of steel wool like an antenna, to amplify the range of the transmitter module. Here the sensor PIR will catch any movement and send to the receiver a signal that someone is coming. It will turn on the led when it happens, the code for this arduino is this one: (you'll need to download the library VirtualWire.h and the Keyboard.h) #include <VirtualWire.h> const int ledPin = 13; const int pir = A0; int value; char Value_CharMsg[4]; int state = 0; void setup() { Serial.begin(9600); pinMode(ledPin,OUTPUT); pinMode(pir,INPUT); vw_set_tx_pin(4); vw_setup(5000); Serial.println("Looking around: \n"); } void loop() { value = digitalRead(pir); state = 0; if (value == 0) { itoa(state,Value_CharMsg,10); Serial.print("Value sended: "); Serial.println(Value_CharMsg); delay(1000); else { state = 1; digitalWrite(13, true); itoa(state,Value_CharMsg,10); vw_send((uint8_t *)Value_CharMsg, strlen(Value_CharMsg)); Serial.print("Value sended: "); Serial.println(Value_CharMsg); vw_wait_tx(); delay(10000); digitalWrite(13, false); } } Step 3: Building the Receiver For this one you gonna use: - Arduino Leonardo - 1 protoboard - 1 Red led - RF 433MHz Receiver module - Jumpers - 1 paper Clips - 1 little ball of Steel wool You will assemble like the picture above, In this one, the Arduino will detect the signal transmitted from the sensor, and tell to the computer to press a combinations of buttons that will active the final program. Why using an Arduino Leonardo? this platform can interact with your computer and send a command to it, so this one will be always connected to the pc. This is the code you'll use here. #include <VirtualWire.h> #include <Keyboard.h> //Define pin led int ledPin = 5; int value_RF; char receive_RF_char[4]; void setup() { Keyboard.begin(); Serial.begin(9600); pinMode(ledPin, OUTPUT); vw_set_rx_pin(7); vw_setup(5000); vw_rx_start(); Serial.println("Waiting..."); } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) { int i; for (i = 0; i < buflen; i++) { receive_RF_char[i] = char(buf[i]); } receive_RF_char[buflen] = '\0'; value_RF = atoi(receive_RF_char); Serial.print("receive: "); Serial.print(value_RF); if (value_RF == 1) { Keyboard.press(KEY_LEFT_CTRL); Keyboard.press(KEY_LEFT_SHIFT); Keyboard.press('j'); delay(10); Keyboard.releaseAll(); digitalWrite(ledPin, HIGH); Serial.println(" - Led on !"); } if (value_RF == 0) { digitalWrite(ledPin, LOW); Serial.println(" - Led off !"); } } } Step 4: Making the Program on the Prompt Here comes the final part, you'll need to open the command prompt and open your Web browser (in my case i use the google chrome, so if you use it, you can just copy my program) and digit the command tasklist, it will show you all the open programs, identify your current browser. Now open the notebook and write this: // taskkill.exe/IM (name of your web browser) start (name of the browser) (the page you want to open) // save it like: name_of_program.bat (the .bat is the function that run the prompt). You can open any page. After that you're gonna create a shortcut, open the Properties of the shortcut and put this on shortcut key Ctrl + Shift + J, this is the command that the arduino sends to the computer Step 5: Profit And here it's how it works, let me know if you liked it! :D 14 Discussions 1 year ago Top! Muito interessante, inovador Reply 1 year ago Brigadão!! ^^ 1 year ago Parabééns Matheus, projeto brilhante, não te conheço mas acho que você tem um futuro brilhante pela frente!!! ?Continue no caminho certo!!! Reply 1 year ago Muito obrigado Wagner, seria um prazer te conhecer! xD 1 year ago Woww exellent project very good idea Reply 1 year ago thank you buddy!! :D 1 year ago Ive been rick rolled Reply 1 year ago it's super effective to distract isn't it?? 1 year ago nice. idea Reply 1 year ago Thanks m8! 1 year ago That is really clever. Reply 1 year ago thanks buddy! 1 year ago What a great idea! Reply 1 year ago thanks!! :D
https://www.instructables.com/id/Dont-Get-Caught-Anymore/
CC-MAIN-2019-09
refinedweb
840
64
The Situation I wrote a script using Biopython which read a file containing a bunch of Genbank accession numbers, and downloaded the Genbank records: 1 ### gentest.py 2 3 from Bio import GenBank 4 5 gi_list = ['AF339445', 'AF339444', 'AF339443', 'AF339442', 'AF339441'] 6 record_parser = GenBank.FeatureParser() # GenBank file parser 7 ncbi_dict = GenBank.NCBIDictionary(parser = record_parser, 8 database = "nucleotide") # Dict for accessing NCBI 9 10 count = 1 11 for accession in gi_list: 12 print "Accessing GenBank for %s... (%d/%d)" % (accession, count, len(gi_list)) 13 try: 14 record = ncbi_dict[accession] # Get record as SeqRecord 15 RECORDS.append(record) # Put records in local list 16 except: 17 print "Accessing record %s failed" % accession 18 19 20 count += 1 This worked fine as a script, but when I attempted to turn it into a Windows executable with py2exe and the setup.py script: with the command python setup.py py2exe, attempting to run the resulting gentest.exe would throw an error. The Error This is the error thrown on running the executable: {{{Traceback (most recent call last): - File "gentest.py", line 1, in ? File "Bio\init.pyc", line 68, in ? File "Bio\init.pyc", line 55, in _load_registries WindowsError: [Errno 3] The system cannot find the path specified: - 'E:\\Data\\CVSWorkspace\\genbank2excel\\genbank2excel\\dist\\library.zip\\Bio\\config/*.*'}}} The Problem Location of Bio.config With help from Thomas Heller on the Python-Win32 mailing list, the problem was identified. When the Bio package is imported, Bio/__init__.py imports a number of modules from the Bio.config module using the _load_registries function. The first problem occurs in line 52: (file version 1.21 from CVS) Under normal script-like execution, the os.path.dirname call returns a string indicating a location accessible through the filesystem via os.listdir. However, py2exe uses new import hooks (via the builtin zipimport hook), described in PEP 302, so the location returned by the os.path.dirname call is located within the shared zip archive that py2exe creates. As a result, os.listdir fails, and the above error is thrown. Module extensions The arrangement with py2exe's shared zipfile causes problems further down the function. The _load_registries function expects that modules will have the .py extension, rather than the .pyc extension that the compiled files (all that are included in the zipfile) use. Zipfile modules within Bio.config are thus not loaded. The Solution Existing code The code to be changed for the _load_registries method is (lines 50-55 in Bio/init.py CVS version 1.21) 1 # Load the registries. Look in all the '.py' files in Bio.config 2 # for Registry objects. Save them all into the local namespace. 3 x = os.listdir( 4 os.path.dirname(__import__("Bio.config", {}, {}, ["Bio"]).__file__)) 5 x = filter(lambda x: not x.startswith("_") and x.endswith(".py"), x) 6 x = map(lambda x: x[:-3], x) # chop off '.py' Which obtains a list of modules, (for later import as Bio.config.module_name). Since we cannot obtain the list of modules with this code, we need to provide an alternative way of generating the list when the modules are in the shared zipfile. Processing the zipfile Firstly, we must determine whether the imported module comes from a zipfile, or is a straightforward import. This is done by checking for the .__loader__ attribute with if hasattr(config_imports, '__loader__'): Next, we need to obtain the list of module files for Bio.config. These are all found within the Bio/config folder, so we can filter the filenames in the shared zipfile using the x = [zipfiles[file][0] for file in zipfiles.keys() if 'Bio\\config' in file] list comprehension. The filenames in this list are absolute paths, so we can grab just the filename with another list comprehension x = [name.split('\\')[-1] for name in x]. We have to lose the extensions from these filenames, too. These are all .pyc files, so we can use a modification of the existing code's map and lambda x = map(lambda x: x[:-4], x). [Note: we could easily combine the last two steps, but I keep them separate for clarity]. We now have the required list of module filenames. Putting the steps together, and combining with the original code, we have: 1 # Load the registries. Look in all the '.py' files in Bio.config 2 # for Registry objects. Save them all into the local namespace. 3 # Import code changed to allow for compilation with py2exe from distutils 4 config_imports = __import__("Bio.config", {}, {}, ["Bio"]) # Import Bio.config 5 if hasattr(config_imports, '__loader__'): # Is it in zipfile? 6 zipfiles = __import__("Bio.config", {}, {}, ["Bio"]).__loader__._files 7 x = [zipfiles[file][0] for file in zipfiles.keys() \ 8 if 'Bio\\config' in file] 9 x = [name.split('\\')[-1] for name in x]# get filename 10 x = map(lambda x: x[:-4], x) # chop off '.pyc' 11 else: # Not in zipfile, get files normally 12 x = os.listdir( 13 os.path.dirname(config_imports.__file__)) 14 x = filter(lambda x: not x.startswith("_") and x.endswith(".py"), x) 15 x = map(lambda x: x[:-3], x) # chop off '.py' Compilation with the original setup.py script and python setup.py py2exe then ran smoothly, apart from a couple of missing modules which had no impact on the running of the executable. Update The changes have now (3rd Feb 04) been incorporated into the Biopython source in CVS.
http://www.py2exe.org/index.cgi/ConfigImportProblems
CC-MAIN-2015-18
refinedweb
898
69.58
In this user guide, we will build an ESP32 web server which will act as a remote serial monitor. This will be achieved by using the WebSerial library and programming the ESP32 board in Arduino IDE. Additionally, we will use the ESPAsyncWebServer library as well. The web based serial monitor will work just the same way as the usual Arduino IDE serial monitor works for debugging purposes. By the end of this article, we will be able to send and receive text from the ESP32 to the web serial. We will show you how to build the web serial as well as how to use it with ESP32 module. Project Overview We aim to build a web server which will act as a serial monitor used for debugging purposes. After making a serial connection with the ESP32 board, it will be able to receive messages from the module as well as send them to our module. The figure below shows the web page which will act as the web based serial monitor. If you do not have access to the regular serial monitor, this web based serial monitor will be very convenient to use while working with ESP32 projects. One of the advantages is that you can open several web serials at a time. Additionally, it is compatible with WebSockets as well making it a great choice to use. In the Web serial we use WebSerial.print() and WebSerial.print() to print messages on the monitor. WebSerial.print(): prints the message on the web-based serial monitor on the same line WebSerial.println(): prints the message on the web-based serial monitor on the next line Setting up Arduino IDE Installing Libraries We will require three libraries for this project. These include the ESPAsyncWebServer library, AsyncTCP library and the WebSerial library by Ayush Sharma Installing ESPAsyncWebServer and AsyncTCP The ESPAsyncWebServer library will help us in creating our web server easily. With this library, we will set an asynchronous HTTP server. AsyncTCP is another library that we will be incorporating as. . Installing WebSerial Library by Ayush Sharma To build our web based serial monitor we will require the WebSerial library created by Ayush Sharma. This is available in the Arduino Library Manager. Open your Arduino IDE and go Tools > Manage Libraries. Type ‘WebSerial’ in the search bar and press enter. Install the latest version. Arduino Sketch (ESP32 Web based Serial Monitor) Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. We are using the example sketch provided with the WebSerial library with a few modifications. This sketch will display “Welcome to Microcontrollerslab!” on the web page after every 5 seconds. Additionally, we have also incorporated LED control as well. Whenever we will type ‘LED ON’ in the web serial, the onboard LED of the ESP32 will turn ON and vice versa. /* This sketch is based on the WebSerial library example: ESP32_Demo */ #include <Arduino.h> #include <WiFi.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> #include <WebSerial.h> #define LED_GPIO 2 AsyncWebServer server(80); const char* ssid = "Your_SSID"; const char* password = "Your_Password";() { Serial.begin(115200); pinMode(LED_GPIO, OUTPUT); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.printf("WiFi Failed!\n"); return; } Serial.print("IP Address: "); Serial.println(WiFi.localIP()); WebSerial.begin(&server); WebSerial.msgCallback(message); server.begin(); } void loop() { WebSerial.println("Welcome to Microcontrollerslab!"); delay(5000); } How does the Code Work? Now, let us understand how each part of the code works. Including Libraries Firstly, we will import the necessary libraries. For this project, we are using five of them. Arduino.h, WiFi.h, ESPAsyncWebServer.h, AsyncTCP.h and WebSerial.h. As we have to connect our ESP32 to a wireless network hence we need WiFi.h library for that purpose. The other libraries are the ones that we recently downloaded and will be required for the building of the asynchronous web server which will act as a serial monitor. #include <Arduino.h> #include <WiFi.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> #include <WebSerial.h> Defining LED GPIO Next, we will define the GPIO which we will control via the web serial. For simplicity purposes, we will toggle the onboard LED of our ESP32 board. It is connected with GPIO2. #define LED_GPIO 2 Creating the AsyncWebServer Object The AsyncWebServer object will be used to set up the ESP32 web server. We will pass the default HTTP port which is 80, as the input to the constructor. This will be the port where the server will listen to the requests. AsyncWebServer server(80);"; void message() Next, we will create a function called message() which takes in two parameters. This function will be called when the ESP32 board receives a message from the web serial. This message will get saved in the string variable named ‘Data’ and gets displayed in the web based serial monitor. Initially, we have defined it as an empty string. Notice that in order to print a text in the web based serial monitor we will use WebSerial.println(Data) instead of Serial.println(Data) where the latter prints the message in the regular serial monitor. Additionally, we will be toggling the onboard LED in this function. When the user types ‘LED ON’ in the web serial, the onboard LED turns ON. This is done by using digitalWrite() and passing the LED GPIO and ‘HIGH’ as arguments inside the function. Likewise, when the user types ‘LED OFF’ in the web serial, the onboard LED turns OFF. this is done by using digitalWrite() and passing the LED GPIO and ‘LOW’ as arguments inside it.() Inside the setup() function, we will first set the LED’s GPIO pin as an output by using the pinMode() function. the LED GPIO (GPIO2) will be passed as a parameter inside the function which will be configured as an output pin. pinMode(LED_GPIO, OUTPUT); The following section of code will connect our ESP32 board with the local network whose network credentials we already specified above. We will first set the ESP32 module in station mode and then use the WiFi.begin() function. The arguments will be the SSID and the password which we defined earlier in the code. After a successful connection is established, the IP address gets displayed on the web server. We will use this IP address to access our web server. WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.printf("WiFi Failed!\n"); return; } Serial.print("IP Address: "); Serial.println(WiFi.localIP()); Now we will use the WebSerial.begin() and pass the WebSerial object which we created previously inside it. This will initialize the web based serial monitor. The next step will be to register the message() function as a call-back function whenever the user sends a message from the web serial to the ESP32 board. This will be achieved by using WebSerial.msgCallback() and passing ‘message’ as the parameter. WebSerial.begin(&server); WebSerial.msgCallback(message); To start the server, we will call begin() on our server object. server.begin(); void loop() Inside the infinite loop() we will print “Welcome to Microcontrollerslab!” after every five seconds in the web serial monitor. This will be achieved by using WebSerial.println(). You can display any text according to your preference. void loop() { WebSerial.println("Welcome to Microcontrollerslab!"); delay(5000); } Demonstration Make sure you choose the correct board and COM port before uploading your code to the board. Go to Tools > Board. Select ESP32 Dev Module. Next, go to Tools > Port.. You will be able to see the IP address of your ESP32 module. Copy that address into a web browser with /webserial and press enter. The web based serial monitor will be displayed. Notice that after every 5 seconds, we are receiving a message (Welcome to Microcontrollerslab!) from the ESP32 module. Now, we can also send messages from this web serial monitor to our ESP32 board. Type ‘LED ON’ in the Type here bar and click Send. Just as you click the Send button the onboard LED will turn ON. In the web based serial monitor you will be able to view the message ‘Data Received!’ and ‘LED ON.’ To turn the onboard LED OFF, type “LED OFF” in the web serial monitor and click Send. The LED will turn OFF. Likewise, In the web based serial monitor you will be able to view the message ‘Data Received!’ and ‘LED OFF.’ Conclusion In conclusion, we were able to show you how to build and use a web based serial monitor easily using the WebSerial library created by Ayush Sharma. This web server is very advantageous if you are unable to serially connect your ESP32 module with a system. Additionally, it uses WebSocket and displays data in real-time which makes it quite handy. For more ESP32 related tutorials visit the links below: - ESP32 WebSocket Server using Arduino IDE – Control GPIOs and Relays - ESP32/ESP8266 Web Server with Input Data on HTML Form using Arduino IDE - ESP32 Server-Sent Events (SSE) Web Server (Arduino IDE) - ESP32 Asynchronous Web Server using Arduino IDE and ESPAsyncWebServer library - IBM Watson Cloud Platform with ESP32: Display sensor Readings
https://microcontrollerslab.com/esp32-web-based-serial-monitor-webserial/
CC-MAIN-2021-39
refinedweb
1,529
59.09
The Watts-Strogatz (WS) network model has small world characteristics, but the degree distribution is roughly normal, very different from observed distributions. The Barabasi-Albert (BA) model has low path lengths and a heavy-tailed degree distribution, but - It has low clustering, and - The degree distribution does not fit observed data well. The Holmes-Kim (HK) model generates graphs with higher clustering, although still not as high as observed values. And the degree distribution is heavy tailed, but it still doesn't fit observed distributions well. I propose a new model that generates graphs with - Low path lenths, - Clustering coefficients similar to the HK model (but still lower than observed values), and - A degree distribution that fits observed data well. I test the models with a relatively small dataset from SNAP. The proposed model is based on a "friend of a friend" growth mechanism that is a plausible description of the way social networks actually grow. The implementation is simple, comparable to BA and HK in both lines of code and run time. All the details are in this Jupyter notebook, but I summarize the primary results here. Comparing the modelsThe Facebook dataset from SNAP contains 4039 nodes and 88234 edges. The mean path length is 3.7 and the clustering coefficient is 0.6. A WS model with the same number of nodes and edges, and with probability of rewiring, p=0.05, has mean path length 3.2 and clustering 0.62, so it clearly has the small world properties. But the distribution of degree does not match the data at all: A BA model with the same number of nodes and edges has very short paths (2.5), but very low clustering (0.04). The degree distribution is a better match for the data: If we plot CDFs on a log-log scale, the BA model matches the tail of the distribution reasonably well, but the WS model is hopeless. But if we plot CDFs on a log-x scale, we see that the BA model does not match the rest of the distribution: The HK model also has short path lengths (2.8), and the clustering is much better (0.23), but still not as high as in the data (0.6). The degree distribution is pretty much the same as in the BA model. The FOF model The generative model I propose is called FOF for "friends of friends". It is similar to both BA and HK, but it yields a degree distribution that matches observed data better. It starts with a complete graph with m nodes, so initially all nodes have degree m. Each time we generate a node we: - Select a random target uniformly from existing nodes. - Iterate through the friends of the target. For each one, with probability p, we form a triangle that includes the source, friend, and a random friend of friend. - Finally, we connect the source and target. Because we choose friends of the target, this process has preferential attachment, but it does not yield a power law tail. Rather, the degree distribution is approximately lognormal with median degree m. Because this process forms triangles, it yields a moderately high clustering coefficient. A FOF graph with the same number of nodes and edges as the Facebook data has low path length (3.0) and moderate clustering (0.24, which is more than BA, comparable to HK, but still less than the observed value, 0.6). The degree distribution is a reasonable match for the tail of the observed distribution: /> And a good match for the rest of the distribution /> In summary, the FOF model has - Short path lengths, like WS, BA, and HK. - Moderate clustering, similar to HK, less than WS, and higher than BA. - Good fit to the tail of the degree distribution, like BA and HK. - Good fit to the rest of the degree distribution, unlike WS, BA, and HK. Also, the mechanism of growth is plausible: when a person joins the network, they connect to a randomly-chosen friend and then a random subset of "friends of friends". This process has preferential attachment because friends of friends are more likely to have high degree (see The Inspection Paradox is Everywhere) But the resulting distribution is approximately lognormal, which is heavy tailed, but does not have a power law tail. ImplementationHere is a function that generates FOF graphs: def fof_graph(n, m, p=0.25, seed=None): if m < 1 or m+1 >= n: raise nx.NetworkXError() if seed is not None: random.seed(seed) # start with a completely connected core G = nx.complete_graph(m+1) for source in range(len(G), n): # choose a random node target = random.choice(G.nodes()) # enumerate neighbors of target and add triangles friends = G.neighbors(target) k = len(friends) for friend in friends: if flip(p): triangle(G, source, friend) # connect source and target G.add_edge(source, target) return G def flip(p): return random.random() < p def triangle(G, source, friend): """Chooses a random neighbor of `friend` and makes a triangle. Triangle connects `source`, `friend`, and random neighbor of `friend`. """ fof = set(G[friend]) if source in G: fof -= set(G[source]) if fof: w = random.choice(list(fof)) G.add_edge(source, w) G.add_edge(source, friend) Again, all the details are in this Jupyter notebook. I enjoyed this blog post very much. I didn't think about scale free networks for some years. However, I see some waek points: - the only parameter that alows you to controll the degree sequence and the clustering coefficient independently of the average degree is the rewiring probability. this means that the clustering coefficient and the distribution do strongly dependend on each other. -every edge is part of a triangle. There is a the model of hyperbolic randomg raphs which became very popular in the last few years. Its possible to control its clustering, average degree and degree sequence. The degree sequence can be power law distributed, the clustering can be strong and the average degree can be small. The model was introduced here: Later we analyzed it rigorously here: Since then many other usefull properties like small average path lengh, efficient greedy routing etc. have been proven. Moreover, on a phylosophical level, it give (in my opinion) a very nice explanation for the properties of social networks, the internet graphs and other small world network. That's very helpful. Thanks!
https://allendowney.blogspot.com/2016/09/its-small-world-scale-free-network.html
CC-MAIN-2019-09
refinedweb
1,068
64.71
. (On Islam) - Conversations in '11. - Conversations in '12. (On civics and politics) (on Kamek98) - Conversations in '13 before Oppage. After oppage: 2 3 4 5 6 - RFCs received in 2013 of no enduring interest except to those studying the requestors. Template:VFDn {{VFDn}} shows talk, history, search for previous nominations (once I set that up), and can check if the article is a feature, or in the Category:In-jokes - although the last item is not a reason to sway vote as far as I'm concerned. Working on a way to do a semi-auto add of {{Oldvfd}} to talk page (still an idea in progress), but I may leave that last item to {{VFDc}}. I'm trying to set it so an edit of one letter to template closes the nomination and gives you the links most relevant to poopsmithing. Anything else that would be suitable that you can think of? I'd like to get this as smooth for adding, voting, and closing nominations as possible, while giving the access to due diligence, so any suggestions are very welcome. • Puppy's talk page • 10:20 02 Oct 2013 - I take it that {{VFDn}} would be the new section head for ballots at VFD. It's helpful, though my tests have not found a page where "Search previous VFD nominations" works. - I have not stopped wanting to change other things about VFD; notably, to display the case (Delete) before the rebuttal (Keep). However, last time, Sycamore insisted that I take it to the Forum, where the result was ridicule that the change was too trivial and I was wasting everyone's time: "It is so trivial that you must not do it." So this would require a return trip to the Forum, which would bog down your changes. - Also, it would be painless to have a background of pastel green for the Keep votes and pastel red for the Deletes, and I have become enamored of rounded corners, just because they are smooth and we never used to be able to code it. Spıke Ѧ 11:38 2-Oct-13 - Never been able to get rounded corners to work smoothly cross browser. The backgrounds and the reversal of order is fairly straight forward, but it means creating a fresh template for votes, which I'll play with over the course if the next few days. My intention is to get it as complete as possible, so we don't need to do too many tweaks. • Puppy's talk page • 12:09 02 Oct 2013 - On reversal-of-order, again: Please don't. It might bog your uncontroversial work down in the revival of old controversy. Spıke Ѧ 12:16 2-Oct-13 - It's a valid point. We'll see how it goes. • Puppy's talk page • 12:23 02 Oct 2013 Hey. I don't have access to the deletion page, so could you just confirm that the delete link here autopopulates the deletion reason? (There is another way to do this so it uses the drop down box, but I can't remember for the life of me what it is.) If you want to adjust the phrasing of the deletion reason then feel free, but it may need a little url encoding if you do. • Puppy's talk page • 11:51 07 Oct 2013 - It does indeed. However, instead of what I do--putting the link to VFD in the "Reason for deletion" field via pulldown menu, which leaves the "Other/additional reason" field free for possible comment, it puts the link in the latter field. That's good enough, as I am free to append comments to it. Spıke Ѧ 12:01 7-Oct-13 US Government shuts down I'd have thought that this would make a good UnNews story. The whole things caused quite a stir over here. I don't really know enough information about how the US Government runs to write a decent UnNews on it but I just thought that as you are the king of UnNews writing and you know a fair bit about US Politics that you might want a crack at it. Seems stupid how not acheiving a budget statement causes so much distress.:28, October 2, 2013 (UTC) - Sorry, but I wrote UnNewses about the previous round of brinksmanship/fingerpointing/Kabuki-dances. The bottom line is that nothing important will fail to occur, but Obama will tough it out and wait for Republican after Republican to claim, increasingly publicly, that "we can't win." In my state, we are grooming the next generation of Conciliation Monkeys even now. - As far as UnNews goes, the story on the top of the stack provides a novel take on the shutdown, and I did a narration of it. Spıke Ѧ 17:36 2-Oct-13 - Oh one has already been written...whoops. Didn't see it. Thanks. - Our intake in my corner of the island is also "blame the republicans." The main reason being that Obama is one of the most liberal Presidents seen in a while so us Brits take a liking to:43, October 2, 2013 (UTC) - ScottPat, perhaps what you want is at UnNews:US government shuts down with unprecedented triteness (). Spıke Ѧ 20:58 3-Oct-13 Forum:A reskin for the US government shutdown Could I bring you to the attention of this forum. What do you think of the idea?:52, October 5, 2013 (UTC) I think that there has been some mis-communication with Sansee. Instead of a spoof Government shut down message, I know see the original content warning back to haunt 8, 2013 (UTC) - Yes, we did mis-communicate, as I thought she would install the file I specified. I'm glad someone is reporting something! I have found Puppy's instructions following the last round of Content Warning debate and followed them to copypaste MainPageTemp and delete the Content Warning Footer. The haunted-house background should already be disabled. Please tell me how it looks. Spıke Ѧ 20:46 8-Oct-13 - I think I need to log off to view. Be back in a:53, October 8, 2013 (UTC) - Please comment at the relevant Forum so more people will see it. Spıke Ѧ 20:53 8-Oct-13 - I'm afraid I cannot see it and yet you can. This is probably because it has a timer or something and I haven't waited enough before logging on to see a warning. I'll have to wait till tomoroow to see full effect therefore. Thanks for everything, this can go down in history:15, October 8, 2013 (UTC) - If you delete your Uncyclopedia cookie, you'll probably see it immediately. Spıke Ѧ 21:26 8-Oct-13 - I don't know how to I'm afraid. I'll leave it till tomorrow. Thanks Spike, it was good of you to make the spoof main:46, October 8, 2013 (UTC) - It is tomorrow now, for me and I was met by neither a content warning nor a spoof government message. Strange.:15, October 9, 2013 (UTC) - Delete the cookie. Like the Content Warning, any Uncyclopedia user will only see our little gag once, and will not even see it once if they ever saw the actual Content Warning. On Firefox, under Tools/Options/Privacy, click "Show Cookies." 10:26 9-Oct-13 - Also, note the almost complete lack of vandalism and bad edits overnight. All the unfunny Anons of the world have bought it, hook, line, and sinker, the level of credulity Wikia cited when they slapped the original Content Warning on (initially because someone might mistake our writing for truth and it would be Wikia's fault). Leave it on for good??? Spıke Ѧ 10:39 9-Oct-13 - Yessir! I am not using firefox but Internet Explorer. I do have firefox so perhaps I should switch to that. I used to see Content Warning all the time when that was around but this spoof page still alludes me. Thanks for UnSignpost:54, October 9, 2013 (UTC) - The control for cookies is somewhere comparable in IE. PS--eludes. Spıke Ѧ 16:05 9-Oct-13 - Went on firefox and saw it. Wonderful, absolutely:50, October 9, 2013 (UTC) Meet the new Newman66 in the future! In the future, I will make new articles, which are funny ones ranging from science stuff to video game articles. I may also request or make bots for Wikia and Uncyclopedia. Make sure to stay tuned, and don't forget that I'm better than ever! Newman66 Visit my table here! Contributions My works 01:05, October 7, 2013 (UTC) Denza for Admin? (Original title: "A query of complete neutrality that will not have any relation to events in the VFS") Alright, were I to get nominated by, whoever, would you, or some other sysop/admin remove it, or let it stand as a fair nomination? --The Sieger of Dungeons Lord Denza Aetherwing Inventory 17:06, October 7, 2013 (UTC) - And were I to somehow get opped, would I be able to keep it? --The Sieger of Dungeons Lord Denza Aetherwing Inventory 17:06, October 7, 2013 (UTC) Hey! I may seem like I want oppage, but I don't really want it. Don't put words in my mouth without backing. I may have said GIVE ME ADIM PLZ I R XEXZY!!11!, but that is obviously a joke. --The Sieger of Dungeons Lord Denza Aetherwing Inventory 22:24, October 15, 2013 (UTC) Newman's block Wow! For what did you block him? For suggesting me and ScottPat as candidates for admins to Chief Justice? But that was his opinion and it was perfectly legitimate, even though he did not know how to express it (forum/VFS). Anton (talk) 06:09, October 8, 2013 (UTC) - I have unblocked Newman for now but I will put him on official:19, October 8, 2013 (UTC) - Thank you for your concern, Anton. But my decision does not require your review, as the Summary indicates I would immediately ask another Admin to review it. (In fact, I asked two.) And, as before, I do not need to explain it to you, as I have explained it directly to him. - It seems as though he went on the wire last night and tried to focus attention on innocent individual actions. No, it is not a problem to express an opinion to the Chief Justice; it is not a problem not to know about the VFS procedure (though Denza makes clear, above, that he did Newman the favor of advocating for a new VFS vote because Denza wants oppage himself); it is not a problem to press the Save button. It is a problem when a new user, with a pattern of raping slightly new users, holds himself out to yet another relatively new user as a person through whom favors can be obtained from an Admin — even favors that the user didn't ask for and wouldn't notice the granting of. If you have heard these complaints and are interceding personally to get credit for obtaining justice, you are doing the same thing. Spıke Ѧ 17:41 8-Oct-13 - Let not assume the worst from Anton. I agree that this block was a good call...but Anton has every right to ask you about a block and he shouldnt be considered opportunistic for doing so. What paranoia. Remember how Aleister, Lyrithya and I questioned your excessively long block by Zombie before you became admin? It wasnt about getting credit for anything but caring about the best interests of the site and users. --ShabiDOO 18:07, October 8, 2013 (UTC) - Spike, you have told me several times that I maybe considered this site as an opportunity to create or break alliances. And I have told you that I did not. I have no allies here, only friends, if people want to be friends with me. And you are wrong, if you think that I want to promote myself, when I ask for justice (not ChiefJustice, but the abstract meaning of the word), it is only because I want justice, and not because I want credit. - Separately, thank you for responding to me and clarifying the matter even more, once again! Anton (talk) 20:32, October 8, 2013 (UTC) - P.S. Shabidoo, thanks for your post and Spike, I am not saying that your actions are wrong or not legitimate; I just want to make sure nobody gets banned for too long, if he does not deserve it. UN:CHAT Add another # infront of #uncyclopedia and the links, and we have our own chatroom, separate from #uncyclopedia. irc://irc.freenode.net##uncyclopedia. Its the future of... the past... --The Sieger of Dungeons Lord Denza Aetherwing Inventory 17:21, October 8, 2013 (UTC) - Ok. Don't people have to register their:04, October 9, 2013 (UTC) - Not really, unless I go insane and set mode +r. Btw, don't try to register it, its already registered to me. :D --The Sieger of Dungeons Lord Denza Aetherwing Inventory 14:46, October 9, 2013 (UTC) (+F flag bitchez; adminses will still get OPs tho.) -? • Puppy's talk page • 07:26 09 Oct 2013 - Yes, I think that is a fair summary. Not for nothing do we call him Captain Self-promotion. At least it doesn't include Pay-to-Play. Spıke Ѧ 19:39 9-Oct-13 Don't worry, I won't hold the power once people are here. I was going to actually hold a forum to create #uncyc-wikia as a channel, but due to the actions by members of the fork, I decided to make one with haste, as they would have tried to sabotage it if they got wind of it. I will retain the +F flag, but I am allirght with deopping myself, and giving the actual adminses power. Also, I think that active rollbackers should be given Voice flags (+Vv) to denote them as people to deal with minor bouts of vandalism or such. I'm sorry I didn't hold a discussion beforehand, and if I must, I can take down the channel, it was just that I can't trust the fork anymore. On another note, I plan to make a recent-changes bot, akin to Uncyc-rc in #uncyclopedia-rc-en, but for the wikia site, if we decide to keep our channel. --The Sieger of Dungeons Lord Denza Aetherwing Inventory 16:55, October 10, 2013 (UTC) Metal Gear Solid 2: Sons of Liberty Did you even read the article? The whole thing (as well as all the other MGS articles) are self-referencing UnScripts. I'd just made that edit because I was dissatisfied with the original version's conclusion. You can bring the matter up with Guildy if you like, but for God's sake don't revert because you assumed bad faith. Lord Scofield Stark 09:47, October 11, 2013 (UTC) - Your point is well-taken. So is mine: When someone makes a massive edit to a Feature Article (likewise yesterday's vanity edit of Justin Bieber), I do not have the time to track down the author and ask him if he is happy with the change. You are probably in closer contact with Guildy than I am. If he comes here and okays it, it can stand. Telling me that I "assumed bad faith" is manipulative. What I assumed is that for Uncyclopedia articles to talk about the writing of Uncyclopedia articles is bad writing, though there may also be plenty of it elsewhere in the series. Spıke Ѧ 10:17 11-Oct-13 Kiwi Slayer WHY DOES UNCYCLOPEDIA EXIST? ALSO, I BLANKED OUT THAT WEIRD PAGE ON NEW ZEALAND AGAIN(NOT) —The preceding unsigned comment was added by 122.57.106.136 (talk • contribs) - The above IP was blocked for his behavior in messing with Captain gull's userpage, plus blanking out part of this article. -- Simsilikesims(♀GUN) Talk here. 04:18, October 16, 2013 (UTC) Excuse me! Will you please stop edit conflicting me while I'm busy edit conflicting you! • Puppy's talk page • 12:56 16 Oct 2013 - And will you please not post to me while I am replying to you! I put back your correction of that little pederasty Freudian slip, didn't I??? Spıke Ѧ 13:04 16-Oct-13 - Not my fault. It's all the fault of the iProd. • Puppy's talk page • 01:07 16 Oct 2013 Banning Denza I dunno man, I think you were kinda harsh on him. Even if he didn't revert your move by mistake, which would be higly unlikely given that he's pretty much an established user by now (or is he), I believe it's the first time he's done it, isn't it? Maybe give him a serious warning or a 3-4 days ban, if it's that much of a problem, but I think two weeks, is a little over the top? Then again, you are the admin and you probably have a better judgement. I'm just suggesting you might want to re-consider the lengh of his ban. Peace --Mimo&Maxus (Talk) 16:28, October 17, 2013 (UTC) - I always enjoy explaining penalties on users to other users, even in the unlikely case that it was not a result of the banned user committing ban evasion by lobbying on other web sites. Denza's Forum:A Forum for the presentation and debate of new ideas did not present nor debate any new idea, though it raised the possibility that he would make new initiatives like his personal IRC channel in our name or his recent campaign to hold a new Admin vote (for him). It instructed other Uncyclopedians on how to contribute. In other words, it was a Forum set up for no purpose other than for Denza to have something to run; in still other words, it was vanity. (It followed a re-creation of a deleted article in mainspace which, likewise, had utterly no content and had to be deleted.) Rather than immediately delete the Forum, I remembered Simsilikesims's solution the last time we had a vanity Forum: Move it to BHOP, which is the location for Forums that do not pertain to the business of the website (which, remember, is comedy). - When he undid this move, I deleted the forum and banned him. The duration of the ban was the next notch up from the effective duration of his previous ban, in the menu of intervals presented to me on the Ban menu. It occurs to me that selecting 1 year would have resulted in exactly the same immediate reaction, and more time before he returns and resumes acting out and begging everyone to drop everything and look at him. But in that case, Simsie would have had to listen to yet more of Denza's life story. Spıke Ѧ 17:39 17-Oct-13 - Denza wants to run something and at the same time he wants to help the community. Now, instead of criticising him, why don't we allow him to actually run a project? Anton (talk) 20:38, October 17, 2013 (UTC) - UN:WYCD. Plenty to do, and it's a way to create respect that he's after before trying to create something new in order to control it. There's also the option of working on USP. He's been presented with these options, and asked to focus on this. • Puppy's talk page • 09:06 17 Oct 2013 - We have so little precious free time on our hands I don't want to waste it reading pointless forums and long paragraphs about how Denza is the dude. He's not ready to run anything. There's lots of admin, categorizing, proof reading, tagging, patrolling, updating featured article lists, chopping images, pee reviews etc. to do. --ShabiDOO 01:06, October 18, 2013 (UTC) - In fact, he did run something; he cajoled us into giving him rollback, spent several weeks doing good patrol work, then — in my opinion, right after asking me for an honest evaluation and me giving it, which fell short of a permanent declaration that he was the dude — the Usefulness Offensive ended and he went back to being an ornery kid writing about being an ornery kid. Spıke Ѧ 01:22 18-Oct-13 Hey there guys. This is what Denza answered me on his talkpage after I criticized him for begging to be unbanned on the other Uncyclopedia only when he was banned from this one....After that, I advice you to reconsider the lenght of his ban again... Only this time, I suggest you increase it. --Mimo&Maxus (Talk) 13:19, October 18, 2013 (UTC) - PS--Mimo, being banned means that Denza does not get to influence things on this website during his ban. Please don't help him evade the ban, no matter what effect you would like to achieve by doing so. Spıke Ѧ 13:25 18-Oct-13 I was just letting you know about his opinion on the ban. It was relevant to the discussion and I thought you people should, or might want to, know about it. --Mimo&Maxus (Talk) 13:33, October 18, 2013 (UTC) Treatment of user Makkkeeemeeemamamamamdddddooojojook I think Makkkeeemeeemamamamamdddddooojojook is just Makkkeeemeeemamamamamdddddooojojook. Whatever. I did not mean that. I meant that he probably does not hate you and will become a great in-joker if he keeps on going the way he does now.Anton (talk) 19:11, October 19, 2013 (UTC) - I am confused. I see a vandal who is making spam pages with no humour content (not even an in-joke, as Anton claimed) whose articles are deleted at QVFD and yet Spike has not banned him and instead has written on Makkkeeemeeemamamamamdddddooojojook userpage, himself breaking a rule of Uncyclopedia and his own personal belief of not giving vandals the communication and attention they want. I do not mean to say that Spike's actions were wrong as there must be a valid reason. What is the:21, October 19, 2013 (UTC) - He wanted to receive a ninjastar. That's all. Anton (talk) 19:45, October 19, 2013 (UTC) - (1) I am at the ballpark. (2) I deleted his mainspace crap because it is mainspace and they were crap. (3) I did not delete his user page because it is his user page even though it is crap too. (4) I replied on his user page rather than his talk page because I don't think he had one, and I am not going to welcome him and create one just so that I can reply, as I still think it is likely that when he sobers up or experiences a power failure, he will never remember his user name or see fit to look it up. Spıke Ѧ 20:18 19-Oct-13 - He is my hero. His user name made me laugh and laugh, and I told him so on his talk page. I may start a fan club for him, as he rocks my world. Aleister 19-10 - If you do, put it under BHOP, where similar fan clubs have been started in the past. BENSON! -- Simsilikesims(♀GUN) Talk here. 20:30, October 19, 2013 (UTC) - Spike did you just ban Shabidoo because of his comment? o_O --Mimo&Maxus (Talk) 23:40, October 19, 2013 (UTC) Rewrite on Gumby I have already removed two inappropriate bias quotes on the article Gumby, which I am going to give even more improvement on this article, which is one of the older prized articles on Uncyclopedia. The same kind of things I am going to do and already did somewhat to the article Indus River, which I made a forum team for, and I am also going to work with more professional users to improve Gumby and Indus River. Newman66 Visit my table here! Contributions My works 14:48, October 20, 2013 (UTC) - I was editing your page as you were editing mine. I agree with your edits, only not with citing the Terms of Use in the Change Summary, but everything's cool. Regarding your Forum, you already moved it to BHOP, which was my only problem with it. In the United States, by the way, no one knows what the Indus River is, nor especially uses it to refer to the India/Pakistan region, so this is not an absolutely essential topic for Uncyclopedia to cover, though it may line up with what you are studying just now; good luck on the Forum. Spıke Ѧ 14:55 20-Oct-13 - I live on the banks of the Indus River, and my family has lived thusly for a thousand years. We farm, and milk goats, and make the kind of living that river folk are prone to do. It's essential in my life, and in the life of my ancestors, but is not essential to uncyclopedia? We cry and tear our clothes, and at tonight's feast I will discuss this and we shall vote after the lamb and River Croc are consumed. Aleister 20-10 Too far It went too far. I agree and I appologise. SPIKE...we both have to tone down the language we use with other users sometimes. It goes too far at times and it gets toxic. --ShabiDOO 02:29, October 21, 2013 (UTC) - Agreed, we move on. This morning there even seem to be few of the pirates who crawled through the hole in the hull yesterday. Spıke Ѧ 10:11 21-Oct-13 - Who are those SPIKE? Newman66 Visit my table here! Contributions My works 12:51, October 21, 2013 (UTC) - Correct me if I am wrong, but I think he is referring to the sockpuppets we banned. ---- Simsilikesims(♀GUN) Talk here. 13:01, October 21, 2013 (UTC) - Was a user check run? Were they actually sockpuppets of each other (or Denza as:03, October 21, 2013 (UTC) - Black Sikhhead confessed on being a sockpuppet. Jihadrian on the other hand didn't (As far as I know). AllahuAcky was also banned for being, obviously, a sockpuppet (first thing to do after he created his account was to demand a voting on deoping Spike) although I can't find him in the block log. --Mimo&Maxus (Talk) 13:50, October 21, 2013 (UTC) 1 vs. 100 I was considering this for VFD as it is poorly formatted and not that encyclopedic. I know nothing of the topic and the comedy about the gameshow is funny in some parts. A re-write oppurtunity for you perhaps? Just a suggestion. 21, 2013 (UTC) - The existing article is awful, but I have never heard of the show. Go fish! Spıke Ѧ 20:38 21-Oct-13 - Sorry. Not in the mood for re-writing it now. Maybe another time if I remember.:24, October 21, 2013 (UTC) - No, "go fish" means, "I am not suitable for service as a sucker; please search further and find someone you can convince to do it" — not necessarily do it yourself. Spıke Ѧ 21:37 21-Oct-13 - Sorry. Google translate told me it was "Go and research it." I blame the:01, October 21, 2013 (UTC) - What did you call me Spıke Ѧ 22:04 21-Oct-13 - Tool=Google Translate. YOU FOOL (Get it...Tool, Fool...it rhymes...oh never:07, October 21, 2013 (UTC) - Reminder, you have now taken the very last tart from the VFD serving tray. One more and the rules are very clear, and these are written down. And so soon after a phantom "block" button appeared in buggy reports and made us all salivate! Spıke Ѧ 22:20 21-Oct-13 - Where is the VFD limit written:26, October 21, 2013 (UTC) - On VFD. In red and pink. I would be obliged to ban you. (One day would be my pick, if I read the rules aright.) That would be a shame, as I like it when you're busy. So quit nominating and let us catch up! Spıke Ѧ 22:29 21-Oct-13 - Ahh I see I was looking at the bit in orange. Sorry about that. No more noms tonight:34, October 21, 2013 (UTC) BAN THEM ALL! Not quick enough! • Puppy's talk page • 11:50 22 Oct 2013 One-year ban of Denza A message on behalf of the defendant Due to stress, a pileup of schoolwork, and displeasure with this site (uncyclopedia.wikia.com)'s administration, the defendant will be taking a indefinite break from this site (uncyclopedia.wikia.com). 198.105.216.188 02:44, October 23, 2013 (UTC) - In the above message, I deleted some additional demands, criticism, and attempts at applying a guilt trip. Being banned from the site means you do not participate in the site, even to portray yourself as a player in a court of law where you have some rights, or get a final shot to try to manipulate others. Spıke Ѧ 09:58 23-Oct-13 - I agree with the sockpuppet or troll or whatever he is here; even though your changing of other people's posts may be considered as a prevention of drama, I personally would like 'a careful record of what said' and instead have to always check history and all the individual edits, to understand the conflict. Anton (talk) 13:26, October 23, 2013 (UTC) Frosty permabans DungeonSiegeAddict510 Just a notice to say I have updated his ban to indefinite after words stated above and dickish words directed at Puppy on the fork. I'd strongly suggest you keep an eye on his pages because on the fork prior to me locking his userspace and banning proxies/shared ips he was using a spiral of drama and time wasting resulted. Probably best if someone more active here than I am did the same. I'm going to be blocking any more socks he uses on both sites as soon as I see:20, October 23, 2013 (UTC) - I just tested. Blocked users here are unable to edit their own talk pages. - As an aside, can someone lift the ban on 58.107.181.104, block ID #69802? (Stupid, stupid puppy.) • Puppy's talk page • 09:03 23 Oct 2013 - This ban is now lifted, though I had to relearn what Simsie taught me about BlockList, which you are just now learning. - Thanks, Frosty, for the continuing vigilance. I was convinced that, at the end of two weeks, he would exhibit more misconduct that would require a follow-on ban, and each ban induces him to howl at his Darthpedia buddies and for them to attack the site as part of the Denza crusade. Therefore I support getting over with it for good, and not continuing to hold out his hopes that there will be another chapter--which reads the same as the first. Romartus has noticed the ban and seems to be fine with it too. Spıke Ѧ 09:58 23-Oct-13 "Darthipedia buddies" While I'm sure you could care less, it would be vastly appreciated if you'd stop pointing fingers at Darthipedia (or "Darthpedia", as you put it, as the I is silent) every little time Denza acts out on this wiki. Not only is Denza permanently banned from Darthipedia for the very same reasons he's banned here, Darthipedia hasn't been active for several months with the exception of a barely-used IRC channel that he almost never joins, so saying that we're his "buddies" is equally ridiculous as saying you're his lover. Additionally, I'd suggest at least skimming through Darthipedia's official stance on trolling. Spoiler: There Is No Denza Cabal attacking you or this wiki and paranoia is a sign of deeper issues. Thank you for your time. Darth Muscare (talk) 10:54, October 23, 2013 (UTC) - I am sorry to have tarred you all with the same brush. However, two of your number did and do listen to Denza's rants and act out here in his cause. And they are just as snide as you are too. Rather than accuse me of prejudice, I would suggest that you better control your lot so as not to give rise to prejudice. Spıke Ѧ 11:08 23-Oct-13 - It is pointless to blame the entire community for what two individuals did. If I, for instance, will go and vandalize Wikipedia, they won't blame Uncyclopedia for not being able to control me. Denzadenzadenza I cannot deny that DungeonSiegeAddict was sometimes rude and uncivil, but you cannot deny that his idea ##uncyclopedia was thrown away very impolitely, even though he had best motivations. Anton (talk) 13:25, October 23, 2013 (UTC) - I can deny. His behaviour did not indicate any community spirit. The chat room was initially put forward as an alternative to the chat room he had just been banned from, and he placed himself in a position where he couldn't be banned. This was after he had been banned from the fork site, along with other chat channels and wikis. When presented with the option of releasing control of it, he said he couldn't - despite it actually being a fairly easy task to do so. He did not gather community support for the idea until after he had established the chat channel. And then he put himself forward (supposedly as a joke) as a draw card for this new channel. If he was looking to support the wiki it would have been easy to do this - and put forward this idea - in a way that made him an equal part, rather than a controlling factor. - The idea itself I have no fondness for, but the fact his entire actions surrounding it were completely self motivated just made it less appealing. I approached him initially with politeness, and then humour to try and defuse his drama, and then blunt statements, and each attempt to communicate with him was met with no response. Every polite approach I made to him was ignored - simply because I didn't agree with him. Rudeness was the final step to try and get him to look critically at the way he was acting - and the only response to that was another dramatic outburst. - At no stage did he appear to be a willing, positive contributor to this or any other wiki, and multiple times he appeared to be creating dramatic scenes any way he could. In short, the dictionary definition of a troll. • Puppy's talk page • 01:47 23 Oct 2013 - Concerning your last comments, that kind of opinion was the primary topic of this. - I have to admit that you were polite, but your first comment "So to sum up, you've created a channel that no one here asked for..." would offend me, if I were at Denza's place. In addition to this, may I ask you: "Have you t least visited the channel?" I did and did find it 'Denza-controlled' or anything of that kind. What I noticed was a bot that was trying to op Denza, whilst Denza tried to deop himself and finally 'won the battle' (I think). Many of Denza's critics preferred to ignore and still judge it. - So to sum up we chased away and banned the user who could have been a great contributor, if someone would have helped him. Please, don't talk about how you told him everything he had to know about being 'useful'; there is a great deal more than this and I talked about our attitude towards users here but it did not even have the slightest possible effect. Anton (talk) 14:52, October 23, 2013 (UTC) - Actually, that was one of my later comments to Denza, where I started to get frustrated with his refusal to respond. And why would I have visited a channel that I was completely against the creation of? Denza has shown - over and over - that he is unstable and unwilling to listen. That doesn't make for a good contributor. - As for your forum - I did write a response to that forum much more substantial than what is there, but due to network issues it dropped off. I'll respond to that over there a little later. • Puppy's talk page • 09:16 23 Oct 2013 - Well, I hope this response will re-appear. Anton (talk) 15:06, October 24, 2013 (UTC) - And it's unbelievable that he had all those sockpuppets and meatpuppets on the fork. Newman66 Visit my table here! Contributions My works 21:28, October 24, 2013 (UTC) Forum:UnSignpost Changes! Sorry to bother you Spike but could you take a look at this please. Two new users are claiming (one is banned, both created recently) that we cannot create another namespace. While I would dismiss this as vandalism due to the odd circumstances and likely sock puppet he has brought up some evidence that seems legitimate, could you take a look at the evidence and make a decision please?:05, October 23, 2013 (UTC) - Puppy has given an explanation and we can move on. --Mimo&Maxus (Talk) 12:16, October 23, 2013 (UTC) - Yes, sorry about that Spike, Puppy's dealt:35, October 23, 2013 (UTC) Damn silly of me! I told you to huff wrong forum page Spike! Please could you delete Forum:UnSignpost Namespace and reinstate Forum:UnSignpost Changes!. Sorry,:06, October 23, 2013 (UTC) - Spike why did you delete Forum:UnSignpost Changes! in the first place? It contained the voting on making UnSignpost into a new namespace and should be preserved for historical purposes. --Mimo&Maxus (Talk) 17:17, October 23, 2013 (UTC) - It didn't originally. It was on Forum:UnSignpost Namespace originally then I moved it to Forum:UnSignpost Changes! to put all onto one forum so others can be deleted as mentioned on User talk:ScottPat!:22, October 23, 2013 (UTC) New namespace As per the forum relating to it, we now have UnSignpost as a new namespace. Some USP related stuff is admin protected though, so moving it over to the relevant namespace will require an admin's touch. Tim has set this up to be non-content namespace (doesn't show in random searches, etc.) • Puppy's talk page • 12:22 27 Oct 2013 - Am happy to oblige; at the moment am a little distracted by the broadcast of the World Series. Spıke Ѧ 00:32 27-Oct-13 YIKES I just read the second de-op spike forum. So that there is NO doubt...I had nothing to do with it...and I would have voted AGAINST. The whole forum was way out of line and no user/admin should have to read something like that. We all need to smoke some virtual cannabis. Strong strong virtual cannabis. From British Columbia or Morrocco. Premious quality. The kind that makes you laugh your ass off at the slightest joke. In a 10 hour laughing fit that makes us soil our undergarments. Does anyone know where to get any? --ShabiDOO 18:38, October 23, 2013 (UTC) - No one is entitled to protection against harsh words in an open-borders place like this. That Forum was clearly agitation from outside. It is a difficult and important call telling good-faith users who are here to write comedy from instigators, and one can make errors in either direction. But a new user whose first edit is opening a Forum about our personnel, or reverting me with a Change Summary that parrots words I used in the past on someone, is surely a sockpuppet here to pursue a grudge and not to contribute. There is no principle of management under which such a user is entitled to call a vote. But it's problematic to have established users question my reaction to each new user when they don't have to make the call and don't bother looking at the context, acting as though there is no call to make, and in the process projecting disharmony that the outsiders take as an opening for follow-on trolling. It is not "paranoid" to observe that there are people who would enjoy making Uncyclopedia fail. Regarding undergarments, I suggest Walmart. Spıke Ѧ 02:21 24-Oct-13 500 ft tall turd monster Does the merit a VFD nomination? No one will ever type it in. I find turd jokes off-putting from my point of view but it isn't that bad in terms if comedy.:07, October 24, 2013 (UTC) - I not only neglected this but took the 20th VFD slot just freed up by the Acting Poopsmith (moi) for the worst user of the deleted Category:Over 9000. I'll take a look now. Spıke Ѧ 14:16 25-Oct-13 - Thanks. Ohhhhh - does that mean there is an excuse for a 30/40/50/100 nom limit on VFD forum?:19, October 25, 2013 (UTC) - The answer to the original question is that there are bigger fish to fry. This article is in the form of a scientific paper and is pretty well done although its subject is gross. In contrast, there are dozens of articles with graphic descriptions of the author's bowel movements (the Yuky Doody series). - I am hoping our Poopsmith will get out of his body-cast or acquire voice-recognition editing technology soon. The 20-ballot limit predates me, dates back to a time when there were many more voters, and is not crying for review, given, for example, how the stuff at the bottom of the page has languished. Spıke Ѧ 14:24 25-Oct-13 - Fair enough. I am still a bit confused as to what the Poopsmith page is as on it it says that if you are a regular VFD voter you can't use it. I had always presumed it was an overflow car park for VFD but maybe I am:26, October 25, 2013 (UTC) - Please refer to its talk page, which is where Mimo applied for the job, with commentary by Puppy and me. Spıke Ѧ 14:39 25-Oct-13 Pear Inc. Why did you delete it? I know it had almost no content but there was a construction tag. Don't you think you should've waited a little more? --Mimo&Maxus (Talk) 13:46, October 24, 2013 (UTC) Just saw your answer on hellroad24's talk page and I understand why you deleted it. --Mimo&Maxus (Talk) 13:52, October 24, 2013 (UTC) User:Xzd5bp/Ted Cruz I read your comments and a Pee Review from another user regarding the article I submitted. They're both very helpful and I appreciate your insight. I'm not being sarcastic or spiteful! The critiques make sense and I agree with them. Unfortunately, I wrote it strictly for a specific audience of haters. So I guess it would be inappropriate to post it on this web site. Please feel free to dispose of the draft as you see fit. I apologize for any inconvenience. Best Wishes, ~~xzd5bp P.S. I'm new to the Wiki game so I apologize if I didn't respond in the correct user group or format. I'm x^5 years old. I have a peptic ulcer. I need a root canal and I have a wife hocking me for a new car. - As I replied at Simsie's talk page, your text is properly "disposed of" now, as it is in your userspace, where you will still be able to find it if a more general comedy gimmick occurs to you some day. If you are into current events, take a look at UnNews and see if you could contribute (and try to make it funny to people across the political spectrum!). Regarding the car, I recommend the Hyundai, although you will surely still need a root canal. Spıke Ѧ 15:47 24-Oct-13 Mimo volunteers as Poopsmith And QVFD I've already asked this on Uncyclopedia talk:Poopsmith's Lounge but since I got no answer I assumed you didn't see it so I'm asking you my question again here. Should I archive QVFD (after all the articles there have been patrolled by an administrator of course) or is it not my responsibility to do so? --Mimo&Maxus (Talk) 15:47, October 17, 2013 (UTC) - As the attending Admin is supposed to use {{BPC}} to note that he took care of the little bastards, Admins tend to poopsmith it themselves. The Chief Justice complained recently that I was neglecting this, but sometimes I like to leave it long so there is an example of the right way to nominate a {{Redirect}} because no one reads the instructions. If you would like to clean it up from time to time, that wouldn't be a problem. - Did you see my new material at VFDA (new shortcut!) regarding creating new VFD archive files? You might wait on this because next week Puppy's new VFD system will be voted on, and it might be nice if the start of a new archive is at the start of the new VFD system. Spıke Ѧ 15:54 17-Oct-13 I did actually and found it very helpful. You might want to add info about poopsmithing QVFD, like the things you just told me, to avoid similar confusion for future poopsmiths. - P.S. It's alright. I wasn't in a hurry to create a new VFD archive anyway! (Like anyone's ever been in that kind of hurry) - P.S. (2) In a few more hours, I will finally be able to move my first article from VFD to archive 276! Yay! --Mimo&Maxus (Talk) 16:17, October 17, 2013 (UTC) Hmm, positive byte count equals negative byte count...diffs look correct...By George, I think he's got it! Spıke Ѧ 19:27 17-Oct-13 - OR I removed parts from VFD to make it look like I tried to archive a closed nomination and then added random, meaningless text to the VFD archive to make it look like the archiving procedure was succesfully over. Of course, all that would be just an attempt on making you notice me, your long-lost son, who, in order to gain his father's love again, will change his way of life as a vandal and will, eventually, find his inner Uncyclopedian. It's either that or what you said. --Mimo&Maxus (Talk) 20:29, October 17, 2013 (UTC) No, like I said, I looked at the diffs too. "Trust but verify." (Reagan) Spıke Ѧ 20:35 17-Oct-13 Sidelined by injury I fractured two of my fingers and typing with the left hand is kinda hard so I won't be able to poopsmith for a couple of days. You told me to give you a heads up if something like this were to happen, especially when VFD is almost filled with articles like it is now, so here it is. Anyway, see you in two or three days! Bye! --Mimo&Maxus (Talk) 20:24, October 24, 2013 (UTC) - OK, thanks for the notice. Spıke Ѧ 20:28 24-Oct-13 - Mimo "fractured" two of his fingers. hahahahahahahahahahahahahahaha Aleister down to the nub Delay before poopsmithing I noticed that you didn't follow the 12-24 hours rule on archiving closed nominations so may I suggest decreasing the waiting hours to, let's say, 5 or 6? You're not the only one who was too bored to wait for the 12 hours to pass to get to work (first it was me and then Simsie) so I think it'd be pretty practical to change this rule. P.S. The reason I didn't create a forum to discuss this is because it's relevant only to poopsmiths and ministering admins. --Mimo&Maxus (Talk) 14:32, October 28, 2013 (UTC) - I agree a broadcast isn't necessary. The reason I didn't wait is not "boredom" but that VFD has been pegging 20 ballots for a long time. Early poopsmithing adds clarity that there is space for new ballots and is at the discretion of the Poopsmith--as I wrote in VFDA. Meanwhile, how is the sore hand? Spıke Ѧ 14:43 28-Oct-13 Oh right! I accidentaly clicked the wrong revision in the history and it caused me the confusion which led to this section. Sorry for all this. Also, my hand is alright now, thank you! --Mimo&Maxus (Talk) 15:03, October 28, 2013 (UTC) UN:SIG again Would you, please, take a look at the changes I made to UN:SIG and say if this can be accepted or not? The changes are minor but they help to make the page less serious, whilst it still contains all the essentials. Anton (talk) 16:05, October 23, 2013 (UTC) - I addressed UN:SIG today at the new, initial section of Forum:A new VFS is in order, that I would prefer that humor be added through photos and captions. Some of the levity in your version, while it reassures us that we are still funny, might make it harder to read for the newbie who would be directed to read it. Spıke Ѧ 16:16 23-Oct-13 - Well, then we can add photos. But could you, please, tell me what parts may be hard to read for a newbie? - P.S. I myself was rather new to this website when I read UN:SIG and, although some of the parts were rather confusing, the part about the size of the sig was really clear, even with "your penis is too short joke", which was surprisingly relevant. Anton (talk) 09:17, October 24, 2013 (UTC) From User talk:Anton199 Spike....I would like to respond to your comments on my talkpage because that particular section is full of drama-related comments, whilst neither Pup, nor me wanted to cause any drama. First of all, I do try to take into consideration whether the user in question (often, a banned user) is new to this site, was not behaving well or is incapable of writing. And when I talk about them, I always try to explain why they should be unbanned. Second, you misunderstood the "Diary of a disillusioned editor". If you were watching its creation (which you were not, but that's not anyone's fault), you would have seen that it was not even a diary at the beginning but a list of facts, presented with humour. Then, these facts were not news anymore, so I thought they would be a perfect diary. Then I added some thoughts of "a disillusioned editor", thinking that they would also be funny. Now, I am not that editor, I do not feel disillusioned and these are not my thoughts. This was an attempt to present the latest events with humour. If you thought I was manipulating the site through the UnSignpost, you could have told me before. Third, I am sorry if I did something to you, but I really would like to get responses to things I am saying, because I have questions and you seem to think that you've already responded to them by your previous comments. Anton (talk) 17:08, October 25, 2013 (UTC) - Spike I agree with what you said on Anton's talk page although just to point out that I responded to the Darthipedia person as I thought that you had gone and so did not want to give Uncyclopedia a bad impression if he wasn't going to stick around waiting for a reply. Therefore I hastily put together a message saying that Uncyclopedia does not want to attack Darthipedia as a filler till you came back. It wasn't meant to be official policy and I did not mind you overriding:25, October 25, 2013 (UTC) - Gentlemen, I believe Mr. Romartus wanted us to shut down the drama, not merely move it to another page, and especially not to play out all other unfinished dramas. ScottPat, I meant to cite examples of people appearing to act as official representatives of Uncyclopedia, including one where I was at fault; not to demand satisfaction from you. Anton199, I am working to inject levity into UN:SIG through illustrations. That is all for now. Spıke Ѧ 18:36 25-Oct-13 WP:Template:Infobox officeholder Hey SPIKE, would it be possible for you to transfer the Officeholder infobox from Wikipedia to here? I think it looks a lot better (design-wise) than the President infobox we have currently. --EpicWinner (talk) 00:32, October 26, 2013 (UTC) - I could do it, or you could do it. A problem is that we have different values from Wikipedia; theirs is completeness and ours is humor. In cases where we have made Wikipedia templates available, newbies obliged to fill out all the fields either use nonsense numbers and unfunny stuff or leave them blank and display the error messages. By comparison, a lot of the Uncyclopedia Infoboxes were edited a couple years ago to ensure that most of the fields would be optional. A better question might be: Can you improve the appearance of the current President Infobox? Either I or PuppyOnTheRadio might be able to do so. Do you think this is a better approach? What about our template do you think looks bad? Spıke Ѧ 00:55 26-Oct-13 - PS--Another reason it might be better to improve the existing template is that, if you start using a different one so your page looks better, other President pages don't pick it up and don't look the same. Spıke Ѧ 00:57 26-Oct-13 Patrolling tool Recent changes. Let me know if it's still not working. • Puppy's talk page • 06:51 26 Oct 2013 - This is an unpatrolled edit, created to see if Spike can get his beaver based tool working. Please do not patrol this edit (unless you're Spike). 58.107.181.104 - There was nothing about RecentChanges that did not work for me, and I am able to mark one or many edits as Patrolled. "Watchgadget" on my Watchlist is the gadget that failed. I'll test this now. Spıke Ѧ 08:06 26-Oct-13 - Watchgadget is indeed working now, and the Java Error Console is quiet. Wha'djou do?! Spıke Ѧ 08:08 26-Oct-13 - Nothing. Just figured that the change to the js that altered the TOC may have also impacted on other things, so just thought I'd check a couple of gadgets to see if they had come back to life. • Puppy's talk page • 08:19 26 Oct 2013 - But Watchgadget broke long before the TOCs did. Perhaps Wikia are simply doing work! I'll give it a day and then ask to have my bug report closed and remove my notice from UN:HAX. By the way, the entire site seems to have just gone down for about 5 minutes. (I thought of you.) Spıke Ѧ 08:28 26-Oct-13 - I never go down that long. • Puppy's talk page • 09:03 26 Oct 2013 - At this writing, TOCs are broken again, and so is Watchgadget. Very interesting. Spıke Ѧ 23:53 26-Oct-13 - Tim's looking into the TOC issue, per his email to you. I wonder if it's something that is impacting on only some servers? • Puppy's talk page • 11:59 26 Oct 2013 A quick inquiry into inter-wiki linking Are we allowed add a link to our user page that directs to another language's Uncyclopedia wiki (that is owned by wikia) as I was wondering whether I could but after all the recent comotion over links to the fork I thought I'd check with you first? It will not say I have moved or anything (as I haven't) simply will link to my user page on the other language Uncyclopedia wiki.:20, October 26, 2013 (UTC) - Yes; this is mentioned in UN:SIG. Spıke Ѧ 19:31 26-Oct-13 - Thanks. Got, October 26, 2013 (UTC) VFD stuff So, a nomination will look kinda like this: =={{VFDn|Article}}== {{VFDt|time= etc. To close it, it's two letters that need to be changed: =={{VFDc|Article}}== {{VFDg|time= etc. I've removed the padlock image as it was doing odd things to the TOC, which may be just due to the issues we're currently getting. Oddly the old version of {{VFDc}} was doing the same thing. The newer version adds in a link to add {{oldvfd}} (after checking if it has been added in the last 1-2 months), a link to create a new section in the archive (based upon year-month nomenclature), and probably something else I don't remember. {{VFDg}} simply greys out the boxes. (g is for grey.) You may want to update the admin instructions so that this is clear to anyone 'smithing. • Puppy's talk page • 12:22 27 Oct 2013 - Yes, your reforms will obsolete a several of the instructions. I will take responsibility for correcting them once I have been through the process a couple times. Also, once we know everything works smoothly, we might ultimately want to replace the existing templates rather than rally around a new set with completely different names and work to educate people. Spıke Ѧ 00:32 27-Oct-13 Orphaned images Just so I can clarify your process - you open the article, and from there open individual images to ensure they are single use images prior to deletion? If they are you then delete these images individually. Is that right? If so, would a template that shows the names of all images “linked to” or “displayed in” a particular article, and under each a list showing what other pages use these images, and if the image is shown as {{notorphan}} (sp?) be of use? If I also include a delete link on these saying “deleted as used only on xyz” or something along those lines? • Puppy's talk page • 09:09 27 Oct 2013 - Oh - I'm thinking of reducing the clutter by reducing the links to single letter, with a tooltip to what it actually is. I've erred on the side of clarity at this stage until we all get used to the way it works, and until I work out my remaining kinks. • Puppy's talk page • 09:13 27 Oct 2013 - Such a template would be enormously useful! Separately, I notice two things in the rewritten VFD procedures: - The threat of "1 day. No exceptions" is gone; intentionally? I appreciated having this clarity, in ScottPat's recent ban, versus the implied job of weighing willful violation against his useful work. - The rules plus instructions to Admins are unclear whether failure to tag the article makes the Admin reset the clock (my usual approach) versus invalidate the nomination (the historical reality, but mostly a slap-down to users. Your thoughts? Spıke Ѧ 21:40 27-Oct-13 - 1 day, no exceptions probably belongs more on Uncyclopedia:Ban Policy than directly here, where I thought it was mentioned. (It isn't, but that was why I left that timeframe out of here - bad assumption.) Rewriting that rule to "Do not increase the number of active nominations on VFD to over twenty, this will lead to a banning." and adding this to the list at Uncyclopedia:Ban Policy would make more sense to me, but we could just as easily add back in the original wording, but I'd still suggest adding it to policy. - I've always felt that this was the call of the admin in question. I've seen it go both ways, depending on the user who nominated (which was useful for dealing with VFD flooders who remained just within the 20 articles.) - Back to the template: - I've created a draft template at {{User:PuppyOnTheRadio/image thingy}}, which I'll get you to check out before I template space it, as you may be able to add suggestions. - The draft calls on User:PuppyOnTheRadio/image thingy3 where I've added five images - one notorphan, one unusued, one transcluded by full url of the image, and two others widely used. - I have a real-life example at User:PuppyOnTheRadio/image thingy4, which has the text of {{User:PuppyOnTheRadio/image thingy|2 Wizards 1 Cup}}as the entirety of the page. - What I can add to it is a delete link with a pro-forma summary (similar to the delete link that started this). I can also exclude File:Bloink1 solid.png, as that's transcluded as part of the VFD template. - Note that this does not catch images transcluded by full url. - One last thing, which this template reminded me of. I created User:PuppyOnTheRadio/image ages ago, which uses a similar dpl to this. This goes through all the images that we have on uncyc (one page of 500 at a time) and highlights if an image is used, used only in user/user talk pages, or unused. Because of the way {{notorphan}} works, those images tagged with this template show up as used. This was designed as a quick way to determine if an image was truly unused. I created this as a way of prioritising importing images into the mirror, but it still sits there as a useful way of determining if images are worth keeping or deleting. I can easily update that page so it shows a thumbnail/gallery size of the image as well. - If we are going to delete unused images, this may also be a useful tool. Of course, we still have Special:UnusedFiles, but that doesn't reflect if the image is used on user space only. • Puppy's talk page • 04:53 28 Oct 2013 - I'm an attention seeker and I am feeling unattentioned! • Puppy's talk page • 10:04 29 Oct 2013 Santa Claus The IP you were reverting deleted a section of this. I was inclined to let it stand, as the section didn't add any real value to an already over full page, but figured I'd leave this for you. • Puppy's talk page • 12:22 27 Oct 2013 - Sigh! My last revert complained that his addition was UnNews-ish (as well as talking about the "happy nigga"). His new edit attacks a paragraph he may feel has the same flaw. I stayed my hand on this in case he is starting to think like an owner. If he goes from there back to a rant, Rollback will get 'em all. Spıke Ѧ 00:32 27-Oct-13 - Much the same thought process here. If it hasn't already been done I'll mark as patrolled. • Puppy's talk page • 12:41 27 Oct 2013 Uncyclopedia:FFS Spike, much to our disapproval, the result of the nomination was Keep, not Keep as a historical archive. Please, unlock the page. --Mimo&Maxus (Talk) 15:58, October 29, 2013 (UTC) - No, there were no Keep votes, and 5 votes either to delete it or to at least discontinue it as an active page. So it is locked and marked {{Historical}}. Spıke Ѧ 20:35 29-Oct-13 Is that a new rule you just created or has it actually been used in another survived article before? If an article is kept, for whatever reason, it's simply kept. There's no need to complicate things. --Mimo&Maxus (Talk) 20:50, October 29, 2013 (UTC) - No, this is not spontaneous Spike tyranny. There are several more suitable dispositions than outright deletion — userspacing being the most common — and I did not act without a mandate. Spıke Ѧ 20:52 29-Oct-13 - Yeah - been done numerous times before. If there is no objection saying “we want this” but there is a compromise solution put forward (like “redirect to blah blah”) this gets done. This predates SPIKE's tyrannical reign. - {{Historical}} has been adjusted to do a “no editing” lock similar to old forums. This may mitigate the need to admin protect pages going forward. (I have no concern if this one is locked or not.) - I'm undecided as to wether we need to keep UN:FFS or FFS any further - we don't want to create unneeded red links, but they have no purpose going forward, so I guess it's completely up to you. - Also {{FFS}} and {{FFSblock}} could likewise be given an <includeonly>{{Historical}}</includeonly> as well. • Puppy's talk page • 10:02 29 Oct 2013 TOC again Has this now shrunk down to just four headers for everyone, or is it just that I'm using an old version of IE at work? • Puppy's talk page • 10:57 29 Oct 2013 - I have seen different things over the course of the day. But I have changed locations, and enabled/disabled JavaScript, so I can't really say what state the software is in. At no time have I seen only four items in a Table of Contents when there should have been more. Also: At the moment, Watchgadget doesn't work. Spıke Ѧ 01:58 30-Oct-13 - Seems to be back to as normal as we get. • Puppy's talk page • 08:49 30 Oct 2013 - Watchgadget is still not working. Separately, thanks for your clean-up of the old infrastructure of FFS. Spıke Ѧ 12:20 30-Oct-13 Thank you await your respostapedido for creating page hello am SPIKE "Amilton Christ" would you create me a page in the Wiki as I see it and very competent in his work and this my email: pr.amiltondecristo @ hotmail.com site: I await your response thank you user:Amilton, 08:48, October 10, 2013 (UTC) - Hello. You have twice tried to upload this content, and I have twice deleted it, after discussions with two other Uncyclopedians. Your content has no humor that we can detect, your subject is not notable to other readers, and your content is indistinguishable from vanity, even more so now that your email and website shows you were trying to create an article in our encyclopedia about yourself. I have informed you of these problems, on your user talk page and in a box in the articles, and you did not respond. I banned both of your accounts. We are a humor wiki, not a personal disk farm or vanity blog. There are many other websites that would be happy to post your vanity in exchange for you viewing their advertisements. Spıke Ѧ 12:44 31-Oct-13 Why?:Does it burn when I pee The parts that Anon deleted were awful. I would re-delete then myself and maybe even nominate the article for VFD but this would be reverting you. Anton (talk) 17:49, October 31, 2013 (UTC) - You are right. The whole thing is awful. There is a difference between an Uncyclopedian section-blanking with explanation and Anon doing it without. However, this page was "featured" (within the Why?: project, a gray area) and it is assumed not to need fixing or huffing. Also, there are bigger fish to fry. I'll reduce Anon's ban to 2 days. Spıke Ѧ 18:15 31-Oct-13 This... Any thoughts? User:PuppyOnTheRadio (not signed in) 05:57, November 5, 2013 (UTC) - That just makes everything too darned easy! Useful also to the poopsmith and random user who can't actually delete the items. Such a useful compendium, in fact, that I wouldn't mind a button in the sidebar called "Relations" for every Uncyclopedia page. Label the tables; "Links" should read "What links here" for consistency. Why are you not signed in? I read something about a national strike, are you scabbing it under an assumed IP, my good liberal? Spıke Ѧ 11:27 5-Nov-13 - It was a public holiday here today. The first Tuesday in November all Australians stop working to worship the ritualistic whipping of horses, and women are obliged to wear a bit of lacy stuff on their heads and say they are fascinating. I was obliged to go to work however and realise exactly how damned dull my workplace is when I have nothing fruitful to do. I also discovered just how annoying MSIE can be, and decided that for half a dozen edits I would jump to Firefox, where I hadn't logged in. - The problem is that this page isn't a true page, as such, and is actually a trick using editintro. I'm considering removing the “delete” link on {{VFDn}} and replacing it with a link that generates a page like this. To be on the safe side though it might be an idea to set up an auto filter that won't allow pages to be created with the title of Do not save this page/what ever, or even This page does not exist/whatever, given that page is already a taboo for other purposes. - As for sidebar link - there is a feasible way to do this rather than my current collection of hacks, but not something I'd really considered. • Puppy's talk page • 12:00 05 Nov 2013 - Goodness, Australia must be crazier than we are--though today is Election Day in a few places even though it is an odd-numbered year. The Delete link is not useful to me but your new display would be. A sidebar link could be written with {{BASEPAGE}} to have the same effect. - I can protect page names with an Abuse Filter but don't see why it's necessary. - Hooray for Firefox! Hooray for your job becoming boring again after a mid-year in "management" and away from Uncyclopedia! Spıke Ѧ 12:37 5-Nov-13 - Didn't think of {{BASEPAGE}}. I tend think think more {{SUBPAGE}} when doing this stuff. Either way it generates the text by creating a page that isn't a really a page, but it does keep the save/preview all down the bottom there, and my concern is someone not knowing what they are doing creating meaningless pages. Of course, we have that happen all the time, but you get my meaning. • Puppy's talk page • 12:56 05 Nov 2013 - Oh, I get it. Indeed I don't know a way of splashing a report onto a screen except by creating a page. Spıke Ѧ 13:01 5-Nov-13 Okay. If you - change MediaWiki:Gadget-autotags.js to link to a js page in the MediaWiki section, rather than in the user section, - take the js from here and move it to the page you just created, - change the text… sectionText = '==[[' + vfd.page +']]==\n{{Votervfd| time=~~~~~\n|keepnumber=0\n|keep=\n|delnumber=1\n| delete=\n#' + vfd.comment + ' ~~~\n|comments=\n}}\n\n' + sectionText; …to something like… sectionText = '=={{VFDn|' + vfd.page +'}}==\n{{VFDt| time=~~~~~\n|delnumber=1\n|delete=\n#' + vfd.comment + ' ~~~\n| keepnumber=0\n|keep=\n|comments=\n}}\n\n' + sectionText; …a fairy will get its wings! • Puppy's talk page • 01:51 05 Nov 2013 - Cripes! this is like listening to full-speed Spanish: I understand half the words but have to strain to figure out what we're doing. Moving the page from userspace is a damned fine idea, and I trust we have broken at most the single button on the sidebar. I depend on you to verify the change, as I long ago removed my sidebar. Spıke Ѧ 14:24 5-Nov-13 - Oh - this is more along the lines of the drop down tag for VFD that caused Anton's stuff up the other day. Sidebar is a step or two further away. Needs a little more testing for my satisfaction. • Puppy's talk page • 02:35 05 Nov 2013 - Hmmm… something screwy. I might play with what we have there (even though my js is crap) and see what I did wrong. Should be better than what it is though. • Puppy's talk page • 07:50 06 Nov 2013 Ace Attorney This article seems to be bloated randumbo to me, but given your last edit there, I'll hand it back to you. • Puppy's talk page • 07:42 06 Nov 2013 Baseball-based nuclear weapons delivery system Hello Maestro. If you have minutes or hours can you practice your magic on the article? I've put it into some kind of shape, but I know you love baseball as only an American can (one of the themes of the page) and would love to see what you can do to improve the page. Did you read the Babe Ruth book I linked to the line about him - he does seem to be the most underrated player in the game. Did you know he not only would have hit hundreds of more home runs if he had played in today's stadiums (would have hit 104 in 1921) but in every park he played in in the majors he had or has the record for the longest home run in that park! If he were still alive I'd buy him a beer, a hot dog, and a whore. And one of each for me too! Aleister 8-11 - I don't want it. The page title is still the punch line. It is not a satire encyclopedia article; it is — now, more than ever — a fiction essay; now with higher-quality writing than before, but the point is not to showcase your writing skills, but to further the project, which is a compendium of cracked takes on real things. This didn't and doesn't fit. - And, to continue a past discussion, boldfaced photo captions is not "a style variation we have allowed since 2009"; it is a unique personal affectation that no one has objected to, except me, once, at the Forum. If you don't like the way captions display, I can give you CSS to put on your computer to change them. Compelling them to be displayed differently on everyone else's computer is tantamount to signing your articles. It's vanity. Spıke Ѧ 12:48 8-Nov-13 - I agree that it's not that good, I was just playing around with it and got carried away with the story. It's a stupid title anyway, and not much else to do with it. And many magazines and newspapers use bold captions, they accent the pictures and pop out the jokes, which otherwise blend into the woodwork because of the contrast of the colors in pictures. I'm not the only one who uses those, and they've been an option since '009, so I use them because they look better (to me at least). Nobody has questioned them before you, so did uncy have a policy at some point? And since you don't want to talk about Babe Ruth, I dunno. Aleister minutes later - It would fit in UnBooks. The only "policy" on boldfaced captions is that all the articles in an encyclopedia should have baseline similarity of style. Do we really need another rule for this? Again, there are ways for your personal rendition to be as pretty as you want. Here, they are all on blue paper and with no dots on the i's. Spıke Ѧ 13:07 8-Nov-13 Stale VFD stuff Some of those articles are over 14 days (336 hours) old, with hardly any movement. Maybe it's time to {{fix}} tag them if they are going nowhere and make room for newer nominations? If they still haven't improved over the time then we can look at nominating them again later on down the line, but (I feel) VFD needs to remain active to encourage deletion of cruft. • Puppy's talk page • 08:31 08 Nov 2013 - I've asked Simsie to help push Invisia and Tunisia over the edge. Romartus hasn't visited VFD in a little while either. A {{Fix}} of an article whose owner has left the building is merely a license for me to huff it in 30 days, though Frosty usually beats me to this task. Most of these articles have had no support expressed for them. I'll close out those that got significant support now. Spıke Ѧ 21:06 8-Nov-13 Clean-up of help pages Great job with HTBFANJS! I know that you know it, but I still want to say it. I now managed to read it till the end. Separately - if you think that it is the right a idea, would you, please, unprotect the Beginner's Guide to Being an Uncyclopedian? I think I know how to make it more convincing and helpful. Anton (talk) 21:04, November 8, 2013 (UTC) - Wow! Thank you. Simsie post-edited. I'm not done yet; see her talk page. Spıke Ѧ 21:06 8-Nov-13 - The document you link to above is just the outline! You know how to make it a more convincing and helpful outline??? Spıke Ѧ 21:10 8-Nov-13 - You could always {{subst:Uncyclopedia:Beginner's Guide/Overview}} into your user space if you want to work on it, and then move it all over in one hit. That's the way I tend to work with protected titles. - Side note: Anton, is your tag button broken? • Puppy's talk page • 09:27 08 Nov 2013 - An outline should be helpful! No, but seriously, our Beginner's Guide is not really a guide but multiple illustrated redirects, but which is still protected. Making that outline convincing would be helpful, I think. And making it helpful would be convincing. Maybe making it a true guide would be of more use to the users (well, I really got influenced by HTBFANJS)?Anton (talk) 21:32, November 8, 2013 (UTC) - What's a tag button? Anton, go wild. Also, please make the page stop experimenting with inventing new font sizes. Spıke Ѧ 21:37 8-Nov-13 - Puppy, this wouldn't have anything to do with the change you asked me to make to the MediaWiki JavaScript exactly "several days" ago, would it? Spıke Ѧ 21:39 8-Nov-13 - I do not really care, as I liked using it to place pages to VFD and now I should not anyway, as it is out-of-date. Anton (talk) 21:45, November 8, 2013 (UTC) - There is an extremely remote, far left field, teensy tiny possibility that I completely ballsed it up. I think I requested you to change some of the code with line breaks where there shouldn't have been line breaks. (If not that, then I don't know what went wrong. Needs more fixing anyway, but just wanted to be sure.) • Puppy's talk page • 09:50 08 Nov 2013 Section 4 could be redundant. A little further up we go though write consistently, and the non-NPOV doesn't add to comedic style, or avoid stupid, so probably has no point here. ( Would Does fit in at UN:NOT though.) • Puppy's talk page • 04:59 09 Nov 2013 - As Romartus's original point was that this needs to get easier to slog through, I'll take a look at this option later today. Spıke Ѧ 11:13 9-Nov-13 - The heading "We are not Wikipedia" did sound as though it should move to UN:NOT. But on further review, it is simply a throw-away heading. The paragraph it began actually related more closely to the other paragraph I threw in there than it did to its own (now-deleted) heading. Everything in Section 4 does relate to writing good comedy and probably should stay there. What is missing is our emerging doctrine about making an article start well (no quotecruft, no alias-cruft, give the reader a hint of the pleasures about to arrive, etc.). Spıke Ѧ 23:32 9-Nov-13 1990s Hey SPIKE, could you possible help me in expanding the 1990s article? "90s kids" are perhaps the most despised, arrogant, and annoying people on the Internet (next to Sonicfans, Directioners, and weeaboos, of course), and I think this article is rife with opportunity to make fun of them.--EpicWinner (talk) 18:23, November 9, 2013 (UTC) - What I did was move all the funny stuff out of Category:1990s and create this article, in place of a redirect to the category. - Someone looking for a mainspace article generally doesn't want to see a category but some mainspace article, if only a disambiguation. - Someone looking at a category is using it seriously to search for stuff. Mainspace (and the other projects) is where we make people laugh. - Now that the funny stuff has gone where it should live, am not sure I can help you with the content. Nineties kids were annoying after The Me Generation were annoying, which was after the Free Sex Generation were annoying, and preceded the people who are annoying me now. That is, I don't remember a thing. Spıke Ѧ 23:28 9-Nov-13 Faces I see you've sunk the VFH nom of the faces in the cloud. May I have one question. In the past you talked about not looking at pictures from your computer. Did you look at the photograph in question, look for the faces, as well as the other stuff described? The page and its subpage are hinged on the picture, and if you didn't see it, I submit this to the judges. If you did look at it, never mind. Aleister 10-11 - In fact, I did. At one point I followed the article's hint on where to look. Your question proves my point that the article exists to make demands of the reader rather than bring fun to him. Not on our main page! Spıke Ѧ 11:34 10-Nov-13 - Alright, thanks. I had to check after remembering you sometimes don't look at pics. And these don't seem like very demanding "demands", just a curious and, ah, fun, thing to do, and it would reward lots of people when they find some faces. JFK is very obvious, as is Bevel, and King if you can see him peeking out from behind some white clouds. If you have time maybe go back and spend some time with the page, and if a face or two comes into focus, maybe you can reconsider your vote. Proof is in the pudding, in this case, in the pic. And I'm still working on that baseball page, and put in more stuff about Babe Ruth. George to his friends. Aleister awhile later EvilCecil4th userspace clean-up request Hey there. It's been quite a while since I've been on Uncyclopedia (took the email notifying of the deletion of that dumbass drug-induced article I wrote when I was 15 to get me back here :P), but if you don't mind; there's two drafts I was working on (not exactly Uncyclopedia related) that are of the same drunk-shooping nature and after taking a look at them they don't seem to going anywhere anyways. I kinda want to clean my main profile here up so I'd be grateful if you could delete these two sub pages for me: User:EvilCecil4th/School_Fighter User:EvilCecil4th/Abuse Of The Lulz (if there's a way to do this kind of thing yourself, sorry. My wiki skills are pretty rusty). Thanks for your time. --EvilCecil4th (talk) 14:20, November 10, 2013 (UTC) - These two are gone. Take any others to QVFD. I've nominated Lads on VFD; not one of yours, but more of the same; if you agree, I welcome your vote (if not, I welcome your editing of it). Spıke Ѧ 14:26 10-Nov-13 Oh yeah, completely forgot about QVFD! Thanks for your help. --EvilCecil4th (talk) 14:30, November 10, 2013 (UTC) Policy on original video Speaking of uTube....what are your thoughts on original video content (like Unfomercial:Playstation)? • Puppy's talk page • 05:05 11 Nov 2013 - My thoughts on unoriginal video content, and on original video content posted on other sites (that is, on using Uncyclopedia to advertise one's other work) are clear. I envisage Uncyclopedia as a place for "original comedy writing" (that is, more than a group television watch), but Wikia techies have made a push to acquire videos and to get them to download faster, so it is comfortable with hosting videos. An Unfomercial in the form of a video would be funny, and the video format would correctly imitate the real-world thing being ridiculed. A video in an "encyclopedia article" doesn't look like an encyclopedia article, but it's only if the motive is to catalog funny things done elsewhere that I'd try to fight it in the style guide. Spıke Ѧ 10:21 11-Nov-13 - I don't think video snippets are always outside of an encyclopaedic tone though. There's a few WP articles with video in them. Although I agree that adding one of the several hundred Wilford Brimley videos here wouldn't help. - I'm probably harping on about this as it has seemed to me to be a logical extension of Uncyc - having video content - but one that has always been contentious. But it's the same as uploading images from demotivational posters, xkcd, et al. I have no concern about linking or uploading original content, but youtube vids are a minefield. Have a look at what Love was prior to the rewrite, for example. It's a personal bugbear though. • Puppy's talk page • 10:48 11 Nov 2013 - This is a topic I was going to ask about and maybe have a reversal. I missed the change from having youtube vids run on the page and now they are listed as a 'file'. Some pages I've worked on include youtube vids as things to listen to while reading the page, or to contemplate just afterwards while still on the page. In-A-Gadda-Da-Vida is a listening one, as is an unnews about marrying brown rice, and the best one of all, at the bottom of Gildy and my UnPoetia:Well-Oiled Birds. In these pages they are part of the format of the page. It would be nice to have them back, and was this a Wikia decision or an in-house decision? Thanks Aleister 13:34 UTC, 2013 November 11 - If you are in the mood for an epiphany, then stop worrying about what the author is listening to in the background — stop trying to control the reader's mind, as in Faces (see just above) — and simply serve him comedy. PS: It is not 11-11-11 so I gave your post a correct timestamp. Spıke Ѧ 21:05 11-Nov-13 User Opples ond bononas Listen....It's not about gayness and rape. It's actually real funnyness. Listen, this is not from another wiki and i'm not criticizing, but personally this wiki is really unfunny and pretty much it needs a little explicit jokes to make it funny I'm trying to make people laugh. That's what I do. I don't offense or anything. — Opples ond bononas (talk) 00:15, November 12, 2013 (UTC) - Even when you create an imitation {{Construction}} template that calls the reader or the admin an idiot? "Listen." I'm sorry you think this website isn't funny, and I'm sorry you think you are. Perhaps take it elsewhere over the next month. Spıke Ѧ 00:27 12-Nov-13 - Not about gayness, eh? I counted, and the terms "gay" "gayness" or "homo" are used eight times in the article. Seriously, if gayness isn't part of the comedic strategy of this article, that number needs to be cut at least in half, or perhaps replaced with the more formal term "homosexual". Making fun of gays is immature and overused, and has worn out its welcome here, as discussed in HTBFANJS. Likewise, the terms raped, rapes, raping, or incest, are used 9 times. Most people don't think rape jokes are funny, and the few who do usually find offending other people funny. If this is your mindset you might fit in quite well at Encyclopedia Dramatica, where they already happen to have an article written about Hetalia, and shock images and offensive articles you will find plenty of. Calling other editors or admins idiots isn't funny either. It violates Rule 2. -- Simsilikesims(♀GUN) Talk here. 01:29, November 12, 2013 (UTC) - He seems to be trying, to be communicating, and likely will take guidance. Isn't a month's first time ban for someone who both writes and communicates harsh? Mars needs women. Aleister 12-11 - Problem is, there were two offenses. So basically two weeks for the dickish "Constuction" template added to his article, and two weeks for recreating a deleted article that was userspaced. That's not even including the 15 to 30 minutes to read HTBFANJS for failing which, a ban from 2 hours to 1 day is typically given. ---- Simsilikesims(♀GUN) Talk here. 01:53, November 12, 2013 (UTC) - Thank you, Aleister, for your advice. My harshness was based on him dumping Hetalia on us in one gulp, as though sporking it from ED from the beginning, and rebuffing attempts to advise him about this article, including with {{ICU}}. The attitude shown above — This wiki is unfunny and you need me — iced it. Every ban involves a judgement on the future potential of the recipient, and I don't have much doubt about this one, except whether he is one of our past attitude problems under a new name. Spıke Ѧ 01:58 12-Nov-13 - To be fair, he did cross out what he had said about the wiki being unfunny, as if he had second thoughts about that. However, I have been watching him too, and his overall response so far has been trollish. -- Simsilikesims(♀GUN) Talk here. 02:09, November 12, 2013 (UTC) - No, he did not file that comment and strike it out after reconsideration; he filed the comment struck-through in a single edit. (His second edit was to sign the message.) In other words, "Here is what I'm not going to say about your wiki. But oh! I did now, didn't I?" Spıke Ѧ 02:31 12-Nov-13 Introduction joke Thanks for the modification of the introduction and the picture, it's much better this way (I started this article 2 years ago but was too lazy to end it so I published it the way it is even though I had more ideas but no time to implement them). As a French contributor, this is the first time I write an article directly in English, I usually translate articles I originally made in French on Désencyclopédie. This is not a signature - WiiKend Magritte 20:04, November 14, 2013 (UTC) - Thank you! But I couldn't help noticing — The ending needs work too! Also, the article is written more like a comic book than an encyclopedia article. What you have would work better as a pictorial section of examples, after a funny explanation in prose. Romartus is our wizard in the Humanities and might be able to contribute with disastrous speeches throughout history. Spıke Ѧ 20:23 14-Nov-13 USERNAME template abuse I didn't say delete the Username template abuse article. This article is extremely funny, I was asking if the article can be on the category pages that look like the things they're about. —The preceding unsigned comment was added by BetterSkatez2012 (talk • contribs) - I know you didn't say to delete it. The category does fit. If you like it, you had better vote to save it. It doesn't make the reader laugh; it either annoys him or confuses him. Spıke Ѧ 03:50 17-Nov-13 - Or, simply causes the infamous Facepalm. -- Simsilikesims(♀GUN) Talk here. 03:54, November 17, 2013 (UTC) - No, in cases where the page works, I think it produces annoyance (maybe worry) rather than exasperation. Spıke Ѧ 04:07 17-Nov-13 A gift I know how much you love tildes, as if they were your own children of different mothers. Here is one: ~ And here are three more... ~ ~ ~ --Definitely not Al 14:05, November 17, 2013 (UTC)
http://uncyclopedia.wikia.com/wiki/User_talk:SPIKE?diff=5750411&oldid=5750267
CC-MAIN-2016-18
refinedweb
15,481
70.13
Why such strange behaviour while outputting the difference in sizes of two queues. When i am storing them in a diff variable its showing right answer, while just outputting the difference gives wrong answer. #include<bits/stdc++.h> using namespace std; int main() { priority_queue<int , vector<int> , greater<int> > pmin; priority_queue<int , vector<int> >pmax; pmin.push(5); pmin.push(9); pmin.push(10); pmax.push(1); cout << pmax.size() - pmin.size() << endl; int diff = pmax.size() - pmin.size(); cout << diff <<endl; return 0 ; } **** TO DV : Since downvotes doesn't affects me, but I think this is a very good question whom most of have no idea about the flaw in this. So it would be good if some good answers known to other people.
http://codeforces.com/blog/entry/67644
CC-MAIN-2019-26
refinedweb
125
73.27
.76 Saturday August 20, 2011, 06:30:00 PM -0700 *. 0.75 Saturday August 13, 2011, 05:30:00 PM -0700 * MANIFEST Somehow, t/13_no_deep_recursion.t never got added to MANIFEST. * lib/RPC/XML/Parser/XMLLibXML.pm RT #65154: Fixed a cut/paste error in an error message. * lib/RPC/XML/Client.pm * t/51_client_with_host_header.t (added) RT #68792: Merge pull request #2 from dragon3/master (). Allow setting of "Host" header, and test suite for it. * MANIFEST * t/51_client_with_host_header.t Added new test suite to MANIFEST, fixed spelling. Also added "plan tests" line to the test suite. * lib/RPC/XML/Parser/XMLLibXML.pm * t/20_xml_parser.t * t/21_xml_libxml.t * t/41_server_hang.t Merge pull request #3 from yannk/master (). Expat parser subclass is protected against ext ent attack, libxml isn't. * t/41_server_hang.t Undo a change to this suite from yannk's pull. * etc/make_method * More perlcritic-driven clean-up. This is mostly POD sections, but also includes heavy re-working of etc/make_method and parts of lib/RPC/XML.pm. * lib/RPC/XML/Parser/XMLLibXML.pm * t/21_xml_libxml.t Fixed external entity handling on MacOS. Also made small change to the test suite to be cleaner. * lib/RPC/XML/Parser/XMLLibXML.pm * lib/RPC/XML/Parser/XMLParser.pm Took out warnings on external entities blocking. Now it blocks silently. Also cleaned up some docs. * t/15_serialize.t Additions to increase code coverage in XML.pm. * lib/RPC/XML.pm Turns out this wasn't exporting RPC_I8. * * xt/02_pod_coverage.t Made 5.8.8 the new minimum-required perl. Also dropped the utf8_downgrade hack, which affected an xt test. * lib/RPC/XML/Client.pm Improved arguments-checking in send_request. * lib/RPC/XML/Client.pm * lib/RPC/XML/Parser/XMLLibXML.pm * lib/RPC/XML/Parser/XMLParser.pm * lib/RPC/XML/Server.pm Fixed error-cases in usage of File::Temp->new(). File::Temp::new croaks on errors, doesn't return undef like I thought. * MANIFEST * lib/RPC/XML/Function.pm (deleted) * lib/RPC/XML/Method.pm (deleted) * lib/RPC/XML/Procedure.pm Roll Method.pm and Function.pm into Procedure.pm. Remove Method.pm and Function.pm from distro. * lib/RPC/XML/Parser/XMLLibXML.pm Fixed regexp for methodName validation. * t/10_data.t * t/11_base64_fh.t * t/12_nil.t * t/15_serialize.t * t/20_xml_parser.t * t/21_xml_libxml.t * t/25_parser_negative.t (added) * t/29_parserfactory.t * t/30_method.t * t/40_server.t * t/40_server_xmllibxml.t * t/50_client.t * t/BadParserClass.pm (added) * t/meth_good_1.xpl * t/namespace3.xpl * t/svsm_text.b64 (added) * t/util.pl First round of Devel::Cover-inspired improvements. These are the changes to the test suites to increase coverage of the code. * lib/RPC/XML.pm * lib/RPC/XML/Procedure.pm * lib/RPC/XML/Server.pm Fixes and such from Devel::Cover analysis. * lib/RPC/XML/Procedure.pm * lib/RPC/XML/Server.pm * t/30_method.t * t/meth_good_1.xpl * t/meth_good_2.xpl (added) * t/meth_good_3.xpl (added) Fixes for file-based method loading/reloading. New tests in the suite, and re-working of the ugliest hacky part of this package. * lib/RPC/XML/Procedure.pm * lib/RPC/XML/Server.pm * t/30_method.t * t/meth_good_3.xpl RPC::XML::Procedure test-coverage improvement. Also removed some unneeded code. * lib/RPC/XML/Procedure.pm * lib/RPC/XML/Server.pm * t/30_method.t * t/40_server.t Last round of RPC::XML::Procedure test coverage. This is mostly in t/40_server.t, though some bugs were found and addressed in the modules and in t/30_method.t. * lib/Apache/RPC/Server.pm * lib/Apache/RPC/Status.pm * lib/RPC/XML.pm * lib/RPC/XML/Client.pm * lib/RPC/XML/Parser.pm * lib/RPC/XML/Parser/XMLLibXML.pm * lib/RPC/XML/Parser/XMLParser.pm * lib/RPC/XML/ParserFactory.pm * lib/RPC/XML/Procedure.pm * lib/RPC/XML/Server.pm Documentation clean-up and update. * lib/Apache/RPC/Server.pm * lib/Apache/RPC/Status.pm * lib/RPC/XML/Client.pm * lib/RPC/XML/Parser/XMLLibXML.pm * lib/RPC/XML/Parser/XMLParser.pm * lib/RPC/XML/Procedure.pm * lib/RPC/XML/Server.pm Changes from new Perl::Critic::Bangs policies. * xt/01_pod.t * xt/02_pod_coverage.t * xt/03_meta.t * xt/04_minimumversion.t * xt/05_critic.t Adjustments to reflect moving from t to xt. Also made changes to xt/02_pod_coverage.t to reflect changes to modules. * lib/RPC/XML/Client.pm Removed some error checks that can never fail. * lib/RPC/XML/Server.pm * t/40_server.t Code-coverage-driven changes and added tests. * etc/make_method Fixes from new Perl::Critic::Bangs policies. * lib/RPC/XML/Server.pm Removed usage of AutoLoader completely. * lib/RPC/XML/Server.pm * t/40_server.t * xt/02_pod_coverage.t Removed some dead code and better did the aliases. This required a change in t/40_server.t for a private sub that no longer exists. Also updated xt/02_pod_coverage.t for private subs that have no pod. * lib/Apache/RPC/Server.pm RT #67694: Fix a potential infinite-loop condition. * MANIFEST * t/01_pod.t (deleted) * t/02_pod_coverage.t (deleted) * t/03_meta.t (deleted) * t/04_minimumversion.t (deleted) * t/05_critic.t (deleted) * xt/01_pod.t (added) * xt/02_pod_coverage.t (added) * xt/03_meta.t (added) * xt/04_minimumversion.t (added) * xt/05_critic.t (added) Lingering problem from RT ticket #30354, RPC::XML::Parser did not get the change committed that included parser-level support for <i8>. Also added tests for parsing RPC::XML::request objects and all the data-type objects to the parser test suite (had they been there before, I would have caught this myself). 0.63 Testers-service reports showed that the new i8 type was not auto-boxing correctly on true 64-bit machines. Turns out I had bogus values for the maximums and minimums, not just for 8-byte ints but also for plain 4-byte ones as well. 0.61 Fix for RT ticket #36078, fix the URL testing on the server object to be less strict. Instead of only allowing "localhost", now also allows "localhost.localdomain" and does a look-up of "localhost" for the 127.* IP address and permits that as well. In essence, this extends and supercedes the second change listed above after more invariant cases were discovered. * lib/RPC/XML.pm, Related to the main change of RT ticket #30849, fixes potential problem in the creation of temporary file names if a test script is run directly from the "t" directory. While at it, added a line with the Subversion "Id" keyword and set the "svn:keywords" property on all test scripts. The code-fix is based on suggestions from Jörg Meltzer <joerg@joergmeltzer.de>. * lib/RPC/XML/Client.pm, Per RT ticket #30042, made a do-nothing branch in RPC::XML::smart_encode actually die with an error when a reference-type is passed in that cannot be converted. Added two tests to cover this, and took the opportunity to convert 10_data.t to Test::More. * t/40_server.t, Applied a patch from Masatake Daimon (大門正岳) to improve the performance of the parser by reducing the (vast) number of string-concat operations. During this change, re-wrote the parser tests to use Test::More and have better diagnostics. * lib/RPC/XML/Server.pm, Per RT ticket #31818, fix to the XML serialization of double values to conform to the XML-RPC spec, as it does not allow for exponential notation. This also required changes to the tests, as values were no longer being auto-truncated at 5 decimal places. Also finished cleaning up the t/10_data.t test suite with diagnostic messages on the tests that had not previously gotten them. * lib/RPC/XML.pm, revision 339 * t/20_parser.t, revision 339 In response to concerns raised by a report of parsing problems, added XML entity encoding for ' and " (' and ") to the base RPC::XML module, and added a test to the parser suite to make sure it is correctly turning all core XML entities back into characters during the parsing process. * lib/Apache/RPC/Server.pm, revision 341 * lib/RPC/XML/Server.pm, revision 341 * t/40_server.t, revision 341 RT ticket #34557: Provide access to client-side connection info to methods called on the server, by placing the data from get_peeraddr() (as abstracted through existing methods in HTTP::Daemon::ClientConn and Apache::Connection) into localized keys on the server object, as is already done with the method_name and signature pseudo-keys. Tests added to 40_server.t and docs updated. * etc/make_method, Applied patches from Stephen Veiss to fix a small bug in the encoding method of RPC::XML::string. Trying to encode the literal string "0" would result in a null string. The patches provided the fix and a specific test-case for the related suite. * lib/RPC/XML/Procedure.pm, Based on a report from Brian Phillips, made adjustments in the smart_encode helper-routine to deal with blessed references. Anything that is derived from HASH or ARRAY is encoded as a struct or array, respectively. Anything derived from SCALAR is dereferenced and encoded as per usual. Carried this over to the class constructors, with special attention to the RPC::XML::simple_type class. Added tests to the suite for all of this, as well. * lib/Apache/RPC/status.base, The "system.status" method (both the general one and the one that is specific to Apache) now recognizes an optional boolean parameter that can keep the status call from counting against the "total_requests" struct value. This is to allow external monitors (status, health, etc.) to use that call without running up the value of that field needlessly. 0.56 Th Traced a bug that was causing test failures in 50_client.t to a bug in version 5.800 of the LWP package. Now, Makefile.PL explicitly requires 5.801 or higher, and the test suite skips the two tests that are broken by it, in cases where the system is still at 5.800 or older. * lib/RPC/XML/Client.pm, Applied a patch from Tim Peoples that does three things: the 301 error code in RPC::XML::Procedure::call now includes signature info when a signature mismatch occurs. RPC::XML::smart_encode turns undef values into zero-length RPC::XML::string objects. Lastly, the RPC::XML::string::as_string method turns undef into null values as well. * lib/RPC/XML.pm, revision 1.28 * t/10_data.t, revision 1.6 Small change to the XML character-escaping in RPC::XML::string's as_string method, so that a lookup-table is used. The same table is now used to escape keys in structs, as well. Added tests to cover this. This was suggested by Johnathan Kupferer. * Applied a patch from Chris Darroch to allow better handling of arguments in RPC::XML::Server::server_loop. While the HTTP::Daemon portion was fine with collapsing the arg list into a hash, the Net::Server portion actually has documented behavior when it sees the same argument more than once, and collapsing to a hash caused these extra arguments to be lost. 0.53 T Calls to the encode_base64 routine from MIME::Base64 now pass a zero- length second argument, to suppress newlines between Base64 lines when stringifying the RPC::XML::base64 objects. This is to accomodate a broken Java XML-RPC package. * Extended the RPC::XML::base64 class to allow for and handle being given a filehandle object instead of straight data. The object is kept as an open filehandle, and the buffer position is always noted and reset when operated on, so that other parts of the process using the handle don't get surprised. Added tests in t/11_base64_fh.t to exercise.t Modified RPC::XML::Parser to accept arguments to new() that instruct it to spool Base64 data to a filehandle, using the new capabilities of the base64 class described previously. Added tests to t/20_parser.t and support for the parameters to the constructors of the client and base server classes. Documented all around. * All the internal use of object attributes in RPC::XML::Client now use accessors instead of the hash keys directly, to make it easier to sub-class the package. The same was done in RPC::XML::Server and to some degree in Apache::RPC::Server. The server classes are more likely to have problems, though. * lib/RPC/XML/Client.pm * lib/RPC/XML/Parser.pm * lib/RPC/XML/Server.pm The parsing of incoming data in the client and both server classes is now done to a streaming XML parser, eliminating the need for the full message to ever be in memory at once. Likewise, the client and server classes have new attributes and accessor methods to allow them to spool outgoing messages to files if the messages threaten to be too large to keep in memory (this is best used when dealing with a lot of Base64 data that is being dealt with directly on disk as well). 0.46.pm Fixed a bad bug with the newly-added compression support in Apache::RPC::Server::handler. Because $self was defined earlier, strict failed to point out that my object in that scope was called $srv, rather than $self. And $self->compress didn't work, amazingly enough. Found and reported by Scott Fagg. * Changed the test in Apache::RPC::Server of the Content-type header so that it accepts a header that contains "text/xml", as opposed to only accepting a header that exactly equalled that string. Allows for things like SOAP::Lite's XMLRPC::Lite which include a charset in the header. *. 0 Implemented two fixes sent in by Marc Liyanage: a fix for setting the Content-Length headers on messages that takes the length in bytes rather than characters; the second is a fix around the compression support that makes certain an undef isn't evaluated against the regex. *.pm Fixed a bug in RPC::XML::Procedure found by a user (a former co-worker from my Denver days, coincidentally enough) that would trigger when auto_methods was set to 1 on a server object, but the request had no matching file anywhere in the search path. 0.36 T August 21, 2011, 12:31:39 PM -0700 # Using changelog2x/0.11, App::Changelog2x/0.11, XML::LibXML/1.84, # XML::LibXSLT/1.70, $
https://metacpan.org/changes/release/RJRAY/RPC-XML-0.76
CC-MAIN-2015-48
refinedweb
2,374
59.4
Printable View There is only one sure-fire way to eliminate bugs from a program. That involves hard work. To give a precise description of requirements (and the problem to be addressed or the task that the software is to achieve). To understand what each code construct (whether it is a declaration/definition, an expression, or even a preprocessor directive) you use contributes to meeting those requirements. To define test cases that will fail unless the software meets the requirements, or - if the test cases are passed - can be used to provide a body of defendable evidence about how well the requirements are met. Instead, what we have is a lot of rules of thumb, often based on a false premise that a few small simple tricks can eliminate bugs from a program. The thing is, if you dig into the places where many of those rules originate (journal articles, teacher guides, coding standards) their primary goal is to be easy to use, teach (it is easier to get a novice to add a "= 0" than it is to get them to think about how a variable contributes to the code working as required) and (in a lot of cases) be automatically enforced (eg by some software tool, such as a compiler, that enforces coding standards). The secondary goal (at best) of these rules is that they can, in some hopefully realistic scenarios, be demonstrated to reduce incidence of bugs in software. In practice, some authors do express a wish that, by encouraging programmers to follow their chosen rules of thumb or coding guidelines, that they will encourage programmers to think more carefully about their code, and thereby reduce bug counts. In most cases, those authors wish in vain - most programmers learn to follow the "rules of thumb" without understanding, as a habit rather than something they think about, and therefore eventually run into the inconvenient pitfalls. Code: #include <stdio.h> int main() { float p,n,dm,q; float sum_p,sum_n,sum_dm,sum_q; float total_sum; float dollars; printf("\nEnter the number of pennies:\n"); scanf("%f",&p); sum_p=p*1.00; printf("\nEnter the number of nickels:\n"); scanf("%f",&n); sum_n=n*5.00; printf("\nEnter the number of dimes:\n"); scanf("%f",&dm); sum_dm=dm*10.00; printf("\nEnter the number of quarters:\n"); scanf("%f",&q); sum_q=q*25.00; total_sum=(sum_p)+(sum_n)+(sum_dm)+(sum_q); dollars=total_sum/100.00; printf("\nYou have $%.2f dollars\n",dollars); return(0); } > Thank you very much! Yes, you got a spoon-fed answer from some overly enthusiastic newbie poster. The real question is, have you learnt anything from this exercise (except perhaps that there's a sucker to answer your question somewhere). Will you feel as confident with next weeks assignment (which will be harder)?.Quote: Originally Posted by c99tutorial But hey go ahead and be hostile. Thus I don't think Salem had you in mind when he talks about an "overly enthusiastic newbie poster" Bye, Andreas I liked your post, Tomwa - LTA's also. You gave plenty of info, and LTA's code was so clear that there was no need to explain anything further. The forum does have a problem, that if the OP posts no code, we quickly become a "please give me the codez" gathering spot, for lazy students. Clearly, that was NOT the case here. The OP's code was "close", imo. Well done, both of you.
https://cboard.cprogramming.com/c-programming/153560-i-cant-figure-out-why-my-simple-program-not-working-2-print.html
CC-MAIN-2017-26
refinedweb
572
61.16
Hi. I'm creating an interface using the Tkinter library, but I seem to be having some issues with placing 3 buttons BELOW 3 buttons which are on top. All buttons should be inside the second LabelFrame. I've looked all over and I can't seem to figure out why the other buttons are not placing themselves below the top 3. I've tried various options using the pack method such as side = BOTTOM or anchor = SW, but they don't seem to be helping at all. from Tkinter import * class GUI(): def __init__(self, r): self.r = r self.i = StringVar() self.f = Frame(self.r) self.f.pack(fill = BOTH) self.g = LabelFrame(self.f, text = 'Groupbox 1', height = 90, width = 150, font = 'Lucida 8') self.g.pack_propagate(0) self.g.pack(side = LEFT, pady = 10, padx = 10) self.id = Entry(self.g, justify = CENTER, textvariable = self.i, font = 'Lucida 8') self.id.pack(pady = 22) self.opt = LabelFrame(self.f, text = 'Groupbox 2', height = 90, width = 200, font = 'Lucida 8') self.opt.pack_propagate(0) self.opt.pack(side = LEFT) self.button1 = Button(self.opt, text = 'Button 1', height = 1, width = 7, font = 'Lucida 8') self.button1.pack(side = LEFT, anchor = N, pady = 5, padx = 4) self.button2 = Button(self.opt, text = 'Button 2', height = 1, width = 7, font = 'Lucida 8') self.button2.pack(side = LEFT, anchor = N, pady = 5, padx = 4) self.button3 = Button(self.opt, text = 'Button 3', height = 1, width = 7, font = 'Lucida 8') self.button3.pack(side = LEFT, anchor = N, pady = 5, padx = 4) self.button4 = Button(self.opt, text = 'Button 4', height = 1, width = 5, font = 'Lucida 8') self.button4.pack(side = BOTTOM, anchor = W) # Buttons 5 & 6 will be added, but I'd first like to rectify button 4's issue. t = Tk() t.title('test') #t.configure(bg = 'white') t.geometry('400x120') t.pack_propagate(0) GUI(t) t.mainloop() As stated, I've changed the options in the button4's pack method, but it doesn't seem to want to place itself directly beneath the other buttons. It's placing itself to the right. I'd like to stay away from the grid manager, as I've already gotten most of what I need in the right place. I'd appreciate any help in this situation, and hopefully it wasn't a simple mistake on my part.
https://www.daniweb.com/software-development/python/threads/397470/tkinter-button-placement-problem
CC-MAIN-2015-22
refinedweb
397
60.82
0x00240001: Windows Update Agent was stopped successfully.[1] 0x00240002: Windows Update Agent updated itself.[1] 0x00240003: Operation completed successfully but there were errors applying the updates.[1] 0x00240004: A callback was marked to be disconnected later because the request to disconnect the operation came while a callback was executing.[1] 0x00240005: The system must be restarted to complete installation of the update.[1] 0x00240006: The update to be installed is already installed on the system.[1] 0x00240007: The update to be removed is not installed on the system.[1] 0x00240008: The update to be downloaded has already been downloaded.[1] 0x00240009: The operation completed successfully, but some updates were skipped because the system is running on batteries.[1] 0x00242015: The installation operation for the update is still in progress.[1] 0x00245001: No operation was required by the server-initiated healing server response.[1] 0x00246001: The update to be downloaded is already being downloaded.[1] 0x80240001: Windows Update Agent was unable to provide the service.[1] 0x80240002: The maximum capacity of the service was exceeded.[1] 0x80240003: An ID cannot be found.[1] 0x80240004: The object could not be initialized.[1] 0x80240005: The update handler requested a byte range overlapping a previously requested range.[1] 0x80240006: The requested number of byte ranges exceeds the maximum number (2^31 - 1).[1] 0x80240007: The index to a collection was invalid.[1] 0x80240008: The key for the item queried could not be found.[1] 0x80240009: Another conflicting operation was in progress. Some operations such as installation cannot be performed twice simultaneously.[1] 0x8024000A: Cancellation of the operation was not allowed.[1] 0x8024000B: Operation was cancelled.[1] 0x8024000C: No operation was required.[1] 0x8024000D: Windows Update Agent could not find required information in the update's XML data.[1] 0x8024000E: Windows Update Agent found invalid information in the update's XML data.[1] 0x8024000F: Circular update relationships were detected in the metadata.[1] 0x80240010: Update relationships too deep to evaluate were evaluated.[1] 0x80240011: An invalid update relationship was detected.[1] 0x80240012: An invalid registry value was read.[1] 0x80240013: Operation tried to add a duplicate item to a list.[1] 0x80240014: Updates requested for install are not installable by caller.[1] 0x80240016: Operation tried to install while another installation was in progress or the system was pending a mandatory restart.[1] 0x80240017: Operation was not performed because there are no applicable updates.[1] 0x80240018: Operation failed because a required user token is missing.[1] 0x80240019: An exclusive update cannot be installed with other updates at the same time.[1] 0x8024001A: A policy value was not set.[1] 0x8024001B: The operation could not be performed because the Windows Update Agent is self-updating.[1] 0x8024001D: An update contains invalid metadata.[1] 0x8024001E: Operation did not complete because the service or system was being shut down.[1] 0x8024001F: Operation did not complete because the network connection was unavailable.[1] 0x80240020: Operation did not complete because there is no logged-on interactive user.[1] 0x80240021: Operation did not complete because it timed out.[1] 0x80240022: Operation failed for all the updates.[1] 0x80240023: The license terms for all updates were declined.[1] 0x80240024: There are no updates.[1] 0x80240025: Group Policy settings prevented access to Windows Update.[1] 0x80240026: The type of update is invalid.[1] 0x80240027: The URL exceeded the maximum length.[1] 0x80240028: The update could not be uninstalled because the request did not originate from a WSUS server.[1] 0x80240029: Search may have missed some updates before there is an unlicensed application on the system.[1] 0x8024002A: A component required to detect applicable updates was missing.[1] 0x8024002B: An operation did not complete because it requires a newer version of server.[1] 0x8024002C: A delta-compressed update could not be installed because it required the source.[1] 0x8024002D: A full-file update could not be installed because it required the source.[1] 0x8024002E: Access to an unmanaged server is not allowed.[1] 0x8024002F: Operation did not complete because the DisableWindowsUpdateAccess policy was set.[1] 0x80240030: The format of the proxy list was invalid.[1] 0x80240031: The file is in the wrong format.[1] 0x80240032: The search criteria string was invalid.[1] 0x80240033: License terms could not be downloaded.[1] 0x80240034: Update failed to download.[1] 0x80240035: The update was not processed.[1] 0x80240036: The object's current state did not allow the operation.[1] 0x80240037: The functionality for the operation is not supported.[1] 0x80240038: The downloaded file has an unexpected content type.[1] 0x80240039: Agent is asked by server to resync too many times.[1] 0x80240040: WUA API method does not run on Server Core installation.[1] 0x80240041: Service is not available while sysprep is running.[1] 0x80240042: The update service is no longer registered with AU.[1] 0x80240043: There is no support for WUA UI.[1] 0x80240044: Only administrators can perform this operation on per-machine updates.[1] 0x80240045: A search was attempted with a scope that is not currently supported for this type of search.[1] 0x80240046: The URL does not point to a file.[1] 0x80240047: The operation requested is not supported.[1] 0x80240048: The featured update notification info returned by the server is invalid.[1] 0x80240049: The data is out of range.[1] 0x8024004A: Windows Update agent operations are not available while OS setup is running.[1] 0x8024004B: An orphaned downloadjob was found with no active callers.[1] 0x8024004C: An update could not be installed because the system battery power level is too low.[1] 0x8024004D: The downloaded infrastructure file is incorrectly formatted.[1] 0x8024004E: The infrastructure file must be downloaded using strong SSL.[1] 0x8024004F: A discovery call contributed to a non-zero operation count at idle timer shutdown.[1] 0x80240050: A search call contributed to a non-zero operation count at idle timer shutdown.[1] 0x80240051: A download call contributed to a non-zero operation count at idle timer shutdown.[1] 0x80240052: An install call contributed to a non-zero operation count at idle timer shutdown.[1] 0x80240053: An unspecified call contributed to a non-zero operation count at idle timer shutdown.[1] 0x80240054: An interactive user cancelled this operation, which was started from the Windows Update Agent UI.[1] 0x80240055: Automatic Updates cancelled this operation because it applies to an update that is no longer applicable to this computer.[1] 0x80240056: This version or edition of the operating system doesn't support the needed functionality.[1] 0x80240057: The requested update download or install handler, or update applicability expression evaluator, is not provided by this Agent plugin.[1] 0x80240058: The requested serialization version is not supported.[1] 0x80240059: The current network cost does not meet the conditions set by the network cost policy.[1] 0x8024005A: The call is cancelled because it applies to an update that is hidden (no longer applicable to this computer).[1] 0x8024005B: The call is cancelled because it applies to an update that is invalid (no longer applicable to this computer).[1] 0x8024005C: The specified volume id is invalid.[1] 0x8024005D: The specified volume id is unrecognized by the system.[1] 0x8024005E: The installation extended error code is not specified.[1] 0x8024005F: The installation extended error code is set to general fail.[1] 0x80240FFF: An operation failed due to reasons not covered by another error code.[1] 0x80241001: Search may have missed some updates because the Windows Installer is less than version 3.1.[1] 0x80241002: Search may have missed some updates because the Windows Installer is not configured.[1] 0x80241003: Search may have missed some updates because policy has disabled Windows Installer patching.[1] 0x80241004: An update could not be applied because the application is installed per-user.[1] 0x80241005: Search may have missed some updates because the Windows Installer is less than version 3.1.[1] 0x80241FFF: Search may have missed some updates because there was a failure of the Windows Installer.[1] 0x80244000: WU_E_PT_SOAPCLIENT_* error codes map to the SOAPCLIENT_ERROR enum of the ATL Server Library.[1] 0x80244001: Same as SOAPCLIENT_INITIALIZE_ERROR - initialization of the SOAP client failed, possibly because of an MSXML installation failure.[1] 0x80244002: Same as SOAPCLIENT_OUTOFMEMORY - SOAP client failed because it ran out of memory.[1] 0x80244003: Same as SOAPCLIENT_GENERATE_ERROR - SOAP client failed to generate the request.[1] 0x80244004: Same as SOAPCLIENT_CONNECT_ERROR - SOAP client failed to connect to the server.[1] 0x80244005: Same as SOAPCLIENT_SEND_ERROR - SOAP client failed to send a message for reasons of WU_E_WINHTTP_* error codes.[1] 0x80244006: Same as SOAPCLIENT_SERVER_ERROR - SOAP client failed because there was a server error.[1] 0x80244007: Same as SOAPCLIENT_SOAPFAULT - SOAP client failed because there was a SOAP fault for reasons of WU_E_PT_SOAP_* error codes.[1] 0x80244008: Same as SOAPCLIENT_PARSEFAULT_ERROR - SOAP client failed to parse a SOAP fault.[1] 0x80244009: Same as SOAPCLIENT_READ_ERROR - SOAP client failed while reading the response from the server.[1] 0x8024400A: Same as SOAPCLIENT_PARSE_ERROR - SOAP client failed to parse the response from the server.[1] 0x8024400B: Same as SOAP_E_VERSION_MISMATCH - SOAP client found an unrecognizable namespace for the SOAP envelope.[1] 0x8024400C: Same as SOAP_E_MUST_UNDERSTAND - SOAP client was unable to understand a header.[1] 0x8024400D: Same as SOAP_E_CLIENT - SOAP client found the message was malformed; fix before resending.[1] 0x8024400E: Same as SOAP_E_SERVER - The SOAP message could not be processed due to a server error; resend later.[1] 0x8024400F: There was an unspecified Windows Management Instrumentation (WMI) error.[1] 0x80244010: The number of round trips to the server exceeded the maximum limit.[1] 0x80244011: WUServer policy value is missing in the registry.[1] 0x80244012: Initialization failed because the object was already initialized.[1] 0x80244013: The computer name could not be determined.[1] 0x80244015: The reply from the server indicates that the server was changed or the cookie was invalid; refresh the state of the internal cache and retry.[1] 0x80244016: Same as HTTP status 400 - the server could not process the request due to invalid syntax.[1] 0x80244017: Same as HTTP status 401 - the requested resource requires user authentication.[1] 0x80244018: Same as HTTP status 403 - server understood the request, but declined to fulfill it.[1] 0x80244019: Same as HTTP status 404 - the server cannot find the requested URI (Uniform Resource Identifier).[1] 0x8024401A: Same as HTTP status 405 - the HTTP method is not allowed.[1] 0x8024401B: Same as HTTP status 407 - proxy authentication is required.[1] 0x8024401C: Same as HTTP status 408 - the server timed out waiting for the request.[1] 0x8024401D: Same as HTTP status 409 - the request was not completed due to a conflict with the current state of the resource.[1] 0x8024401E: Same as HTTP status 410 - requested resource is no longer available at the server.[1] 0x8024401F: Same as HTTP status 500 - an error internal to the server prevented fulfilling the request.[1] 0x80244020: Same as HTTP status 500 - server does not support the functionality required to fulfill the request.[1] 0x80244021: Same as HTTP status 502 - the server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.[1] 0x80244022: Same as HTTP status 503 - the service is temporarily overloaded.[1] 0x80244023: Same as HTTP status 503 - the request was timed out waiting for a gateway.[1] 0x80244024: Same as HTTP status 505 - the server does not support the HTTP protocol version used for the request.[1] 0x80244025: Operation failed due to a changed file location; refresh internal state and resend.[1] 0x80244026: Operation failed because Windows Update Agent does not support registration with a non-WSUS server.[1] 0x80244027: The server returned an empty authentication information list.[1] 0x80244028: Windows Update Agent was unable to create any valid authentication cookies.[1] 0x80244029: A configuration property value was wrong.[1] 0x8024402A: A configuration property value was missing.[1] 0x8024402B: The HTTP request could not be completed and the reason did not correspond to any of the WU_E_PT_HTTP_* error codes.[1] 0x8024402C: Same as ERROR_WINHTTP_NAME_NOT_RESOLVED - the proxy server or target server name cannot be resolved.[1] 0x8024502D: Windows Update Agent failed to download a redirector cabinet file with a new redirectorId value from the server during the recovery.[1] 0x8024502E: A redirector recovery action did not complete because the server is managed.[1] 0x8024402F: External cab file processing completed with some errors.[1] 0x80244030: The external cab processor initialization did not complete.[1] 0x80244031: The format of a metadata file was invalid.[1] 0x80244032: External cab processor found invalid metadata.[1] 0x80244033: The file digest could not be extracted from an external cab file.[1] 0x80244034: An external cab file could not be decompressed.[1] 0x80244035: External cab processor was unable to get file locations.[1] 0x80240436: The server does not support category-specific search; Full catalog search has to be issued instead.[1] 0x80240437: There was a problem authorizing with the service.[1] 0x80240438: There is no route or network connectivity to the endpoint.[1] 0x80240439: The data received does not meet the data contract expectations.[1] 0x8024043A: The url is invalid.[1] 0x8024043B: Unable to load NWS runtime.[1] 0x8024043C: The proxy auth scheme is not supported.[1] 0x8024043D: The requested service property is not available.[1] 0x8024043E: The endpoint provider plugin requires online refresh.[1] 0x8024043F: A URL for the requested service endpoint is not available.[1] 0x80240440: The connection to the service endpoint died.[1] 0x80240441: The operation is invalid because protocol talker is in an inappropriate state.[1] 0x80240442: The object is in a faulted state due to a previous error.[1] 0x80240443: The operation would lead to numeric overflow.[1] 0x80240444: The operation was aborted.[1] 0x80240445: The operation was abandoned.[1] 0x80240446: A quota was exceeded.[1] 0x80240447: The information was not available in the specified language.[1] 0x80240448: The address is already being used.[1] 0x80240449: The address is not valid for this context.[1] 0x8024044A: Unrecognized error occurred in the Windows Web Services framework.[1] 0x8024044B: A security operation failed in the Windows Web Services framework.[1] 0x80244FFF: A communication error not covered by another WU_E_PT_* error code.[1] 0x80245001: The redirector XML document could not be loaded into the DOM class.[1] 0x80245002: The redirector XML document is missing some required information.[1] 0x80245003: The redirectorId in the downloaded redirector cab is less than in the cached cab.[1] 0x80245004: The service ID is not supported in the service environment.[1] 0x80245005: The response from the redirector server had an unsupported content type.[1] 0x80245006: The response from the redirector server had an error status or was invalid.[1] 0x80245008: The maximum number of name value pairs was exceeded by the attribute provider.[1] 0x80245009: The name received from the attribute provider was invalid.[1] 0x8024500A: The value received from the attribute provider was invalid.[1] 0x8024500B: There was an error in connecting to or parsing the response from the Service Locator Service redirector server.[1] 0x8024500C: Connections to the redirector server are disallowed by managed policy.[1] 0x8024500D: The redirector would go online but is disallowed by caller configuration.[1] 0x802450FF: The redirector failed for reasons not covered by another WU_E_REDIRECTOR_* error code.[1] 0x80245101: Verification of the servicing engine package failed.[1] 0x80245102: Verification of a servicing package failed.[1] 0x80245103: Verification of the staged engine failed.[1] 0x80245104: Verification of a staged payload failed.[1] 0x80245105: An internal error occurred where the servicing action was not found.[1] 0x80245106: There was a parse error in the service environment response.[1] 0x80245107: A downloaded file failed an integrity check.[1] 0x80245108: No engine was provided by the server-initiated healing server response.[1] 0x802451FF: There was a failure for reasons not covered by another WU_E_SIH_* error code.[1] 0x8024C001: A driver was skipped.[1] 0x8024C002: A property for the driver could not be found. It may not conform with required specifications.[1] 0x8024C003: The registry type read for the driver does not match the expected type.[1] 0x8024C004: The driver update is missing metadata.[1] 0x8024C005: The driver update is missing a required attribute.[1] 0x8024C006: Driver synchronization failed.[1] 0x8024C007: Information required for the synchronization of applicable printers is missing.[1] 0x8024C008: After installing a driver update, the updated device has reported a problem.[1] 0x8024CFFF: A driver error not covered by another WU_E_DRV_* code.[1] 0x80248000: An operation failed because Windows Update Agent is shutting down.[1] 0x80248001: An operation failed because the data store was in use.[1] 0x80248002: The current and expected states of the data store do not match.[1] 0x80248003: The data store is missing a table.[1] 0x80248004: The data store contains a table with unexpected columns.[1] 0x80248005: A table could not be opened because the table is not in the data store.[1] 0x80248006: The current and expected versions of the data store do not match.[1] 0x80248007: The information requested is not in the data store.[1] 0x80248008: The data store is missing required information or has a NULL in a table column that requires a non-null value.[1] 0x80248009: The data store is missing required information or has a reference to missing license terms, file, localized property or linked row.[1] 0x8024800A: The update was not processed because its update handler could not be recognized.[1] 0x8024800B: The update was not deleted because it is still referenced by one or more services.[1] 0x8024800C: The data store section could not be locked within the allotted time.[1] 0x8024800D: The category was not added because it contains no parent categories and is not a top-level category itself.[1] 0x8024800E: The row was not added because an existing row has the same primary key.[1] 0x8024800F: The data store could not be initialized because it was locked by another process.[1] 0x80248010: The data store is not allowed to be registered with COM in the current process.[1] 0x80248011: Could not create a data store object in another process.[1] 0x80248013: The server sent the same update to the client with two different revision IDs.[1] 0x80248014: An operation did not complete because the service is not in the data store.[1] 0x80248015: An operation did not complete because the registration of the service has expired.[1] 0x80248016: A request to hide an update was declined because it is a mandatory update or because it was deployed with a deadline.[1] 0x80248017: A table was not closed because it is not associated with the session.[1] 0x80248018: A table was not closed because it is not associated with the session.[1] 0x80248019: A request to remove the Windows Update service or to unregister it with Automatic Updates was declined because it is a built-in service and/or Automatic Updates cannot fall back to another service.[1] 0x8024801A: A request was declined because the operation is not allowed.[1] 0x8024801B: The schema of the current data store and the schema of a table in a backup XML document do not match.[1] 0x8024801C: The data store requires a session reset; release the session and retry with a new session.[1] 0x8024801D: A data store operation did not complete because it was requested with an impersonated identity.[1] 0x80248FFF: A data store error not covered by another WU_E_DS_* code.[1] 0x80249001: Parsing of the rule file failed.[1] 0x80249002: Failed to get the requested inventory type from the server.[1] 0x80249003: Failed to upload inventory result to the server.[1] 0x80249004: There was an inventory error not covered by another error code.[1] 0x80249005: A WMI error occurred when enumerating the instances for a particular class.[1] 0x8024A000: Automatic Updates was unable to service incoming requests.[1] 0x8024A002: The old version of the Automatic Updates client has stopped because the WSUS server has been upgraded.[1] 0x8024A003: The old version of the Automatic Updates client was disabled.[1] 0x8024A004: Automatic Updates was unable to process incoming requests because it was paused.[1] 0x8024A005: No unmanaged service is registered with AU.[1] 0x8024A006: The default service registered with AU changed during the search.[1] 0x8024A007: A reboot is in progress.[1] 0x8024A008: Automatic Updates can't process incoming requests while Windows Welcome is running.[1] 0x8024AFFF: An Automatic Updates error not covered by another WU_E_AU * code.[1] 0x80242000: A request for a remote update handler could not be completed because no remote process is available.[1] 0x80242001: A request for a remote update handler could not be completed because the handler is local only.[1] 0x80242002: A request for an update handler could not be completed because the handler could not be recognized.[1] 0x80242003: A remote update handler could not be created because one already exists.[1] 0x80242004: A request for the handler to install (uninstall) an update could not be completed because the update does not support install (uninstall).[1] 0x80242005: An operation did not complete because the wrong handler was specified.[1] 0x80242006: A handler operation could not be completed because the update contains invalid metadata.[1] 0x80242007: An operation could not be completed because the installer exceeded the time limit.[1] 0x80242008: An operation being done by the update handler was cancelled.[1] 0x80242009: An operation could not be completed because the handler-specific metadata is invalid.[1] 0x8024200A: A request to the handler to install an update could not be completed because the update requires user input.[1] 0x8024200B: The installer failed to install (uninstall) one or more updates.[1] 0x8024200C: The update handler should download self-contained content rather than delta-compressed content for the update.[1] 0x8024200D: The update handler did not install the update because it needs to be downloaded again.[1] 0x8024200E: The update handler failed to send notification of the status of the install (uninstall) operation.[1] 0x8024200F: The file names contained in the update metadata and in the update package are inconsistent.[1] 0x80242010: The update handler failed to fall back to the self-contained content.[1] 0x80242011: The update handler has exceeded the maximum number of download requests.[1] 0x80242012: The update handler has received an unexpected response from CBS.[1] 0x80242013: The update metadata contains an invalid CBS package identifier.[1] 0x80242014: The post-reboot operation for the update is still in progress.[1] 0x80242015: The result of the post-reboot operation for the update could not be determined.[1] 0x80242016: The state of the update after its post-reboot operation has completed is unexpected.[1] 0x80242017: The OS servicing stack must be updated before this update is downloaded or installed.[1] 0x80242018: A callback installer called back with an error.[1] 0x80242019: The custom installer signature did not match the signature required by the update.[1] 0x8024201A: The installer does not support the installation configuration.[1] 0x8024201B: The targeted session for install is invalid.[1] 0x8024201C: The handler failed to decrypt the update files.[1] 0x8024201D: The update handler is disabled until the system reboots.[1] 0x8024201E: The AppX infrastructure is not present on the system.[1] 0x8024201F: The update cannot be committed because it has not been previously installed or staged.[1] 0x80242020: The specified volume is not a valid AppX package volume.[1] 0x80242021: The configured default storage volume is unavailable.[1] 0x80242022: The volume on which the application is installed is unavailable.[1] 0x80242023: The specified package family is not present on the system.[1] 0x80242024: Unable to find a package volume marked as system.[1] 0x80242FFF: An update handler error not covered by another WU_E_UH_* code.[1] 0x80246001: A download manager operation could not be completed because the requested file does not have a URL.[1] 0x80246002: A download manager operation could not be completed because the file digest was not recognized.[1] 0x80246003: A download manager operation could not be completed because the file metadata requested an unrecognized hash algorithm.[1] 0x80246004: An operation could not be completed because a download request is required from the download handler.[1] 0x80246005: A download manager operation could not be completed because the network connection was unavailable.[1] 0x80246006: A download manager operation could not be completed because the version of Background Intelligent Transfer Service (BITS) is incompatible.[1] 0x80246007: The update has not been downloaded.[1] 0x80246008: A download manager operation failed because the download manager was unable to connect the Background Intelligent Transfer Service (BITS).[1] 0x80246009: A download manager operation failed because there was an unspecified Background Intelligent Transfer Service (BITS) transfer error.[1] 0x8024600A: A download must be restarted because the location of the source of the download has changed.[1] 0x8024600B: A download must be restarted because the update content changed in a new revision.[1] 0x8024600C: A download failed because the current network limits downloads by update size for the update service.[1] 0x8024600E: The download failed because the client was denied authorization to download the content.[1] 0x8024600F: The download failed because the user token associated with the BITS job no longer exists.[1] 0x80246010: The sandbox directory for the downloaded update was not found.[1] 0x80246011: The downloaded update has an unknown file path.[1] 0x80246012: One or more of the files for the downloaded update is missing.[1] 0x80246013: An attempt was made to access a downloaded update that has already been removed.[1] 0x80246014: Windows Update couldn't find a needed portion of a downloaded update's file.[1] 0x80246016: The download failed because the client was denied authorization to download the content due to no user logged on.[1] 0x80246017: The download failed because the local user was denied authorization to download the content.[1] 0x80246018: The download failed because the domain user was denied authorization to download the content.[1] 0x80246019: The download failed because the MSA account associated with the user was denied authorization to download the content.[1] 0x8024601A: The download will be continued by falling back to BITS to download the content.[1] 0x8024601B: Another caller has requested download to a different volume.[1] 0x8024601C: The hash of the update's sandbox does not match the expected value.[1] 0x80246FFF: There was a download manager error not covered by another WU_E_DM_* error code.[1] 0x8024D001: Windows Update Agent could not be updated because an INF file contains invalid information.[1] 0x8024D002: Windows Update Agent could not be updated because the wuident.cab file contains invalid information.[1] 0x8024D003: Windows Update Agent could not be updated because of an internal error that caused setup initialization to be performed twice.[1] 0x8024D004: Windows Update Agent could not be updated because setup initialization never completed successfully.[1] 0x8024D005: Windows Update Agent could not be updated because the versions specified in the INF do not match the actual source file versions.[1] 0x8024D006: Windows Update Agent could not be updated because a WUA file on the target system is newer than the corresponding source file.[1] 0x8024D007: Windows Update Agent could not be updated because regsvr32.exe returned an error.[1] 0x8024D008: An update to the Windows Update Agent was skipped because previous attempts to update have failed.[1] 0x8024D009: An update to the Windows Update Agent was skipped due to a directive in the wuident.cab file.[1] 0x8024D00A: Windows Update Agent could not be updated because the current system configuration is not supported.[1] 0x8024D00B: Windows Update Agent could not be updated because the system is configured to block the update.[1] 0x8024D00C: Windows Update Agent could not be updated because a restart of the system is required.[1] 0x8024D00D: Windows Update Agent setup is already running.[1] 0x8024D00E: Windows Update Agent setup package requires a reboot to complete installation.[1] 0x8024D00F: Windows Update Agent could not be updated because the setup handler failed during execution.[1] 0x8024D010: Windows Update Agent could not be updated because the registry contains invalid information.[1] 0x8024D011: Windows Update Agent must be updated before search can continue.[1] 0x8024D012: Windows Update Agent must be updated before search can continue. An administrator is required to perform the operation.[1] 0x8024D013: Windows Update Agent could not be updated because the server does not contain update information for this version.[1] 0x8024D014: Windows Update Agent is successfully updated, but a reboot is required to complete the setup.[1] 0x8024D015: Windows Update Agent is successfully updated, but a reboot is required to complete the setup.[1] 0x8024D016: Windows Update Agent could not be updated because of an unknown error.[1] 0x8024DFFF: Windows Update Agent could not be updated because of an error not covered by another WU_E_SETUP_* error code.[1] 0x8024E001: An expression evaluator operation could not be completed because an expression was unrecognized.[1] 0x8024E002: An expression evaluator operation could not be completed because an expression was invalid.[1] 0x8024E003: An expression evaluator operation could not be completed because an expression contains an incorrect number of metadata nodes.[1] 0x8024E004: An expression evaluator operation could not be completed because the version of the serialized expression data is invalid.[1] 0x8024E005: The expression evaluator could not be initialized.[1] 0x8024E006: An expression evaluator operation could not be completed because there was an invalid attribute.[1] 0x8024E007: An expression evaluator operation could not be completed because the cluster state of the computer could not be determined.[1] 0x8024EFFF: There was an expression evaluator error not covered by another WU_E_EE_* error code.[1] 0x80243001: The results of download and installation could not be read from the registry due to an unrecognized data format version.[1] 0x80243002: The results of download and installation could not be read from the registry due to an invalid data format.[1] 0x80243003: The results of download and installation are not available; the operation may have failed to start.[1] 0x80243004: A failure occurred when trying to create an icon in the taskbar notification area.[1] 0x80243FFD: Unable to show UI when in non-UI mode; WU client UI modules may not be installed.[1] 0x80243FFE: Unsupported version of WU client UI exported functions.[1] 0x80243FFF: There was a user interface error not covered by another WU_E_AUCLIENT_* error code.[1] 0x8024F001: The event cache file was defective.[1] 0x8024F002: The XML in the event namespace descriptor could not be parsed.[1] 0x8024F003: The XML in the event namespace descriptor could not be parsed.[1] 0x8024F004: The server rejected an event because the server was too busy.[1] 0x8024F005: The specified callback cookie is not found.[1] 0x8024FFFF: There was a reporter error not covered by another error code.[1] 0x80247001: An operation could not be completed because the scan package was invalid.[1] 0x80247002: An operation could not be completed because the scan package requires a greater version of the Windows Update Agent.[1] 0x80247003: An invalid event payload was specified.[1] 0x80247004: The size of the event payload submitted is invalid.[1] 0x80247005: The service is not registered.[1] 0x80247FFF: Search using the scan package failed.[1] 0x8024B001: The task is currently in progress.[1] 0x8024B002: The operation cannot be completed since the task status is currently disabled.[1] 0x8024B003: The operation cannot be completed since the task is not yet started.[1] 0x8024B004: The task was stopped and needs to be run again to complete.[1] 0x8024B005: Cannot cancel a non-scheduled install.[1] 0x8024B101: Hardware capability meta data was not found after a sync with the service.[1] 0x8024B102: Hardware capability meta data was malformed and/or failed to parse.[1]
https://windows-hexerror.linestarve.com/browse/headers/wuerror.h
CC-MAIN-2020-10
refinedweb
5,209
58.79
In codelab MDC-101, you used two Material Components to build a login page: text fields and buttons with ink ripples. Now let's expand upon this foundation by adding navigation, structure, and data. In this codelab, you'll build a home screen for an app called Shrine, an e-commerce app that sells clothing and home goods. It will contain: To start developing mobile apps with Flutter you need: Flutter's IDE tools are available for Android Studio, IntelliJ IDEA Community (free), and IntelliJ IDEA Ultimate. To build and run Flutter apps on iOS: To build and run Flutter apps on Android: Get detailed Flutter setup information Before proceeding with this codelab, make sure that your SDK is in the right state. If the flutter SDK was installed previously, then use flutter upgrade to ensure that the SDK is at the latest state. flutter upgrade Running flutter upgrade will automatically run flutter doctor. If this a fresh flutter install and no upgrade was necessary, then run flutter doctor manually. See that all the check marks are showing; this will download any missing SDK files you need and ensure that your codelab machine is set up correctly for Flutter development. flutter doctor If you completed MDC-101, your code should be prepared for this codelab. Skip to step: Add a top app bar. The starter app is located in the material-components-flutter-codelabs-102-starter_and_101-complete/mdc_100_series directory. To clone this codelab from GitHub, run the following commands: git clone cd material-components-flutter-codelabs git checkout 102-starter_and_101-complete The following instructions assume you're using Android Studio (IntelliJ). The following instructions assume you're testing on an Android emulator or device but you can also test on an iOS Simulator or device if you have Xcode installed. Success! You should see the Shrine login page from the MDC-101 codelab in the simulator or emulator. Now that the login screen looks good, let's populate the app with some products. Right now, if you click the "Next" button you will be able to see the home screen that says "You did it!". That's great! But now our user has no actions to take, or any sense of where they are in the app. To help with that, it's time to add navigation. Material Design offers navigation patterns that ensure a high degree of usability. One of the most visible components is a top app bar. To provide navigation and give users quick access to other actions, let's add a top app bar. In home.dart, add an AppBar to the Scaffold: return Scaffold( // TODO: Add app bar (102) appBar: AppBar( // TODO: Add buttons and title (102) ), Adding the AppBar to the Scaffold's appBar: field, gives us perfect layout for free, keeping the AppBar at the top of the page and the body underneath. Save the project. When the Shrine app updates, click Next to see the home screen. AppBar looks great but it needs a title. In home.dart, add a title to the AppBar: // TODO: Add app bar (102) appBar: AppBar( // TODO: Add buttons and title (102) title: Text('SHRINE'), // TODO: Add trailing buttons (102) Save the project. Many app bars have a button next to the title. Let's add a menu icon in our app. While still in home.dart, set an IconButton for the AppBar's leading: field. (Put it before the title: field to mimic the leading-to-trailing order): return Scaffold( appBar: AppBar( // TODO: Add buttons and title (102) leading: IconButton( icon: Icon( Icons.menu, semanticLabel: 'menu', ), onPressed: () { print('Menu button'); }, ), Save the project. The menu icon (also known as the "hamburger") shows up right where you'd expect it. You can also add buttons to the trailing side of the title. In Flutter, these are called "actions". There's room for two more IconButtons. Add them to the AppBar instance after the title: // TODO: Add trailing buttons (102) actions: <Widget>[ IconButton( icon: Icon( Icons.search, semanticLabel: 'search', ), onPressed: () { print('Search button'); }, ), IconButton( icon: Icon( Icons.tune, semanticLabel: 'filter', ), onPressed: () { print('Filter button'); }, ), ], Save your project. Your home screen should look like this: Now the app has a leading button, a title, and two actions on the right side. The app bar also displays elevation using a subtle shadow that shows it's on a different layer than the content. Now that our app has some structure, let's organize the content by placing it into cards. Let's start by adding one card underneath the top app bar. The Card widget alone doesn't have enough information to lay itself out where we could see it, so we'll want to encapsulate it in a GridView widget. Replace the Center in the body of the Scaffold with a GridView: // TODO: Add a grid view (102) body: GridView.count( crossAxisCount: 2, padding: EdgeInsets.all(16.0), childAspectRatio: 8.0 / 9.0, // TODO: Build a grid of cards (102) children: <Widget>[Card()], ), Let's unpack that code. The GridView invokes the count() constructor since the number of items it displays is countable and not infinite. But it needs some information to define its layout. The crossAxisCount: specifies how many items across. We want 2 columns. The padding: field provides space on all 4 sides of the GridView. Of course you can't see the padding on the trailing or bottom sides because there's no GridView children next to them yet. The childAspectRatio: field identifies the size of the items based on an aspect ratio (width over height). By default, GridView makes tiles that are all the same size. Adding that all together, the GridView calculates each child's width as follows: ([width of the entire grid] - [left padding] - [right padding]) / number of columns. Using the values we have: ([width of the entire grid] - 16 - 16) / 2. The height is calculated from the width, by applying the aspect ratio:: ([width of the entire grid] - 16 - 16) / 2 * 9 / 8. We flipped 8 and 9 because we are starting with the width and calculating the height and not the other way around. We have one card but it's empty. Let's add child widgets to our card. Cards should have regions for an image, a title, and secondary text. Update the children of the GridView: // TODO: Build a grid of cards (102) children: <Widget>['), ], ), ), ], ), ) ], This code adds a Column widget used to lay out the child widgets vertically. The crossAxisAlignment: field specifies CrossAxisAlignment.start, which means "align the text to the leading edge." The AspectRatio widget decides what shape the image takes no matter what kind of image is supplied. The Padding brings the text in from the side a little. The two Text widgets are stacked vertically with 8 points of empty space between them (SizedBox). We make another Column to house them inside the Padding. Save your project: In this preview, you can see the card is inset from the edge, with rounded corners, and a shadow (that expresses the card's elevation). The entire shape is called the "container" in Material. (Not to be confused with the actual widget class called Container.) Cards are usually shown in a collection with other cards. Let's lay them out as a collection in a grid. Whenever multiple cards are present in a screen, they are grouped together into one or more collections. Cards in a collection are coplanar, meaning cards share the same resting elevation as one another (unless the cards are picked up or dragged, but we won't be doing that here). Right now our Card is constructed inline of the children: field of the GridView. That's a lot of nested code that can be hard to read. Let's extract it into a function that can generate as many empty cards as we want, and returns a list of Cards. Make a new private function above the build() function (remember that functions starting with an underscore are private API): // TODO: Make a collection of cards (102) List<Card> _buildGridCards(int count) { List<Card> cards = List.generate( count, (int index) =>'), ], ), ), ], ), ), ); return cards; } Assign the generated cards to GridView's children field. Remember to replace everything contained in the GridView with this new code: // TODO: Add a grid view (102) body: GridView.count( crossAxisCount: 2, padding: EdgeInsets.all(16.0), childAspectRatio: 8.0 / 9.0, children: _buildGridCards(10) // Replace ), Save the project: The cards are there, but they don't show anything yet. Now's the time to add some product data. The app has some products with images, names, and prices. Let's add that to the widgets we have in the card already Then, in home.dart, import a new package and some files we supplied for a data model: import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'model/products_repository.dart'; import 'model/product.dart'; Finally, change _buildGridCards() to fetch the product info, and use that data in the cards: // TODO: Make a collection of cards (102) // Replace this entire method List<Card> _buildGridCards(BuildContext context) { List<Product> products = ProductsRepository.loadProducts(Category.all); if (products == null || products.isEmpty) { return const <Card>[]; } final ThemeData theme = Theme.of(context); final NumberFormat formatter = NumberFormat.simpleCurrency( locale: Localizations.localeOf(context).toString()); return products.map((product) { return Card( clipBehavior: Clip.antiAlias, // TODO: Adjust card heights (103) child: Column( // TODO: Center items on the card (103) crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ AspectRatio( aspectRatio: 18 / 11, child: Image.asset( product.assetName, package: product.assetPackage, // TODO: Adjust the box size (102) ), ), Expanded( child: Padding( padding: EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 8.0), child: Column( // TODO: Align labels to the bottom and center (103) crossAxisAlignment: CrossAxisAlignment.start, // TODO: Change innermost Column (103) children: <Widget>[ // TODO: Handle overflowing labels (103) Text( product.name, style: theme.textTheme.title, maxLines: 1, ), SizedBox(height: 8.0), Text( formatter.format(product.price), style: theme.textTheme.body2, ), ], ), ), ), ], ), ); }).toList(); } NOTE: Won't compile and run yet. We have one more change. Also, change the build() function to pass the BuildContext to _buildGridCards() before you try to compile: // TODO: Add a grid view (102) body: GridView.count( crossAxisCount: 2, padding: EdgeInsets.all(16.0), childAspectRatio: 8.0 / 9.0, children: _buildGridCards(context) // Changed code ), You may notice we don't add any vertical space between the cards. That's because they have, by default, 4 points of padding on their top and bottom. Save your project: The product data shows up, but the images have extra space around them. The images are drawn with a BoxFit of .scaleDown by default (in this case). Let's change that to .fitWidth so they zoom in a little and remove the extra whitespace. Change the image's fit: field: // TODO: Adjust the box size (102) fit: BoxFit.fitWidth, Our products are now showing up in the app perfectly! Our app has a basic flow that takes the user from the login screen to a home screen, where products can be viewed. In just a few lines of code, we added a top app bar (with a title and three buttons) and cards (to present our app's content). Our home screen is now simple and functional, with a basic structure and actionable content. With the top app bar, card, text field, and button, we've now used four core components from the MDC-Flutter library! You can explore even more components by visiting the Flutter Widgets Catalog. While it's fully functioning, our app doesn't yet express any particular brand or point of view. In MDC-103: Material Design Theming with Color, Shape, Elevation and Type, we'll customize the style of these components to express a vibrant, modern brand.
https://codelabs.developers.google.com/codelabs/mdc-102-flutter/
CC-MAIN-2019-43
refinedweb
1,954
66.03
#include <UT_TimeGate.h> Used to reduce the frequency of checks gated by a time out (in milliseconds at resolution of ~100ms). Note that the frequency is not guaranteed, esp. if you try to call tryAcquire() from multiple threads on the same UT_TimeGate object. Definition at line 27 of file UT_TimeGate.h. Definition at line 30 of file UT_TimeGate.h. Resets the gate so that canAcquire()/tryAcquire() will return false until at least TIMEOUT_MS has elapsed. Definition at line 57 of file UT_TimeGate.h. Return true if at least TIMEOUT_MS has elapsed from the last call to acquire(), without actually acquiring. Definition at line 49 of file UT_TimeGate.h. Return true if at least TIMEOUT_MS has elapsed from the last time this method returned true. Resolution is ~100ms. Definition at line 38 of file UT_TimeGate.h.
http://www.sidefx.com/docs/hdk/class_u_t___time_gate.html
CC-MAIN-2018-17
refinedweb
135
69.07
Investors eyeing a purchase of PBF Energy Inc (Symbol: PBF) shares, but tentative about paying the going market price of $24.65/share, might benefit from considering selling puts among the alternative strategies at their disposal. One interesting put contract in particular, is the September put at the $19 strike, which has a bid at the time of this writing of $1.20. Collecting that bid as the premium represents a 6.3% return against the $19 commitment, or a 9.8% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). Selling a put does not give an investor access to PBF's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. And the person on the other side of the contract would only benefit from exercising at the $19 strike if doing so produced a better outcome than selling at the going market price. ( Do options carry counterparty risk? This and six other common options myths debunked ). So unless PBF Energy Inc sees its shares decline 22.9% and the contract is exercised (resulting in a cost basis of $17.80 per share before broker commissions, subtracting the $1.20 from $19), the only upside to the put seller is from collecting that premium for the 9.8% annualized rate of return. Worth considering, is that the annualized 9.8% figure actually exceeds the 4.9% annualized dividend paid by PBF Energy Inc by 4.9%, based on the current share price of $24.65. And yet, if an investor was to buy the stock at the going market price in order to collect the dividend, there is greater downside because the stock would have to lose 22.89% to reach the $19 strike price. Always important when discussing dividends is the fact that, in general, dividend amounts are not always predictable and tend to follow the ups and downs of profitability at each company. In the case of PBF Energy Inc, looking at the dividend history chart for PBF below can help in judging whether the most recent dividend is likely to continue, and in turn whether it is a reasonable expectation to expect a 4.9% annualized dividend yield. Below is a chart showing the trailing twelve month trading history for PBF Energy Inc, and highlighting in green where the $19 strike is located relative to that history: The chart above, and the stock's historical volatility, can be a helpful guide in combination with fundamental analysis to judge whether selling the September put at the $19 strike for the 9.8% annualized rate of return represents good reward for the risks. We calculate the trailing twelve month volatility for PBF Energy Inc (considering the last 252 trading day closing values as well as today's price of $24.65) to be 50%. For other put options contract ideas at the various different available expirations, visit the PBF Stock Options page of StockOptionsChannel.com. Top YieldBoost Puts.
https://www.nasdaq.com/articles/commit-purchase-pbf-energy-19-earn-98-annualized-using-options-2017-01-24
CC-MAIN-2021-17
refinedweb
509
63.39
blockhash Blockhash perceptual image hash algorithm This package is not currently in any snapshots. If you're interested in using it, we recommend adding it to Stackage Nightly. Doing so will make builds more reliable, and allow stackage.org to host generated Haddocks. blockhash This is a perceptual image hash calculation tool based on algorithm descibed in Block Mean Value Based Image Perceptual Hashing by Bian Yang, Fan Gu and Xiamu Niu. Visit the website for further information. Program Usage: blockhash [-q|--quick] [-b|--bits ARG] filenames blockhash Available options: -h,--help Show this help text -q,--quick Use quick hashing method -b,--bits ARG Create hash of size N^2 bits. Library The example code below uses JuicyPixels to load images and prints the hash to stdout. import qualified Codec.Picture as P import Data.Blockhash import qualified Data.Vector.Generic as VG import qualified Data.Vector.Unboxed as V printHash :: FilePath -> IO () printHash :: filename = do res <- P.readImage filename case res of Left err -> putStrLn ("Fail to read: " ++ filename) Right dynamicImage -> do let rgbaImage = P.convertRGBA8 dynamicImage pixels = VG.convert (P.imageData rgbaImage) image = Image { imagePixels = pixels , imageWidth = P.imageWidth rgbaImage , imageHeight = P.imageHeight rgbaImage } hash = blockhash image 16 Precise putStrLn (show hash) Depends on 8 packages:
https://www.stackage.org/package/blockhash
CC-MAIN-2018-05
refinedweb
209
52.36
Console Cat - Privacy-friendly CLI telemetry in less than five minutes - Interview with Matt Evenson Perhaps the most significant challenge of CSS is that all rules exist within global scope, meaning that two classes with the same name will collide. The limitation is inherent to the CSS specification, but projects have workarounds for the issue. CSS Modules introduces local scope for every module by making every class declared within unique by including a hash in their name that is globally unique to the module. Webpack's css-loader supports CSS Modules. You can enable it through a loader definition as above while enabling the support: { use: { loader: "css-loader", options: { modules: true, }, }, }, After this change, your class definitions remain local to the files. In case you want global class definitions, you need to wrap them within :global(.redButton) { ... } kind of declarations. In this case, the import statement gives you the local classes you can then bind to elements. Assume you had CSS as below: app/main.css body { background: cornsilk; } .redButton { background: red; } You could then bind the resulting class to a component: app/component.js import styles from "./main.css"; ... // Attach the generated class name element.className = styles.redButton; body remains as a global declaration still. It's that redButton that makes the difference. You can build component-specific styles that don't leak elsewhere this way. CSS Modules allows composition to make it easier to work with your styles and you can also combine it with other loaders as long as you apply them before css-loader. CSS Modules behavior can be modified as discussed in the official documentation. You have control over the names it generates for instance. eslint-plugin-css-modules is handy for tracking CSS Modules related problems. If you are using CSS Modules in your project, you should process standard CSS through a separate loader definition without the modules option of css-loader enabled. Otherwise, all classes will be scoped to their module. In the case of third-party libraries, this is almost certainly not what you want. You can solve the problem by processing third-party CSS differently through an include definition against node_modules. Alternately, you could use a file extension ( .mcss) to tell files using CSS Modules apart from the rest and then manage this situation in a loader test. CSS Modules solve the scoping problem of CSS by defaulting to local scope per file. You can still have global styling, but it requires additional effort. Webpack can be set up to support CSS Modules easily as seen above. This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack.
https://survivejs.com/webpack/appendices/css-modules/
CC-MAIN-2022-40
refinedweb
463
57.47
adc woes I'm trying to measure the voltage of a 16v DC supply by applying it to an analog pin via a 100k/4k7 voltage divider. My multimeter shows the pin sitting at exactly 721mV. But when I run import time, machine adc=machine.ADC() for i in range(9): val=adc.channel(pin='P20'); v=val.voltage(); print(v, ' ', end='') I'm seeing 10mV of variation 693 691 701 692 702 701 691 700 701 > Averaging import time, machine for i in range(10): Vav=0 adc=machine.ADC() for i in range(10): val=adc.channel(pin='P20'); v=val.voltage(); Vav+=v print(Vav/10, ' ', end='') helps 694.1 696.2 695.7 694.6 693.5 695.4 695.5 692.6 694.6 694.4 > but still 3.5mV (0.5%) variation. I really need 3 significant figures for this, what am I missing? @kjm So you are averaging over 1000 values. You can also use a low pass filter, which is a little bit simpler See also the lessons and analysis by Bernd Boser: and especially which shows a noise of about 25 LSB. So your averaging of 1024 values (25*25=625) matches that. B.t.w: good ADCs have a noise <= 1 LSB. I couldn't get any improvement with a 100nF ceramic across the 4k7 but did better with brutish code import time, machine adc=machine.ADC() for i in range(8): Vav2=0 for i in range(128): Vav1=0 for i in range(128): val=adc.channel(pin='P20'); v=val.value(); Vav1+=v av=Vav1/128#; print(av, ' ', end='') Vav2+=av x=Vav2/128; print('%.0f' % x, ' ', end='') 2687 2687 2687 2687 2687 2688 2687 2687 > @kjm You miss nothing. The ADC of the ESP32 is bad. It helps a little bit, if you add a low impedance capacitor (e.g. 10 nF Ceramic) with short leads as close as possible to the ADC input you are using. Besides that: If you need low noise, good precision and linearity, use an external ADC. Note: You do not have to re-init the channel in the loop all the time.
https://forum.pycom.io/topic/4121/adc-woes
CC-MAIN-2021-43
refinedweb
362
74.79
PageRouter #include <pagerouter.h> Detailed Description An item managing pages and data of a ColumnView using named routes. Using a PageRouter Applications typically manage their contents via elements called "pages" or "screens." In Kirigami, these are called Pages and are arranged in routes using a PageRouter to manage them. The PageRouter manages a stack of Pages created from a pool of potential PageRoutes . Unlike most traditional stacks, a PageRouter provides functions for random access to its pages with navigateToRoute and routeActive. When your user interface fits the stack paradigm and is likely to use random access navigation, using the PageRouter is appropriate. For simpler navigation, it is more appropriate to avoid the overhead of a PageRouter by using a PageRow instead. Navigation Model A PageRouter draws from a pool of PageRoutes in order to construct its stack. You can push pages onto this stack... ...or pop them off... ...or navigate to an arbitrary collection of pages. Components are able to query the PageRouter about the currently active routes on the stack. This is useful for e.g. a card indicating that the page it takes the user to is currently active. Example - See also - PageRouterAttached - PageRoute Definition at line 333 of file pagerouter.h. Property Documentation How large the cache can be. The combined costs of cached routes will never exceed the cache capacity. Definition at line 378 of file pagerouter.h. The initial route. initialRoute is the page that the PageRouter will push upon creation. Changing it after creation will cause the PageRouter to reset its state. Not providing an initialRoute will result in undefined behavior. Definition at line 357 of file pagerouter.h. The ColumnView being puppeted by the PageRouter. All PageRouters should be created with a ColumnView, and creating one without a ColumnView is undefined behaviour. - Warning - You should not directly interact with a ColumnView being puppeted by a PageRouter. Instead, use a PageRouter's functions to manipulate the ColumnView. Definition at line 371 of file pagerouter.h. Exposes the data of all pages on the stack, preferring pages on the top (e.g. most recently pushed) to pages pushed on the bottom (least recently pushed). Definition at line 392 of file pagerouter.h. How large the preloaded pool can be. The combined costs of preloaded routes will never exceed the pool capacity. Definition at line 385 of file pagerouter.h. The named routes a PageRouter can navigate to. Definition at line 343 of file pagerouter.h. Member Function Documentation Shifts keyboard focus and view to a given index on the PageRouter's stack. - Parameters - Navigating to route by index: Navigating to route by name: Navigating to route by data: Definition at line 323 of file pagerouter.cpp. Returns a QJSValue corresponding to the current pages on the stack. The returned value is in the same form as the input to navigateToRoute. Definition at line 751 of file pagerouter.cpp. Navigate to the given route. Calling navigateToRoute causes the PageRouter to replace currently active pages with the new route. - Parameters - Definition at line 277 of file pagerouter.cpp. Pops the last page on the router. Calling popRoute will result in the last page on the router getting popped. You should not call this function when there is only one page on the router. Definition at line 367 of file pagerouter.cpp. Appends a route to the currently navigated route. Calling pushRoute will append the given route to the currently navigated routes. See navigateToRoute() if you want to replace the items currently on the PageRouter. - Parameters - Definition at line 361 of file pagerouter.cpp. Check whether the current route is on the stack. routeActive will return true if the given route is on the stack. - Parameters - routeActive returns true for partial routes like the following: This only works from the root page, e.g. the following will return false: Definition at line 342 of file pagerouter.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2022 The KDE developers. Generated on Fri Jan 28 2022 22:34:51 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/frameworks/kirigami/html/classPageRouter.html
CC-MAIN-2022-05
refinedweb
695
60.11
AIR 3 ios sound issuessaariko Oct 2, 2011 2:01 PM hey all i am using the AIR 3 sdk overlayed Flash Pro 5.5 and i am having 2 sound issues: first of all, my iPhone 3g's physical mute/silent button does not affect my app, and it should secondly, the app records sound from the microphone when the user presses a button, but on playback (with another button) you can hear that the sound is missing half a second or so from the beginning this does not happen when testing on the desktop any ideas? thanx, Saar 1. Re: AIR 3 ios sound issuesvabhatia Oct 16, 2011 10:16 AM (in response to saariko) First limitation is a known limitation for all sounds being played in iOS platform. We will discussing the second concern in this post by you. I hope that helps you. 2. Re: AIR 3 ios sound issuessaariko Oct 16, 2011 10:18 AM (in response to vabhatia) thanx sorry for the duplication 3. Re: AIR 3 ios sound issuesvabhatia Oct 17, 2011 3:56 AM (in response to saariko) I have some more infor regarding the first issue. Even ipod app doesnot acknowdledge the mute button. This is because the mute switch is meant for the silencing the alarms and ringer tones and not the app music. I hope this tells you why we the mute switch should not silence the app. 4. Re: AIR 3 ios sound issuessaariko Oct 17, 2011 4:19 AM (in response to vabhatia) @Varun Bhatia, that is not correct. as i have mentioned here:, all games (like Angry Birds) follow the mute switch on iOS i think a future sdk should let the developer decide about this through actionscript cheers Saar 5. Re: AIR 3 ios sound issuesvabhatia Oct 17, 2011 4:29 AM (in response to saariko) Actually iOS SDK provides 5 different ways to play media out of which only 2 respect the mute switch. The modes we use in our SDK donot respect the mute switch and there is no way we can enable this too. Angry birds might be using one of the 2 modes that respect the mute switch. iPod app on the other way uses a mode that doesnot respect the mute switch. I hope you understand. 6. Re: AIR 3 ios sound issuessaariko Oct 17, 2011 5:11 AM (in response to vabhatia) every game i have on my iPhone 3gs respects the switch. i don't have an iPod. i understand switching between the 2 options (respecting or ignoring the mute switch) is not and wont be a runtime option. this isn't a huge problem since i have a software mute in my app. also i could use native extentions as mentioned by your co-worker Saumitra Bhave at the same link: thanx again for all the help! Saar 7. Re: AIR 3 ios sound issuesColin Holgate Oct 17, 2011 12:36 PM (in response to saariko) I accidentally did a test of the mute situation, in that I had made an AIR 2.6 and an AIR 3 version of the same app, while checking out some non-sound related things. By chance I played the AIR 3 one while the mute button was in the sound off position, and I still heard the audio, which goes along with what you are saying. When I played the AIR 2.6 version I didn't hear sound until I turned the mute button to the sound on position. So, regardless of why things happen the way they do, AIR 2.6 honored the mute switch, and AIR 3 doesn't. 8. Re: AIR 3 ios sound issuessanika Kulshreshtha Oct 18, 2011 1:57 AM (in response to saariko) @saariko You might want to add a feature request for this over at and. In case you decide to add the request, post back the URL so that others can also vote and comment. Thanks. Sanika 9. Re: AIR 3 ios sound issuessaariko Oct 18, 2011 10:22 AM (in response to saariko) i will add a feature request soon in the meantime, this is a quote from Apple's App Store Review Guidelines "Apps that alter the functions of standard switches, such as the Volume Up/Down and Ring/Silent switches, will be rejected" has anyone been rejected by Apple because of the silent switch's behavior in AIR 3? 10. Re: AIR 3 ios sound issuesColin Holgate Oct 18, 2011 10:26 AM (in response to saariko) AIR not reacting to the mute switch isn't the same as repurposing it. Also, the rules may have changed with iOS 5, because Apple themselves have repurposed the volume up button. 11. Re: AIR 3 ios sound issuesrobobobo76 Nov 22, 2011 5:38 AM (in response to Colin Holgate) Its definatelly a bug. This works 100% using 2.6 or 2.7. However its broken using 3.0. 12. Re: AIR 3 ios sound issuesColin Holgate Nov 22, 2011 5:48 AM (in response to robobobo76) I logged a bug about this and currently it's listed as a known issue, and is deferred. That is, they hopefully realize it's wrong but will fix it at some future date. I don't know when that date will be. 13. Re: AIR 3 ios sound issuesundereyes Nov 22, 2011 5:48 AM (in response to saariko) AIR-3 have disabled it. Now you have to use a Native Extension to see if mute or not, and thus able to control it sounds like they sound and what not. I am using a Native Extension own and works perfectly. 14. Re: AIR 3 ios sound issuesrobobobo76 Nov 22, 2011 6:10 AM (in response to undereyes) Would you be able to post a link to the native extension you are using ? Much apriciated! 15. Re: AIR 3 ios sound issueschris.campbell Nov 22, 2011 5:21 PM (in response to robobobo76) Hi Colin, Do you have a bug number handy? I'll do a bit of research on my side to see if I can find an ETA. Also, if you can spread the bug link around, I'd recommend anyone effected to vote if they feel like it should be fixed. We use these votes to help determine priority. Thanks, Chris 16. Re: AIR 3 ios sound issuesColin Holgate Nov 22, 2011 5:36 PM (in response to chris.campbell) The bug number is 3003849, but I don't think it's somewhere that most people can see. 17. Re: AIR 3 ios sound issueschris.campbell Nov 22, 2011 6:00 PM (in response to Colin Holgate) Ah, I see, it was added through the prerelease database. It might not be a bad idea to create a seperate feature request over at bugbase.adobe.com. We can link them internally and that way others can still vote on it. Chris 18. Re: AIR 3 ios sound issuesColin Holgate Nov 22, 2011 6:12 PM (in response to chris.campbell) Ok, added it there too: 19. Re: AIR 3 ios sound issueschris.campbell Nov 22, 2011 6:18 PM (in response to Colin Holgate) Thanks Colin. Everyone else, I'd like to encourage you to visit Colins bug and vote for this issue if you think it's important for your applications. Please pass this around the community so others are aware of it. Chris 20. Re: AIR 3 ios sound issuesundereyes Nov 23, 2011 12:28 AM (in response to saariko) I voted. Mainwhile when I have some time I upload my Native Extension for this issue. 21. Re: AIR 3 ios sound issuessaariko Nov 23, 2011 5:36 AM (in response to Colin Holgate) I also voted, and would like to see the (meanwhile) ANE solution too!! thanx 22. Re: AIR 3 ios sound issuesSarah Northway Jan 27, 2012 6:06 PM (in response to saariko) It looks like Colin's Bug has been closed with a reason of "ThirdParty", which I guess means Adobe thinks this is Apple's problem? It also appears that Apple changed their AudioSession api in iOS5 so that it no longer provides the state of the mute switch, so native extensions are no longer a possible solution. I guess unless Adobe changes the AVAudioSession category to AVAudioSessionCategoryAmbient or lets developers change that somehow, we are out of luck. Meanwhile, I continue to receive complaints about my app disobeying the mute switch. 23. Re: AIR 3 ios sound issuesColin Holgate Jan 28, 2012 2:18 AM (in response to Sarah Northway) Flash apps that were made with AIR 2.0 continue to honor the mute switch under iOS 5, so it's still a simple case of if Adobe handled the mute in AIR 3.x in the same way they did with AIR 2.0, the mute would work. It isn't an iOS 5 or Apple problem. 24. Re: AIR 3 ios sound issuesundereyes Feb 1, 2012 9:03 AM (in response to saariko) Hi!, I have ready the Native Extension to mute sounds when mute button is off. You can download and read documentation here: Be happy! 25. Re: AIR 3 ios sound issuesSarah Northway Feb 1, 2012 12:47 PM (in response to undereyes) Yes! Your extension works perfectly, and is so simple - it just lets you pick the AVAudioSession type to use (AMBIENT_SOUND obeys the mute switch and allows itunes music to continue playing). I was under the impression that this couldn't be changed after the initial session was instanciated in Adobe's code, but this may be wrong. However you did it, thank you! 26. Re: AIR 3 ios sound issuessaariko Feb 2, 2012 3:42 AM (in response to undereyes) havn't implemented your ANE yet but according to skatc's post i'll say: THANK YOU! THANK YOU! 27. Re: AIR 3 ios sound issuesundereyes Feb 2, 2012 4:02 AM (in response to saariko) Thanks a lot!!! If you want to see this ANE running (and adMob ANE for iOS) you can download Pompo & Pompa for free: (sorry for the spam) 28. Re: AIR 3 ios sound issuessnoopyhoff Feb 3, 2012 9:27 AM (in response to saariko). 29. Re: AIR 3 ios sound issuesSarah Northway Feb 4, 2012 9:40 AM (in response to snoopyhoff) snoopyhoff wrote:. According to the iOS developer library, Ambient and SoloAmbient are muted both when the mute switch is on and when the screen locks, whereas Playback (which I think is AIR 3's default) does not mute in either situation. So the mute switch + screen locking behavior seem to be tied together. It sounds like your app behaves similarly to Apple's built-in music app which ignores both mute button and when the screen locks. So I'm guessing you'd want to use AIR's default configuration and ignore the mute button. If you're doing that and your app is still getting silenced when it sleeps, it may have to do with Event.DEACTIVATE getting called, although I thought this was only a problem with Android phones and not iOS. 30. Re: AIR 3 ios sound issuesundereyes Feb 6, 2012 1:29 AM (in response to snoopyhoff) you can use my Native Extension to do it: 31. Re: AIR 3 ios sound issuespaus akid Feb 17, 2012 3:11 PM (in response to saariko) ." 32. Re: AIR 3 ios sound issuesSarah Northway Feb 18, 2012 10:16 AM (in response to paus akid) paus akid wrote: ." You may not have set -extdir in your call to atd. To install the extension you need to: - include mute.SWC in your project (I set it as External library (not included)) - call Mute.Enabled() when your project starts: Mute.Enable(Mute.AMBIENT_SOUND); - Add the class to your application.xml: <extensions> <extensionID>com.devilishgames.nativeextensions.mute</extensionID> </extensions> - Add "-extdir PATH_TO_ANE" to your atd package call (my .ANEs are in a directory called rsrc): call adt -package -target %TYPE%%TARGET% %OPTIONS% %SIGNING_OPTIONS% "%OUTPUT%" "%APP_XML%" %FILE_OR_DIR% -extdir rsrc 33. Re: AIR 3 ios sound issuespaus akid Feb 22, 2012 12:46 PM (in response to Sarah Northway) @skatc thanks for the response! Somehow I've gone a step backward rather than forward by trying to make a stripped down example. Here's my steps so far: - include mute.swc in FlashBuilder Package Explorer > right click project name > Properties > ActionScript Build Path > Library path tab > Add SWC... > mute.swc - import class in my main class: import com.devilishgames.nativeextensions.Mute I actually notice some trouble here: Flash Builder reports "1172: Definition com.devilishgames.nativeextensions:Mute could not be found." which is strange to me, I don't have this issue with any other SWC files (ANE or otherwise). Any ideas? Also of note: when using FlashBuilder 4.6 I haven't had to do the last step you mention (modifying the atd package call), it's taken care of automatically if the ANE is specified for packaging, which I did. 34. Re: AIR 3 ios sound issuespaus akid Feb 22, 2012 1:18 PM (in response to paus akid) I figured something out: I'm able to get my previous error (Some classes used in the application could not be resolved for packaging. See error log for more details) when I include the mute.ane durring Export Release Build, even if I don't import or use the class. So adt can't find the class when exporting and FlashBuilder can't find the class when it processes the code for hinting and error detection. But knowing that doesn't help me much any other thoughts appreciated! Thoughts that crossed my mind: I'm compiling on OSX so maybe it's something case sensitive, I'm compiling with Flex SDK 4.6 and the ANE was compiled with 4.5.1 from what I see by unzipping it. 35. Re: AIR 3 ios sound issuesSarah Northway Feb 22, 2012 7:24 PM (in response to paus akid) paus akid wrote: Thoughts that crossed my mind: I'm compiling on OSX so maybe it's something case sensitive, I'm compiling with Flex SDK 4.6 and the ANE was compiled with 4.5.1 from what I see by unzipping it. I'm using Flex SDK 4.6 and AIR 3.1 so that's probably not it. Maybe it's to do with whether the library is included as Internal or External. I use another extension that needs to be Internal while testing in ADL (or the class can't be found - the same error you're having), and needs to be External when building the production IPA or it won't run. However I don't have this issue with Mute. Internal/External inclusion is an explicit setting in FlashDevelop (right-click the swc/options) but I'm not sure about FlashBuilder 4.6 or developing on a Mac. Maybe try removing the reference to the swc entirely, or the reference to the ane? I just ran across another extension that you might have more luck with. It doesn't give you any options, but simply forces the app to use kAudioSessionCategory_AmbientSound: 36. Re: AIR 3 ios sound issuespaus akid Feb 23, 2012 1:02 PM (in response to Sarah Northway) @skatc Yes, I was able to get ANE Silent Switch going without any trouble. I feel it's a bit less elegant of a solution since you have to call SilentSwitch.apply() after every .play() of a sound. I'm not sure what external mode for libraries in flash develop are. From the little bit of reading I just did, it sounds like a way to link to libraries that are outside the path of your project. AFAIK FB4.6 doesn't care where your swc or ane sit on the file system as long as you browse to them in the project properties. I've been emailing with @undereyes and neither of us is sure why the ANE won't work for me (when others do). If anyone with FlashBuilder4.6 is willing to take a look, the barebones test project I created is here: Thanks! 37. Re: AIR 3 ios sound issuesadijans Mar 4, 2012 7:43 PM (in response to undereyes) This is a really great extension I had a bit of trouble getting the packaging process to work as it was my first native extension I've used. I have put together a bit of a guide for other users that covers not just this extension but the whole packaging process if you're used to the Flash IDE. See here: Hopefully this can help others.
https://forums.adobe.com/message/4225594?tstart=0
CC-MAIN-2018-05
refinedweb
2,793
79.09
preface 1. How to analyze the method of high CPU utilization of JVM. 2. How to troubleshoot online jvm memory leaks. 3. How to locate the jvm thread deadlock problem. 4. How to solve the problem of jvm frequently full gc, etc. These problems will be solved step by step through this article. 1, Pre preparation 1. First prepare a web service: eureka-server.jar and start it java -jar eureka-server.jar Download link: Ggxlsyduvfut1a extraction code: lsuw 2, Common jvm commands 1.jps View the process id of the just started erureka service: 4123 [root@centos-linux ~]# jps 4280 Jps 4123 jar 2.jmap 2.1 this command can be used to view the memory information, the number of instances and the memory occupied, and write it to obj_ In info.txt file: [root@centos-linux opt]# jmap -histo 4123 > obj_info.txt - num: serial number - Instances: number of instances - bytes: occupied space - Class name: class name, [C is a char [], [S is a short [], [I is a int [], [B is a byte [], [[I is a int [] [] 2.2 view heap information. [root@centos-linux opt]# jmap -heap 4123 Attaching to process ID 4123, please wait... Debugger attached successfully. Server compiler detected. JVM version is 25.181-b13 using thread-local object allocation. Mark Sweep Compact GC Heap Configuration: MinHeapFreeRatio = 40 MaxHeapFreeRatio = 70 MaxHeapSize = 260046848 (248.0MB) NewSize = 5570560 (5.3125MB) MaxNewSize = 86638592 (82.625MB) OldSize = 11206656 (10.6875: New Generation (Eden + 1 Survivor Space): capacity = 20643840 (19.6875MB) used = 4067112 (3.8787002563476562MB) free = 16576728 (15.808799743652344MB) 19.701334635416668% used Eden Space: capacity = 18415616 (17.5625MB) used = 3581160 (3.4152603149414062MB) free = 14834456 (14.147239685058594MB) 19.446322077958186% used From Space: capacity = 2228224 (2.125MB) used = 485952 (0.46343994140625MB) free = 1742272 (1.66156005859375MB) 21.80893841911765% used To Space: capacity = 2228224 (2.125MB) used = 0 (0.0MB) free = 2228224 (2.125MB) 0.0% used tenured generation: capacity = 45654016 (43.5390625MB) used = 36456800 (34.767913818359375MB) free = 9197216 (8.771148681640625MB) 79.85453021263234% used 23817 interned Strings occupying 3034368 bytes. 2.3 heap memory dump (key, commonly used to analyze OOM problems). [root@centos-linux opt]# jmap -dump:format=b,file=eureka 4123 [root@centos-linux opt]# jmap -dump:format=b,file=eureka.hprof 4123 Dumping heap to /opt/eureka.hprof ... Heap dump file created Online configuration generally sets memory overflow to automatically export dump files (when the memory is large, it may not be exported) 1. -XX:+HeapDumpOnOutOfMemoryError 2. -XX:HeapDumpPath=./ (route) OK, let's simulate a memory overflow scenario to analyze it. The example code is as follows. public class OOMTest { public static List<Object> list = new ArrayList<>(); // JVM settings // -Xms5M -Xmx5M -XX:+PrintGCDetails -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./jvm.dump public static void main(String[] args) { List<Object> list = new ArrayList<>(); int i = 0; int j = 0; while (true) { //Keep putting student objects into the list until OOM list.add(new Student(i++, UUID.randomUUID().toString())); new Student(j--, UUID.randomUUID().toString()); } } } Import the jvm.dump file into the jvisualvm command tool for analysis (the tool is available in the jdk bin directory and can be executed and run) It is obvious that there are a large number of student objects in the stack. If you have small partners, you will have questions. What are the first char [], String? 3,Jstack 3.1. This command can get the information of the java stack and native stack running the java program. You can easily know the running status of the current thread. Let's use an example to learn public class LockTest { private static Object lock1 = new Object(); private static Object lock2 = new Object(); public static void main(String[] args) { new Thread(() -> { synchronized (lock1) { try { System.out.println("thread1 begin"); Thread.sleep(5000); } catch (InterruptedException e) { } //Got lock1. Tried to get lock2 synchronized (lock2) { System.out.println("thread1 end"); } } }).start(); new Thread(() -> { synchronized (lock2) { try { System.out.println("thread2 begin"); Thread.sleep(5000); } catch (InterruptedException e) { } //Got lock2. Trying to get lock1 synchronized (lock1) { System.out.println("thread2 end"); } } }).start(); System.out.println("main thread end"); } } Competing for resources leads to deadlock. ##Using jstack plus process id to find deadlock jstack 64992 Of course, we can also use the JVisualVM tool to analyze. 3.2 the jstack command is also commonly used to find the thread stack information that occupies the highest cpu /** * Run this code and the cpu will soar */ public class CPUTest { public int calculate() { int a = 1; int b = 2; int c = (a + b) * 10; return c; } public static void main(String[] args) { CPUTest cpuTest = new CPUTest(); while (true){ cpuTest.calculate(); } } } 1. After executing the code, top checks the current cpu usage. The cpu usage is about 98% Use command top -p <pid> ,Show your java Memory condition of the process, pid It's yours java Process number, such as 72414 top -p 72414 2. Press H (uppercase) to get the memory of each thread 3. Find the thread tid with the highest memory and cpu consumption, such as 19664 4. Convert to hexadecimal to get 0x2703, which is the hexadecimal representation of thread id 5. Execute jstack 72414|grep -A 10 0x2703 to get the next 10 lines of the line where the thread 0x2703 is located in the thread stack information. From the stack, you can find the calling method that causes the cpu to soar Summary: - I have learned the common commands of jvm: jps, jmap, jstack and other common commands as well as the troubleshooting methods of some classic cases. Later, I will continue to update the performance tuning methods of relevant JVMs and the use of some powerful and easy-to-use tools. It is greatly convenient for us to solve online problems and improve efficiency. If you are interested, please pay attention and praise. I will continue to share it Power of~~
https://programmer.group/6196f30fbe2d0.html
CC-MAIN-2021-49
refinedweb
967
60.21
Program Structure Magpie programs are stored in plain text files with a .mag file extension. Magpie does not compile ahead of time: programs are interpreted directly from source, from top to bottom like a typical scripting language. some code // This is a line comment. // A line comment ends at the end of the line. some more /* This is a block comment. */ code code /* Block comments can span multiple lines. */ Unlike those languages, block comments nest in Magpie. That's handy for commenting out chunks of code which may themselves contain block comments. code /* A /* nested */ block comment */ code code Doc Comments In addition to regular line and block comments, Magpie has a third kind of comment called documentation comments or simply doc comments. They start with three slashes and proceed to the end of the line. def square(n is Int) /// Returns `n` squared. n * n end Doc comments are used to document entire constructs: modules, classes, methods, etc. Unlike other comments, doc comments are not ignored by the language. This means they are only allowed where they are expected: at the beginning of a file, method body, or class definition: defclass Address /// A postal address. val street val city val state end Doc comments are formatted using Markdown and are intended to be parsed to generate documentation files. Reserved Words Some people like to see all of the reserved words in a programming language in one lump. If you're one of those folks, here you go: and async break case catch def defclass do end else false fn for if import in is match not nothing or return then throw true val var while xor Also, the following are punctuators in Magpie which means they are both reserved words and they can be used to separate tokens: ( ) [ ] { } , . .. ... The only built-in operator is =. All other operators are just methods, as explained below. Names Identifiers are similar to other programming languages. They start with a letter or underscore and may contain letters, digits, and underscores. Case is sensitive. hi camelCase PascalCase _under_score abc123 ALL_CAPS Operators Magpie does not have many built-in operators. Instead, most are just methods like any other method. However, the grammar of the language does treat them a bit specially. Lexically, an operator is any sequence of punctuation characters from the following set: ~ ! $ % ^ & * - = + | / ? < > Also, the special tokens .. and ... are valid operator names. But a = by itself is not—that's reserved for assignment. The exact set of operator characters is still a bit in flux. These are all valid operators: + - * ?! <=>&^?! When expressions are parsed, infix operators have the same precedence that you expect from other languages. From lowest to highest: = ! < > .. ... + - * / % Every operator on the same line above has the same precedence. If an operator has multiple characters, the first determines the precedence. So this (unreadable) expression: a +* b *- c <!! d !> e %< f Will be parsed like: (((a +* (b *- c)) <!! d) !> (e %< f)) The goal here is to have code that works more or less like you expect coming from other languages while still being a little more open-ended than those languages. Newlines Like many scripting languages, newlines are significant in Magpie and are used to separate expressions. You can keep your semicolons safely tucked away. // Two expressions: print("hi") print("bye") To make things easier, Magpie will ignore a newline in any place where it doesn't make sense. Specifically, that means newlines following a comma ( ,), equals ( =), backtick ( `), or infix operator ( +, -, etc.) will be discarded: val a = 1, 2 // a will be the record (1, 2). val b = 1 + 2 // b will be 3. val c = true and false // c will be false. If you specifically want to ignore a newline where it otherwise would separate two expressions, you can end the line with a backslash ( \): val a = foo bar() // Sets a to foo then calls bar() val a = foo \ bar() // Equivalent to: // var a = foo bar()
http://magpie.stuffwithstuff.com/program-structure.html
CC-MAIN-2017-30
refinedweb
653
66.03
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. Using the Custom Elements Design Pattern PHILOSOPHY There are more and more tools out there now to build client apps. AngularJS, Ember, Backbone, React, Knockout, etc.. all have their pros and cons. People in charge of development teams seem to agonize over the decision. The approaches in this guide were picked with the following criteria: Code written for Junior Developers Code is read far more than it’s written. Keeping code easy to read makes it easy to maintain. A junior developer should be able to start pushing code on the first day. Code broken into small modules that have no dependencies with other modules Keeping code in decoupled modules allows developers to add or remove code at will without worrying about breaking the codebase. It also allows a developer to maintain a module as its own separate app without necessarily needing to understand how that module relates to the app in general. The DOM is not the source of truth Too often code is trying to determine state by parsing the DOM for information. The DOM is unreliable: it can be refactored, elements can be hidden by code, or DOM elements you assume are present didn’t get rendered. The DOM is simply a view of the state and reacts to changes in the model layer and router. We use a single global object-model which defines our current state and the DOM simply reacts to that model. Decoupled architecture. The front end code is completely decoupled from the backend and only accesses data through a web api. This allows the backend or front end to be swapped out at any time. It also makes available the possibility of creating native apps. No frameworks. Frameworks define how the entire app is created. If a need arises to switch frameworks, this usually results in a re-architect of the code. Libraries are okay. Libraries like jQuery or moment.js are okay to use because they solve a specific problem. They can easily be removed from the project or swapped with a similar library without causing much downtime. Javascript should be obvious and well-commented Creating a massive structure of prototyped objects creates obfuscation and confusion. All javascript code should simply be procedural which is the pattern most junior developers understand. Object-oriented or functional javascript should only be used in rare cases where procedural javascript is not practical. BUSINESS CASE Besides making the codebase easier to write, read and maintain, this code design pattern has several business cases: Rapid Development and Quick Debugging Because the code is insular and modular using custom elements, developing is much faster because each custom element is a mini-app. There is no need to track dependencies (since there are none between custom elements) so there is very little concern about the x- one break- one problem that occurs in more complex code structures. Easy to make responsive Since the front end is decoupled, it’s easier to make responsive. The code can be wrapped into a web-view native app Running the code through Cordova to generate native iOs and Android apps should be relatively painless. Platform designed for new features The code is designed like legos, so adding new features is quick and easy. Just build a custom element and plug it in. Getting Started INSTALLING YOUR ENVIRONMENT The codebase requires a few tools to be installed in your development environment. Install Node.js WINDOWS ONLY: Install Ruby and then run gem install sass Run npm install -g gulp babel npm-check-updates astrum slimerjs casperjs. Clone the project repo. Run npm install. Run ncu -aand follow instructions (if any) THE CODE STRUCTURE Opening the project code, you’ll see several files and a two folders. Let’s look at each one: .eslintrc These are the rules used by ESLint .gitignore Prevents local npm installation from being pushed to the git repo .scss-lint.yml Scss Lint’s rules file. SCSS Lint is used by your code editor to lint your sass code. gulpfile.js This is the Gulp code responsible for compiling and building the codebase. jscs.json The rules for JSCS builds package.json npm uses this file to keep your development environment up to date. README.md A markdown version of this guide skeleton.js This is a blank custom element you can use to start a new custom element for the codebase. this.sublime-project A SublimeText project file that hides the node_modules folder from the list of files. node_modules folder This folder is used by Npm and you shouldn’t need to ever deal with it. It’s probably a good idea to hide it in from your code editor. develop folder This folder contains all the code for this project. develop/assets This folder contains static assets like fonts and images develop/js This contains the global JavaScript files that control the entire app develop/js/vendors This folder contains the third-party JavaScript libraries used in the app develop/sass This folder contains the global sass files for the entire app develop/sass/baseline This folder contains the resets and baseline styles for the entire app develop/sass/themes This folder contains the styles for any instance-specific themes develop/test This folder contains the Tape unit testing code How it Works CUSTOM ELEMENTS The codebase is built around Custom elements are native to Chrome and Android browsers and a small polyfill in the js/vendors folder expands support to the other browsers including iOs. Custom elements are small, self-contained units of code. HTML already has several default elements that come with the markup out of the box: textareas, dropdowns, inputs, etc. Each of these come with their own separate code that allows textareas to be resized, and dropdowns to drop down. What we’re doing with the codebase's custom elements is defining new elements that the browser can use. Just like a textarea, these custom elements have a separate codebase that doesn’t have dependencies on other custom elements. And just like native elements, you can add or remove the custom elements without necessarily breaking the app. If you open the skeleton.js file in the root, you’ll see that the entire custom element is wrapped in a javascript closure. At the top, there is a default ES6 template. The CustomElement Class defines the custom element, and add three hooks: createdCallback(), attachedCallback() and attributeChangedCallback(). createdCallback() This callback is fired when this custom element is created. This is usually done when the app loads and the custom element is defined for the browser. In most cases you won’t need to mess with this callback unless you are lazy-loading this custom element after the app is initialized. attachedCallback() This callback is fired when you place the custom element into the DOM. This usually contains three functions: dataPlug(), buildOut() and events(). You should try to keep these functions in the callback, but occasionally you’ll need to rearrange the order or move one of the function inside another. In that case, you’ll want to make a comment here explaining where the function you moved is found in custom element. You should not remove any of these functions as developers maintaining the code will expect these to be present. If you’re not using them, you can leave the functions blank or comment them out. attributeChangedCallback() If you dynamically add an attribute to the custom element like a data-id or style, this callback will fire. This is only for the custom element itself, not it’s children. The last line of code in this section attaches the custom element to the browser’s HTML api. dataPlug() This function is for data bindings. This is usually where you want to put the initial AJAX calls to fill out any templates used by the custom element. buildOut() This is occurs after the initial data bindings and can be used for any animated buildouts on load. events() This is where event-bindings would occur. The last section (which is blank) is for standalone functions used for this custom element. SCSS Every custom element should have a SCSS file as well. It should be named the same as its accompanying JavaScript file. The sass file will be namespaced for that custom element. EQCSS EQCSS are for element queries and are only included alongside the SCSS files if the custom element is using EQs. More information about element queries can be found here. HOW TO CREATE A CUSTOM ELEMENT To create a new custom element: Copy the skeleton.js and place it in the develop/custom_elements folder, ideally in a separate folder based on URL “pages”. For example, if you’re creating a profile page, you should create a folder called “profile” and put the blank skeleton.js file inside. Rename it to reference your new custom element (like “profile.js”). Create a blank scss file using the same name as your custom element’s js file. At the top of the scss file put: @import “../../sass/Baseline/sass”;Be sure to check the path to ensure it properly targets the baseline sass file. Next put the name of your custom element with empty brackets to setup the custom element’s namespacing. ( new-web-custom-element {}) In the js file, name your custom element where it says "document.registerElement”. If you need a theme for the custom element, put it in the theme scss found in "develop/sass/themes". Register your scss file in "develop/sass/style.scss". Stop and restart gulp to ensure you’ve compiled your new custom element into the codebase. THE PARENT HTML FILE This codebase is contained inside a single HTML file found in develop/html. Any custom elements that should be available in every view should be placed here (like a spinner). Other custom elements are rendered in the <main> tags by the client-side router. SASS The sass for the entire app is contained in the develop/sass folder. CSS for the custom elements is stored alongside the custom element’s JavaScript file in the develop/custom_elements folder. Let’s take a look at what’s in the main Sass folder: develop/sass/baseline/base.scss This is the CSS reset. There isn’t any real reason to mess with the code inside. It simply ensure that any layout biases between browsers is nulled so every browser plays from the same base styles. develop/sass/baseline/embeded.scss, develop/sass/baseline/perfect-scrollbar.scss These are the styles for the embed.js or perfect-scrollbar plugins. Feel free to change them as needed, but remember that if you are changing the look or feel, you might want to offload those styles to a theme file instead. develop/sass/baseline/project.scss These are the baseline styles specific to the codebase and are the style defaults. This should allow pages to render without a theme and still be somewhat stylish. Put global default styles in here. develop/sass/baseline/sass.scss This is where you’d put global sass variables and mix-ins. develop/sass/style.scss This is the manifest SCSS and its sole purpose is to import all the other sass files. UNIT TESTING The codebase has a simple unit testing framework called Tape installed. More information about Tape can be found here. GLOBAL JAVASCRIPT In the develop/javascript file, there are some js files that are used globally: develop/js/vendor/autoexpand-textarea.js This library makes textareas automatically grow in height as text is entered. This is custom library for this codebase so there is no open source project to update this file with. develop/js/vendor/document-register-element.js This is the custom element polyfill. Most of this code comes from here however the typeof HTMLElement !== ‘function’ conditional (which polyfills iOs Safari) is custom. develop/js/vendor/jquery.min.js Umm - jQuery develop/js/vendor/moment.min.js moment.js is a library that helps with javascript time and date issues: develop/js/vendor/perfect-scrollbar.min.js Creates a nice apple-like scrollbar for content: develop/js/vendor/watch.js Allows you to watch an object (usually the single global object) for changes. develop/js/app.js This is the main JavaScript file and is the javascript code the starts to build the app. It: - creates the single global object - pulls in the initial data via AJAX develop/js/router.js This client-side router watches the URL for changes and fires if it changes. It controls which custom elements are loaded and when. GLOBAL OBJECT MODEL The first thing the codebase does on load is create a global Global object. This is object is for data storage only and works like a mini database in memory. The Global object should not contain any functions or constructors. It should not be extended through prototypal inheritance. It is a global data store and that’s it. Some elements can watch the Global object or one of it’s branches using watch.js so as the Global object can be updated in realtime through long polling or web sockets, it can fire events to whatever is watching it. There are several branches to the Global object: Global.client Stores a list of attributes specific to the current session like information about the instance or where the user is in the app Global.member Stores a list of attributes about the current user Global.timestamps A list of timestamps pertaining to when certain data is loaded. This can be used to check whether or not it’s time to re-check that data again from the backend. The Global object should be stored in local storage at regular intervals. This (coupled with Global.timestamps) will reduce server load and speed up the app. When the app loads in the browser the Global object in local storage can be the initial data so the page loads immediately and then it can retrieve any updates it needs. The Global object is the source of truth for the app. The DOM is unreliable since, at any time, it can change, or be re-factored, or become obscured. Global is where you would store data you intend to reference later. Workflow GULP AND NPM The build tool we use in Gulp with npm. Once it’s installed you run it by typing gulp into your command line positioned in the root directory. Each day you’ll want to make sure your tools are up to date so in the command line run: ncu -a This uses the npm-check-updates package to see if there are any updates available for your node packages. If there are, follow the instructions to update them. For the most part, this is all that’s really required to maintain the tools. Gulp The gulpfile.js has several parts: jsSources: put any js files in this array that you want to load after the vendor files. The files are loaded in order. vendorSource: put any third party js files in this array. The files are loaded in order. sassSources: This should only be a single style.scss file, but you could append a theme sass file afterwards if you want to separate that from the main sass files. htmlSources: pretty much the main HTML file, but others can be added, if necessary. eqcssSources: grabs all the .eqcss files in the custom_elements folder. assetSources: any static assets (fonts, images, svgs) are listed here. Running gulp in the command line will compile these sources, run validation and setup a livereload environment for you on localhost:8080. Gulp will watch for changes to the js and sass files and recompile everything on the fly. Vendor.js, raw html and static assets aren’t watched so when you add these to the project you must start gulp and then restart it so it will compile these additions. DESIGNING WITH CUSTOM ELEMENTS When you first start working with custom elements, there’s a tendency to want to write dependencies between them. Don’t. You want the custom elements to function as separate mini-codebases. If you absolutely need to have a dependency, make it a loose coupling where the code first checks if the dependency is present before executing its code. The code should also run well without the dependency present. In the example code, there is a loose dependency between the discussion-input custom element and the discussion-area custom element. The discussion-input, upon received text, will try to attach the text to the discussion-area if it’s present. If it’s not, the discussion-input still functions normally (saving the data and resetting the tool) without breaking the code. This allows the discussion-input custom element to be used anywhere in the codebase we need a discussion-like input. If there needs to be a hard dependency, try using the Global object as a middleman between the dependencies. In the example code, Global.discussions.currentdiscussionID stores which discussion the user is currently in. Since some code is dependent on knowing the current discussion id, having it stored in the Global object prevents needing to check the DOM or other custom elements for that information. JAVASCRIPT AND ES6 This codebase is written using ES6 syntax that is transpiled down to ES5 via the Babel plugin. While it’s not mandatory that the js should strictly adhere to ES6, it’s a good idea to use the latest version of the language to provide some measure of future-proofing. Babel runs automatically when you run gulp. Something else to note about how js works in this codebase: when using selectors, we don’t attach events to CSS classes or IDs. Instead we use a custom attribute called “js-hook”. This custom attribute works like a CSS class, but decouples javascript from the styling of elements. This allows easy front-end code refactoring where class names can be changes and elements re-ordered without breaking the js. It also tells anyone reading the HTML where the js is hooked in so they can be aware of this fact when refactoring. Animating elements in the DOM should be done by adding and removing CSS classes. Animation is part of the presentation layer and shouldn’t be controlled by js. SASS AND CSS The sass in this codebase works normally as any other project. We use sass to namespace the CSS under the custom element, with sub-styles nested under the custom element. This prevents pollution. When creating a modifier class, prepend the class name with “is-” (.is-hidden, .is-collapsed). These modifier classes will be used by the js code to alter the element’s state. Using is- also helps with CSS refactoring because it’s obvious which styles are default and which are modifiers. Themes are always loaded last in the DOM and are used to override the default styles. In general, you want to put the default styles in the custom elements that aren’t used for aesthetics. Styles like color, background-color, font-family, font-size, etc are best placed in the theme file to reduce the need for using !important later. REFERENCES Write web components with es2015 (es6) JavaScript Tip: Avoid Global Variables
https://bitbucket.org/schonne/boilerplate_spa
CC-MAIN-2018-51
refinedweb
3,239
64.61
Talk:Osmosis Contents - 1 Locale depending decimals - 2 Losless version of enableDateParsing - 3 Producing empty timestamps - 4 Filter out relation - 5 Bounding Box - 6 Osmosis running forever with completeWays=yes? - 7 where find specification ? - 8 Import into PostGreSQL fails - 9 Procedure to Import Data into PostgreSQL - 10 What Java distributions will work? - 11 bandwidth exceeded - 12 Not working on windows. Batch recursion error - 13 Cleanup Request - 14 Windows piping - 15 Importing "Something" into clean PostgreSQL/PostGIS database - 16 Wiki Osmosis organization - 17 How to configure temporary filespace? - 18 Bugs Locale depending decimals On my xp box with Slovenian locale osmosis made an extract from planet's node with decimal points: <node id="6968827" timestamp="2007-11-06T20:56:47Z" lat="46.0544422" lon="14.5046166" /> into a node with decimal commas: <node id="6968827" timestamp="2007-11-06T20:56:47Z" lat="46,0544422" lon="14,5046166" /> Trying to import such extract into mysql (with osmosis) it gave me: Exception in thread "Thread-1-read-xml" java.lang.NumberFormatException: For input string: "46,0544422" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at com.bretth.osmosis.core.xml.v0_5.impl.NodeElementProcessor.begin(NodeElementProcessor.java:62) at com.bretth.osmosis.core.xml.v0_5.impl.OsmHandler.startElement(OsmHandler.java:91) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.start) ... IMO OSM xml should always (regardless of current locale) be formatted with decimal dots (us locale), so that they are portable. Temporary workaround is to include commandline parameters -Duser.country=US -Duser.language=en but permanent one something in the line of Locale.setDefault(new Locale("en","US")); during osmosis initialization. - Fixed by User:Brett in version 0.24. Tnx! --Stefanb 06:57, 19 November 2007 (UTC) Losless version of enableDateParsing enableDateParsing option looses timestamps, however it could treat timestamps as strings, copy them to output as string values without really parsing them into a java Date object. This should still be quite fast AND lossless. --Stefanb 21:09, 4 December 2007 (UTC) - Of course this would only make sense if no comparing of timestamps is needed. Or it could be implemented as lazy date parsing (handling them as strings until comparing is needed) --Stefanb 13:13, 15 January 2008 (UTC) - Yes, I was thinking lazy parsing would be the way to go, and if they're unused in the pipeline, just write out the original timestamp string. Probably would have to change the constructor to accept a string instead of a date, and add another function to get the raw date string. --SiliconFiend 04:36, 16 January 2008 (UTC) - Only now i noticed changes.txt in SVN changesets 8341 and 8342 mentioning: - Enhanced the Entity class to allow dates to be represented as strings to avoid parsing overhead. Updated xml tasks to utilise this feature. - but i fail to see any speed boosts (compared to my build of version 0.24.3) or documentation changes about it. How does one use that? Documentation for enableDateParse still basically says "no timestamps or poor performance" --Stefanb 00:36, 22 November 2008 (UTC) Producing empty timestamps If the elements of input file don't have the optional(!) timestamp attribute (eg from Srtm2Osm) the resulting elements will have a non-sense (and probably invalid) timestamp="" attribute on the output. Not a major problem, but worth knowing and fixing sometime. --Stefanb 10:49, 17 January 2008 (UTC) gpsbabel produces 0.5 files without a timestamp too. As of osmosis-0.31.2 this causes a crash. osmosis-0.31.2/bin/osmosis --read-xml-0.5 Srtm2Osm/srtm3-full-route.osm --migrate --wx Srtm2Osm/srtm3-full-route06.osm org.openstreetmap.osmosis.core.OsmosisRuntimeException: The entity timestamp attribute is missing. at org.openstreetmap.osmosis.core.domain.common.UnparsedTimestampContainer.<init>(UnparsedTimestampContainer.java:34) at org.openstreetmap.osmosis.core.xml.common.BaseElementProcessor.createTimestampContainer(BaseElementProcessor.java:90) at org.openstreetmap.osmosis.core.xml.v0_5.impl.NodeElementProcessor.begin(NodeElementProcessor.java:65) at org.openstreetmap.osmosis.core.xml.v0_5.impl.OsmHandler.startElement(OsmHandler.java:94) Others have seen this too Filter out relation Hi, I can't find an option to filter out all relations from the output. --chris66 15:39, 13 November 2008 (UTC) Bounding Box when cutting out a rectangular area (--bounding-box) is it possible to write this bounding box to the output file in the header? --chris66 15:45, 13 November 2008 (UTC) Also is there any chance that Bounding Box could deal with change sets rather than just raw xml? --Sjk 01:21, 19 November 2008 (UTC)--sjk Osmosis running forever with completeWays=yes? I am trying to cut 10 areas out of the planetfile for germany. When I set the parameter completeWays=yes for these areas, osmosis (V0.29) seems to run forever. After 8,5 hours of CPU time, osmosis had created a number of large temporary files, one output file was at about 15% the expected size and all others were still empty. Without the parameter completeWays=yes the job is completed in less than 30 minutes. Is completeWays=yes broken? Or does it really take this long to process? Is there anything I can do? I want the cut areas to be seamless, that is the reason I switched on completeWays=yes. --Nop 19:09, 1 February 2009 (UTC) where find specification ? artice say osmosis deal with database and file !! is there some more details in some documentation ? : all jdbc drivers not only mysql ? User:France-59-valenciennes 15:51 , 8 February 2009 (UTC) Import into PostGreSQL fails I'm trying to use osmosis to import direct into postgresql. I installed Osmosis using: wget tar xvfz osmosis-latest.tar.gz cd osmosis-0.30 bin/osmosis The notes say cd to osmosis-0.29. Downloaded version is osmosis-0.30 - I guess not a problem. Postinstallation, when I run this command: - $ bin/osmosis --read-xml file="/root/south-090218.osm" --write-pgsql host="localhost" database="osmtest1" user="postgres" password="..." I get this error: 24-Feb-09 2:56:32 com.bretth.osmosis.core.Osmosis run INFO: Osmosis Version 0.30 24-Feb-09 2:56:33 com.bretth.osmosis.core.Osmosis run INFO: Preparing pipeline. 24-Feb-09 2:56:33 com.bretth.osmosis.core.Osmosis run INFO: Launching pipeline execution. 24-Feb-09 2:56:33 com.bretth.osmosis.core.Osmosis run INFO: Pipeline executing, waiting for completion. 24-Feb-09 2:56:33 com.bretth.osmosis.core.pipeline.common.ActiveTaskManager waitForCompletion SEVERE: Thread for task 1-read-xml failed java.lang.NoClassDefFoundError: org.postgresql.jdbc4.AbstractJdbc4Connection at java.lang.Class.initializeClass(libgcj.so.81) at java.lang.Class.initializeClass(libgcj.so.81) at org.postgresql.Driver.makeConnection(Driver.java:386) at org.postgresql.Driver.connect(Driver.java:260) at java.sql.DriverManager.getConnection(libgcj.so.81) at java.sql.DriverManager.getConnection(libgcj.so.81) at com.bretth.osmosis.core.pgsql.common.DatabaseContext.getConnection(DatabaseContext.java:85) at com.bretth.osmosis.core.pgsql.common.DatabaseContext.createStatement(DatabaseContext.java:184) at com.bretth.osmosis.core.pgsql.common.SchemaVersionValidator.validateDBVersion(SchemaVersionValidator.java:72) at com.bretth.osmosis.core.pgsql.common.SchemaVersionValidator.validateVersion(SchemaVersionValidator.java:52) at com.bretth.osmosis.core.pgsql.v0_5.PostgreSqlWriter.initialize(PostgreSqlWriter.java:284) at com.bretth.osmosis.core.pgsql.v0_5.PostgreSqlWriter.process(PostgreSqlWriter.java:1012) at com.bretth.osmosis.core.xml.v0_5.impl.NodeElementProcessor.end(NodeElementProcessor.java:103) at com.bretth.osmosis.core.xml.v0_5.impl.OsmHandler.endElement(OsmHandler.java:109) at gnu.xml.stream.SAXParser.parse(libgcj.so.81) at javax.xml.parsers.SAXParser.parse(libgcj.so.81) at javax.xml.parsers.SAXParser.parse(libgcj.so.81) at com.bretth.osmosis.core.xml.v0_5.XmlReader.run(XmlReader.java:109) at java.lang.Thread.run(libgcj.so.81) Caused by: java.lang.ClassNotFoundException: java.sql.SQLClientInfoException not found in gnu.gcj.runtime.SystemClassLoader{urls=[file:/root/osmosis-0.30/osmosis.jar,file:/root/osmosis-0.30/lib/mysql-connector-java-5.0.7-bin.jar,file:/root/osmosis-0.30/lib/postgresql-8.3-603.jdbc4.jar,file:/root/osmosis-0.30/lib/postgis_1.3.2.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}} at java.net.URLClassLoader.findClass(libgcj.so.81) at gnu.gcj.runtime.SystemClassLoader.findClass(libgcj.so.81) at java.lang.ClassLoader.loadClass(libgcj.so.81) at java.lang.ClassLoader.loadClass(libgcj.so.81) at java.lang.Class.forName(libgcj.so.81) at java.lang.Class.initializeClass(libgcj.so.81) ...18 more 24-Feb-09 2:56:34 com.bretth.osmosis.core.Osmosis main SEVERE: Execution aborted. com.bretth.osmosis.core.OsmosisRuntimeException: One or more tasks failed. at com.bretth.osmosis.core.pipeline.common.Pipeline.waitForCompletion(Pipeline.java:146) at com.bretth.osmosis.core.Osmosis.run(Osmosis.java:85) at com.bretth.osmosis.core.Osmosis.main(Osmosis.java:30) Advice appreciated. User:Nerdling 15:06, 24 February 2009 - There is an osmosis-dev mailing-list for this kind of questions. In your case you did not add the postgres-jdbc-driver to your classpath. --MarcusWolschon 07:58, 25 February 2009 (UTC) Maybe this is just user error (perhaps i need to escape it?), but passing a keyValueList that contains a key with a namespace kills osmosis without a whimper. e.g. osmosis --read-xml file="cambridge.osm" --node-key-value keyValueList="gnis:reviewed.no,building.yes" --write-xml file="filtered.osm" User:Pouletic 02:09, 4 April 2009 Procedure to Import Data into PostgreSQL See Osmosis_PostGIS_Setup What Java distributions will work? I'm not really familar with java. Using Debian Lenny, I have a confusing choice of different java-distros. At least, there is: - OpenJDK - GCJ - Sun JDK 6.0 (and even 5.0) In Osmosis PostGIS Setup, there is an example using openjdk-6-jdk. Following Osmosis#Notes, the favorite distro seems to be Sun JDK 6.0. Could anybody give me a hint what would be the best to install? Concerning PostGIS: I have experienced many oddities in PostGIS. So, is it worth to use the PostGIS storing scheme or is regular PostreSQL without PostGIS sufficient? Thanks for any help. -- Hansm 09:57, 4 July 2009 (UTC) - It's possible all of those will work. I don't think osmosis is very demanding in terms of java features, compared to many GUI apps for example... but then if you want (or may in the future want) other java apps running trouble free, I suspect a Sun JDK will be the best recommendation. More general java info on the Java Runtime Environment page -- Harry Wood 09:44, 8 November 2011 (UTC) bandwidth exceeded seems to be having some bandwidth trouble. "The bandwidth or page view limit for this site has been exceeded and the page cannot be viewed at this time. Once the site is below the limit, it will once again begin serving as normal." -- Harry Wood 19:59, 21 July 2009 (UTC) - There's a download mirror here (maybe only temporary) : -- Harry Wood 10:52, 29 July 2009 (UTC) Not working on windows. Batch recursion error Trying to use it on Windows Vista from the command line running osmosis.bat I get: C:\server\installers\osmosis-0.31.2\bin>osmosis ****** B A T C H R E C U R S I O N exceeds STACK limits ****** Recursion Count=650, Stack Usage=90 percent ****** B A T C H PROCESSING IS A B O R T E D ****** With 0.31.2 and I think 0.31.0/1 (not sure which - there are no version numbers in there, but the .bat file is different). Any suggestions on how to actually get it to work? (I've not changed anything) Thanks. Asdf 15:34, 3 August 2009 (UTC) - Hehe. Awesome error message. Not sure what's causing that exactly, but there's been a few problems with the windows bat script. Working from the latest Osmosis in subversion is probably a good idea, or just take a look at the current version of the bat script. - See also this forum post where I've pasted in a full java command which should work (bypassing the bat script). - Note that even when you get it working, you can't process recent bzipped planet files very easily with windows as far as I can tell. See Osmosis#Notes - -- Harry Wood 17:07, 3 August 2009 (UTC) - I get the same error message (amongst many when trying to use osmosis on Windows 7 x64, has the above been solved? I tried with latest but would run into that error nevertheless. Also no luck on ubuntu for me, seems I'm too stupid for osmosis. 6 month ago osmosis would run fine on my pc however. Don't have any old version anymore, 029 works in XP, but not in 7. On Ubuntu no luck with any version.--Extremecarver 16:00, 3 September 2009 (UTC) Cleanup Request Hi, if it's ok I would like to clean up the osmosis related pages a bit, because for me it was a mess to find some more advanced things. I suggest to: - move Benchmarking to a sep /Benchmarking - move all examples to /Examples - splitting Detailed usage into Storage/Manipulation/Pipeline features and add examples there? - add a sketch showing pipe concept --!i! 11:17, 15 February 2011 (UTC) If anybody knows if Using_planet.osm is still up to date feel free to label it as outofdate or remove it --!i! 21:01, 23 February 2011 (UTC) - Please don't alter it as it stands. In particular do not remove examples and do not split Detailed usage into subpages. The pages are large and contain a lot of information: they are frequently used as core manual pages. As such they are probably more useful than many wikipages. SK53 19:10, 7 April 2011 (BST) - I agree with SK53. There's different ways it could be organised but the Osmosis/Detailed Usage page works reasonably well as is. It's also quite carefully maintained by User:Brett (The main osmosis developer) as the primary documentation, and we don't want to get in his way doing that. No need to fiddle with it. - The examples on the main Osmosis page, I'm thinking perhaps some of them should be moved onto Osmosis/Examples, but not all. It makes sense to have some some simple examples there for quick prominent access. In general the Osmosis/Examples page could be fleshed out with more useful content. It's currently has a couple of quirky how-tos. - Sketch showing pipe concept is good idea - Overall though I feel that this page isn't in need of a cleanup all that much. Right now the most messy thing about this page is the cleanup label! So I'm going to remove it. - -- Harry Wood 15:56, 29 June 2011 (BST) Windows piping In the bounding box extract example, it is suggested to use CONIN$ instead of /dev/stdin on a windows command prompt. This does not work for me (Win7) and I could not find a good reference to using this variable. Is there any way to do this using Win7? -- Martijn van Exel 14:30, 28 February 2011 (UTC) - fixed the example. use a dash for stdin. You might want to google for pipebuf.exe to speed up the pipe even more. --Stephankn 19:47, 6 March 2011 (UTC) Importing "Something" into clean PostgreSQL/PostGIS database Hello, i have problems to follow the examples. While i am trying to start: 'osmosis --read-xml file="myosm.osm" --write-apidb host="localhost" database="postgis" user="postgres" password="xxx"' i get) User:Asdfasdfasdf - 13:47, 1 May 2011 - You pasted in a massive stacktrace. I've thinned it down to just the relevant error messages. I'm pretty sure the key error message is "FEHLER: Relation +schema_migrations½ existiert nicht" - I dont actually know the answer to your question, but I guess you need some tables in place prior to running osmosis. I've not tried doing this myself. I'm sure somebody else can help you, but you might have more luck using a different Contact channel. - -- Harry Wood 11:25, 3 May 2011 (BST) Wiki Osmosis organization There's a lot of great Osmosis-related content on the wiki, but it seems like much of it is spread across several pages and is overlapping on many of those pages. For example, the following pages cover some similar topics: - Osmosis - includes installation, some use examples, tuning information, and leads with a pretty technical description of what Osmosis does - Osmosis/Installation - Osmosis/Examples - from the page: "This page gives some more obscure or convoluted examples of Osmosis usage" - Detailed_Usage_0.41 - this seems more like "man osmosis" than "detailed use," as it primarily discusses command line options and not use cases - Osmosis/Tuning - - Using_planet.osm - includes optimization tips, osmosis use examples I'd like to recommend a cleanup of the main Osmosis page, with the following structure: - Introduction - less technical explanation - explain what it does and why it was built - OSM data background - primary data types (xml, pbf), primary data stores used, sizes of files, etc. - Osmosis basic tech background - and make the following changes: - Consolidate all installation information from Osmosis into Osmosis/Installation - Combine the use examples from Osmosis and Using_planet.osm into a new Osmosis_Getting_Started page - Move the tuning information from Using_planet.osm to Osmosis/Tuning I realize these suggested changes might not seem small, but I believe they will streamline this content significantly, and consolidate similar information, which should hopefully reduce opportunity for conflicting information. It might also lighten the translation load if there's less redundancy. Also - I'd be willing to do this work (in English : ) ). Thoughts? Jeffmeyer 07:57, 20 October 2012 (BST) - What does "OSM data background" have to do with Osmosis? That would appear to duplicate content available elsewhere because it equally applies to all tools. --Tordanik 14:50, 20 October 2012 (BST) - It has to do with the "why" of Osmosis - why does it exist in the first place? Why are there different storage formats? Why do we care about converting data formats? This shouldn't be a deep dive - that should certainly be linked elsewhere. I'm thinking of a sentence or two at most. As it is, although the page explains a little of what osmosis can do, it doesn't explain the why, at least imo. Any thoughts on the other suggestions? Jeffmeyer 21:16, 20 October 2012 (BST) - Only minor feedback otherwise, e.g. Osmosis/Getting started would match the subpage structure used elsewhere. What I would like to see is something about the architecture and use as a library - something to point people with questions like these[1][2] -, but that might be a bit offtopic here, because it would be new content rather than a change of the pages' organization. Oh, and I think you should wait a while longer for feedback, or (maybe) even announce your intention on the osmosis-dev list to avoid that developers are surprised by your changes. Many users don't visit their wiki watchlist all the time. --Tordanik 23:12, 20 October 2012 (BST) How to configure temporary filespace? I've just switched to using idTrackerType=Dynamic, and I'm noticing that Osmosis is throwing huge (700MB) files into /tmp (yes /tmp not $TMPDIR). Which is a problem when /tmp is only 1200MB and other things wish to use it. If Osmosis respected $TMPDIR like every other application, then it would be easy to point it somewhere with more space. So what's the magic to tell it where to put this huge file? --tms13 (talk) 16:13, 15 February 2013 (UTC) Forgot to mention - the temporary files are not removed when Osmosis throws an exception. I expected a 'finally' to clear up this resource drain... --tms13 (talk) 12:39, 18 February 2013 (UTC) - Not sure if this is helpful because it's not answering your question but... Which version of osmosis are you using? If you use the latest v0.42 you don't (I believe) need to use idTrackerType=Dynamic to solve the 64-bit Identifiers problems. -- Harry Wood (talk) 14:00, 18 February 2013 (UTC) - Thanks, Harry. I'm currently using Osmosis Version 0.40.1 (Debian testing), and will remove the idTrackerType argument as soon as we get 0.42 (I only added it because osmosis starting failing on 64-bit ids last week). I don't think the file usage is specific to using idTrackerType=Dynamic, though; I'm half-certain that it does the same without. :( --tms13 (talk) 17:08, 18 February 2013 (UTC) - And now here's the actual answer: - export JAVACMD_OPTIONS="-Djava.io.tmpdir=/home/fred/tmp" - Found this in a bug ticket here: - -- Harry Wood (talk) 18:00, 18 February 2013 (UTC) - Thanks again. I've now added if [ -d "$TMPDIR" ]; then JAVACMD_OPTIONS="$JAVACMD_OPTIONS${JAVACMD_OPTIONS+ }-Djava.io.tmpdir=$TMPDIR" fi Bugs Where can bugs be logged (e.g. the problems reported at ). There's and also - but there seems to be no issues list? --SomeoneElse (talk) 12:20, 11 September 2015 (UTC)
http://wiki.openstreetmap.org/wiki/Talk:Osmosis
CC-MAIN-2017-04
refinedweb
3,509
50.84
Eclipse Community Forums - RDF feed // Eclipse Community Forums specifying icons in exeed // <![CDATA[Hi. A very simple question: I'm starting to use exeed. I want to make an annotation to specify the icon: @exeed(icon... How should I do this? Full path, path relative to what... A simple example of this would be appreciated. Thanks in advance Oskar]]> oskar saiz 2013-04-09T13:19:19-00:00 Re: specifying icons in exeed // <![CDATA[Hi Oskar, Currently, the selection of icons is limited to the built-in icons provided by Exeed [1]. Could you please file an enhancement request so that we can also provide support for custom plugin-based icon locations? Cheers, Dimitris [1]]]> Dimitris Kolovos 2013-04-10T01:00:28-00:00 Re: specifying icons in exeed // <![CDATA[Hi Dimitris. I've just filed the enhancement request as you suggested. Anyway I'm not able to change icons even using the ones provided by Exeed. I've tried with Icon and classIcon; with the name of the icon and with the name and path of the icon, but no success. Some samples: @exeed(classIcon="return 'compare.gif';") @exeed(Icon="return 'icons/compare.gif';") How should this be done? Thanks a lot Oskar]]> oskar saiz 2013-04-16T07:40:00-00:00 Re: specifying icons in exeed // <![CDATA[Hi Oskar, Off the top of my head it should be @exeed(classIcon="compare") @exeed(icon="return 'compare';"); Below is an example of an annotated metamodel and I've also attached a deck of slides I've used in the past to present Exeed. I hope to find some time to transcode this to a HTML page with new screenshots etc. soon but any help with this would be more than welcome Cheers, Dimitris]]> Dimitris Kolovos 2013-04-16T14:44:25-00:00 Re: specifying icons in exeed // <![CDATA[Hi Dimitris. Thank you for the reply. I tested it. Here the result: 1.- This works: a) @exeed(ClassIcon="compare") 2.- These do not work; b) @exeed(icon="compare") c) @exeed(icon="return 'compare';") d) @exeed(classIcon="return 'compare';") c) and d) do worry me: Does this mean that I cannot use a EOL expression for specifying the icon? Must I use just an icon name (as in (a))? Thanks again Oskar]]> oskar saiz 2013-04-17T12:46:15-00:00 Re: specifying icons in exeed // <![CDATA[Hi Oscar, I can't reproduce c) as the following works fine for me --- @namespace(uri="foo", prefix="") package foo; @exeed(icon="return 'package';") class X { attr XType type; } --- d) shouldn't work because "classIcon" is meant to be a static string. For context-specific icons, "icon" should be used instead. Cheers, Dimitris]]> Dimitris Kolovos 2013-04-17T13:42:07-00:00 Re: specifying icons in exeed // <![CDATA[Hi Dimitris. You are right. c) case is also working. @exeed(icon="return 'compare';") Anyway, I'd like to point a couple of things: 1.- According to previows message answers I would derive that the exeed documentation is not correct: It says: classIcon: EOL expression that returns the icon of the instances that conform to the EClass. In my opinion, it should say somthing like: classIcon: name of the icon of the instances that conform to the EClass. It is not a EOL expression but a name. 2.- When both annotations (icon and classIcon) are combined, it is not working as expected. For instance: @exeed(classIcon="clock") @exeed(icon="return 'package';") According to exeed documentation, when 'icon' is specified, it should override the classIcon annotation. My experimentation suggest that the first annotation is "winning". In the example above, when both annotations are used (icon and classIcon), the 'classIcon' one wins. (In the example, the "clock" icon is shown). However, changing the order, the 'package' one wins. @exeed(icon="return 'package';") @exeed(classIcon="clock") This sounds like a bug. Doesn't it? Thanks again Oskar]]> oskar saiz 2013-04-18T06:47:23-00:00 Re: specifying icons in exeed // <![CDATA[Hi Oskar, I've just fixed #1 on the website. Regarding #2 with the following metamodel, instances of X always appear with a "class" icon regardless of the order of the two annotations. Are you encountering a different behaviour? -- @exeed(classIcon="class") @exeed(icon="return 'package';") class X { attr XType type; } -- Cheers, Dimitris]]> Dimitris Kolovos 2013-04-18T07:34:09-00:00 Re: specifying icons in exeed // <![CDATA[Hi Dimitris. Yes. If I write @exeed(icon="return 'package';") @exeed(classIcon="class") always the 'package' icon appears. Anyway, in your example the behaviour isn't either the expected one: When both are specified, the one of the "icon" should win, in this case de 'package' icon, shouldn't it? Thansk again Oskar ]]> oskar saiz 2013-04-18T07:48:09-00:00 Re: specifying icons in exeed // <![CDATA[Hi Oskar, You're right (I clearly shouldn't be replying to newsgroup messages before I've had coffee ). I'll try to fix this shortly. Cheers, Dimitris]]> Dimitris Kolovos 2013-04-18T08:11:01-00:00 Re: specifying icons in exeed // <![CDATA[Actually, both details should go under the same annotation (Exeed only looks at the first @exeed annotation for each element): @exeed(classIcon="class", icon="return 'package';") Cheers, Dimitris]]> Dimitris Kolovos 2013-04-21T20:17:34-00:00 Re: specifying icons in exeed // <![CDATA[That made it!!! Thanks a lot Dimitris. Bye Oskar ]]> oskar saiz 2013-04-22T06:23:13-00:00
http://www.eclipse.org/forums/feed.php?mode=m&th=472843&basic=1
CC-MAIN-2014-15
refinedweb
902
58.28
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Mark-Jason Dominus writes about "accidental syntax" in Perl, and wonders if this happens in other languages. I couldn't think of any examples offhand, but I'm sure Common Lisp must have some... Duff's device has accidental semantics, too! The semantics of the quasiquotation operators can get pretty hairy. ISTR a classic incident when the code was right, but it took the gurus some time to realize why (It involved something like `,`, ). I think that the semantics of nested quasiquotation in Common Lisp and Scheme is wrong. It should work like backslashes in strings in most languages: unescaped unquotes are processed immediately, escaped unquotes become unescaped unquotes for the next stage. This semantics wouldn't need the current workaround for the inability of unquoting inside a nested quasiquotation. The workaround uses a regular Lisp quote, and leaves an extra unquote and quote after the first stage of the expansion, which cancel each other out under the standard interpretation of quasiquotation (modulo sharing constraints). A concrete syntax of escaping might unambiguously use doubled unquote for example to denote escaped unquote, as a naked unquoted term is not a valid expression, so this couldn't be meaningfully interpreted as a regular unquote. You can get a double quote in a string by quoting it: "\"" => " If you want to quote the source string you have to backslash the quotes and the backslash: "\"\\\"\"" => "\"" Another round of quoting: "\"\\\"\\\\\\\"\\\"\"" => "\"\\\"\"" make the exponential growth frighteningly apparent. By constrast, CL's nested quasiquotation works OK. Here is an example of a triple nesting (defmacro define-namespace (prefix-to-name operator) `(defmacro ,(intern (format nil "~A-NAMES" prefix-to-name) (symbol-package prefix-to-name)) (names &body code) (flet ((make-macro-def(name) `(,name (&rest args) `(,',',operator ,',name ,@args)))) `(macrolet ,(mapcar #'make-macro-def names) ,@code)))) The variable OPERATOR is evaluated on the first round of evaluation, then sits out two more rounds. I doubt that anyone needs more than 3 levels of nesting in practice. With even deeper nesting it's probably more clear to use auxiliary macros than to write everything inline, no matter which semantics of nesting is chosen. And with 3 levels of nesting the exponential length is quite short compared to the linear length: , and ,, and ,,,, correspond to ,',', and ,', and ,. , ,, ,,,, ,',', ,', There's a discussion of comma-quote-comma on p74 of The Evolution of Lisp. It is intuitive when you've got your head around it, but it took me a while. Definitely accidental syntax. For example from this page describing its use in the fc++ library. But I mean the subject in a good way. Reading this, and reading about some of the features in the Boost C++ -- especially the lambda and format facilities -- I've lately seen some interesting C++ constructs. Impressive, actually, as it allows for a more expressiveness than I thought possible for the language. That looks like the kind of hoops jMock makes Java jump through to emulate Smalltalk syntax. yesterday I stumbled over the "goes toward" operator: void doStuff(int count) { while(count --> 0) fleh(); } It is possible to make this Vector vec; vec = 1, 2, 3; initialise a vector with 3 elements. But it is parsed as ((vec = 1), 2), 3; Vector vec = 1, 2, 3; will not work. This is really where operator overloading gives me a headache. It's a perfect example of accidental syntax, I think, taking advantage of the fact that assignment in C++ is an expression, as is the result of the comma (list) operator. It doesn't work in the Vector vec = ... example because you're declaring a variable, and in that context the comma takes on a different meaning (allowing you to declare multiple variables of one type: Vector v = 1, vv, vvv = 3, and so forth). Any other operator overload should work, except for the comma, which here loses its usual expressive purpose. I do think operator overloading can be useful and can be done well. But it's up to the designer whether it is or is not done well, which puts off a lot of people. Some would rather throw up their hands in disgust, and have the whole lot carted off to the trash. Wikipedia has a description of it. For fun, I transliterated Jensen's Device and (Knuth's) Man or Boy Test to SML. Do explicit ref cells and thunks make them easier to understand? (* Jensen's Device *) local val i = ref 0 fun sum (i, lo, hi, term) = let val temp = ref 0.0 in i := lo ; while !i <= hi do (temp := !temp + term () ; i := !i + 1) ; !temp end in val () = print (Real.toString (sum (i, 1, 100, fn () => 1.0 / real (!i)))^"\n") end (* Man or Boy Test *) local fun A (k, x1, x2, x3, x4, x5) = let fun B () = (k := !k - 1 ; A (ref (!k), B, x1, x2, x3, x4)) in if !k <= 0 then x4 () + x5 () else B () end in val () = print (Int.toString (A (ref 10, fn () => 1, fn () => ~1, fn () => ~1, fn () => 1, fn () => 0))^"\n") end It just seems like what you'd expect from call-by-name. Surely the designers of Algol intended this, otherwise they'd have adopted call-by-value. No, from that I heard the designers of Algol 60 didn't have a very thorough understanding of what could be done by call by name, and jensens device was concived to point that out. I don't even think that it could be run on many implementations of Algol 60.
http://lambda-the-ultimate.org/node/1309
CC-MAIN-2018-30
refinedweb
940
62.17
The editor is indenting after a carriage return when 1) the code block above has been closed, and 2) when the prevailing format above is left margin aligned. Why does it do this? I turned off SmartIndent and have "solved" the problem that way, however, I find the SmartIndent feature very handy and would prefer if it were enabled. Btw, the indent would still occur even if I didn't have that IF block. It will indent after variable, class, and function definitions as well as include and require statements... Does this sound like a problem any one else is having and if so, have you managed to fix it? Attachment(s): 3-20-2011 12-14-16 PM.png I think all this is happening because of namespace and this is a bug. Please submit it to. Thanks for spotting the issue! This is the second time I have been directed to do your job. So far I have made two posts - both were bugs - and I have been told to log the issue myself both times. This is my free time, guys; I write software for a living and would never ask one of my clients to do something that was my responsiblity. I sloppily logged the issue, but this has left an unpleasant taste in my mouth. WI-5610 We require users to submit bug reports because we need to get various additional information and a way to provide feedback to/from original reporter. Refusal to do so significantly reduces chances that your problem will be adressed. Any such "requirement" for your clients to provide to you with feedback can easily be handled through a courteous request email. You don't see a chef at a restaurant asking their patrons to watch the stove while they cook the rest of their order. Get it? Most importantly, your argument regarding the refusal of submittal potentially holds water only if this were a feature request issue, but this obviously isn't a feature request; this is a functional defect as a result of using a popular language feature -- issues under such a classification are everyone's problem, especially yours. That was merely constation of fact: there are hundreds of reports of various severity and reproduce/fix complexity for each developer and refusal of following established procedure will definitely reduce chances that your problem to be adressed soon. I hear ya. You make the best IDE's on the planet; I'm thankful for that, and I could definitely be less of an ass about writing up bugs. At the same time, do you not have access to a QA department to check into concerns raised by whomever? This is what they're for, afterall. Over and out. I'm still seeing this behavior a year after this report. If "smart indenting" is enabled then it indents when you hit enter when for instance you're writing some css and you want to jump down a line to add another rule. Disabling it means you have to manually expand block curly braces. What a hassle. I don't think this bug has been fixed unless I'm missing something. As far as I can tell, it's been fixed since PHPStorm version 2.1.
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206371809-PHPStorm-smart-indenting-the-wrong-lines-?page=1
CC-MAIN-2020-29
refinedweb
544
71.34
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages. recp/cglm 🎥 OpenGL Mathematics (glm) for C Documentation Almost all functions (inline versions) and parameters are documented inside the corresponding headers. Complete documentation: Note for previous versions: - _dup (duplicate) is changed to _copy. For instance glm_vec_dup -> glm_vec3_copy - OpenGL related functions are dropped to make this lib platform/third-party independent - make sure you have latest version and feel free to report bugs, troubles - [bugfix] euler angles was implemented in reverse order (extrinsic) it was fixed, now they are intrinsic. Make sure that you have the latest version - [major change] by starting v0.4.0, quaternions are stored as [x, y, z, w], it was [w, x, y, z] in v0.3.5 and earlier versions - [api rename] by starting v0.4.5, glm_simd functions are renamed to glmm_ - [new option] by starting v0.4.5, you can disable alignment requirement, check options in docs. - [major change] by starting v0.5.0, vec3 functions use glm_vec3_ namespace, it was glm_vec_ until v0.5.0 - [major change] by starting v0.5.1, built-in alignment is removed from vec3 and mat3 types - [major change] by starting v0.7.3, inline print functions are disabled in release/production mode to eliminate print costs (see options in documentation). Print output also improved. You can disable colors if you need (see documentation) Note for C++ developers: If you are not aware of the original GLM library yet, you may also want to look at: Note for new comers (Important): vec4and mat4variables must be aligned. (There will be unaligned versions later) - in and [in, out] parameters must be initialized (please). But [out] parameters not, initializing out param is also redundant - All functions are inline if you don't want to use pre-compiled versions with glmc_ prefix, you can ignore build process. Just include headers. - if your debugger takes you to cglm headers then make sure you are not trying to copy vec4 to vec3 or alig issues... Note for experienced developers: - Since I'm testing this library in my projects, sometimes bugs occurs; finding that bug[s] and making improvements would be more easy with multiple developer/contributor and their projects or knowledge. Consider to make some tests if you suspect something is wrong and any feedbacks, contributions and bug reports are always welcome. Allocations? cglm doesn't alloc any memory on heap. So it doesn't provide any allocator. You should alloc memory for out parameters too if you pass pointer of memory location. Don't forget that vec4 (also quat/versor) and mat4 must be aligned (16-bytes), because cglm uses SIMD instructions to optimize most operations if available. Returning vector or matrix... ? cglm supports both ARRAY API and STRUCT API, so you can return structs if you utilize struct api ( glms_). Other APIs like Vulkan, Metal, Dx? Currently cglm uses default clip space configuration (-1, 1) for camera functions (perspective, extract corners...), in the future other clip space configurations will be supported Features - array api and struct api, you can use arrays or structs. - general purpose matrix operations (mat4, mat3) - chain matrix multiplication (square only) - general purpose vector operations (cross, dot, rotate, proj, angle...) - affine transformations - matrix decomposition (extract rotation, scaling factor) - optimized affine transform matrices (mul, rigid-body inverse) - camera (lookat) - projections (ortho, perspective) - quaternions - euler angles / yaw-pitch-roll to matrix - extract euler angles - inline or pre-compiled function call - frustum (extract view frustum planes, corners...) - bounding box (AABB in Frustum (culling), crop, merge...) - bounding sphere - project, unproject - easing functions - curves - curve interpolation helpers (SMC, deCasteljau...) - helpers to convert cglm types to Apple's simd library to pass cglm types to Metal GL without packing them on both sides - ray intersection helpers - and others... You have two option to call a function/operation: inline or library call (link) Almost all functions are marked inline (always_inline) so compiler will probably inline. To call pre-compiled version, just use glmc_ (c stands for 'call') instead of glm_. #include <cglm/cglm.h> /* for inline */ #include <cglm/call.h> /* for library call (this also includes cglm.h) */ mat4 rot, trans, rt; /* ... */ glm_mul(trans, rot, rt); /* inline */ glmc_mul(trans, rot, rt); /* call from library */ Most of math functions are optimized manualy with SSE2 if available, if not? Dont worry there are non-sse versions of all operations You can pass matrices and vectors as array to functions rather than get address. mat4 m = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; glm_translate(m, (vec3){1.0f, 0.0f, 0.0f}); Library contains general purpose mat4 mul and inverse functions, and also contains some special forms (optimized) of these functions for affine transformations' matrices. If you want to multiply two affine transformation matrices you can use glm_mul instead of glm_mat4_mul and glm_inv_tr (ROT + TR) instead glm_mat4_inv /* multiplication */ mat4 modelMat; glm_mul(T, R, modelMat); /* othonormal rot + tr matrix inverse (rigid-body) */ glm_inv_tr(modelMat); Struct API The struct API works as follows, note the s suffix on types, the glms_ prefix on functions and the GLMS_ prefix on constants: #include <cglm/struct.h> mat4s mat = GLMS_MAT4_IDENTITY_INIT; mat4s inv = glms_mat4_inv(mat); Struct functions generally take their parameters as values and return their results, rather than taking pointers and writing to out parameters. That means your parameters can usually be const, if you're into that. The types used are actually unions that allow access to the same data multiple ways. One of those ways involves anonymous structures, available since C11. MSVC also supports it for earlier C versions out of the box and GCC/Clang do if you enable -fms-extensions. To explicitly enable these anonymous structures, #define CGLM_USE_ANONYMOUS_STRUCT to 1, to disable them, to 0. For backward compatibility, you can also #define CGLM_NO_ANONYMOUS_STRUCT (value is irrelevant) to disable them. If you don't specify explicitly, cglm will do a best guess based on your compiler and the C version you're using. Build CMake (All platforms) $ mkdir build $ cd build $ cmake .. # [Optional] -DCGLM_SHARED=ON $ make $ sudo make install # [Optional] Cmake options with Defaults: option(CGLM_SHARED "Shared build" ON) option(CGLM_STATIC "Static build" OFF) option(CGLM_USE_C99 "" OFF) # C11 option(CGLM_USE_TEST "Enable Tests" OFF) # for make check - make test Use with your CMake project - Example: cmake_minimum_required(VERSION 3.8.2) project(<Your Project Name>) add_executable(${PROJECT_NAME} src/main.c) target_link_libraries(${LIBRARY_NAME} PRIVATE cglm) add_subdirectory(external/cglm/) # or you can use find_package to configure cglm Meson (All platforms) $ meson build # [Optional] --default-library=static $ cd build $ ninja $ sudo ninja install # [Optional] Meson options with Defaults: c_std=c11 buildtype=release default_library=shared enable_tests=false # to run tests: ninja test Use with your Meson project - Example: # Clone cglm or create a cglm.wrap under <source_root>/subprojects project('name', 'c') cglm_dep = dependency('cglm', fallback : 'cglm', 'cglm_dep') executable('exe', 'src/main.c', dependencies : cglm_dep) Swift (Swift Package Manager) Currently only default build options are supported. Add cglm dependency to your project: ... Package( ... dependencies: [ ... .package(url: "", .branch("master")), ] ... ) Now add cgml as a dependency to your target. Product choices are: - cglm for inlined version of the library which can be linked only statically - cglmc for a compiled version of the library with no linking limitation ... .target( ... dependencies: [ ... .product(name: "cglm", package: "cglm"), ] ... ) ... Unix (Autotools) $ sh autogen.sh $ ./configure $ make $ make check # [Optional] $ [sudo] make install # [Optional] This will also install pkg-config files so you can use pkg-config --cflags cglm and pkg-config --libs cglm to retrieve compiler and linker flags. The files will be installed into the given prefix (usually /usr/local by default on Linux), but your pkg-config may not be configured to actually check there. You can figure out where it's looking by running pkg-config --variable pc_path pkg-config and change the path the files are installed to via ./configure --with-pkgconfigdir=/your/path. Alternatively, you can add the prefix path to your PKG_CONFIG_PATH environment variable. Windows (MSBuild) Windows related build file and project files are located in win folder, make sure you are inside cglm/win folder. Code Analysis is enabled, so it may take awhile to build. $ cd win $ .\build.bat if msbuild won't work (because of multi version VS) then try to build with devenv: $ devenv cglm.sln /Build Release Running Tests on Windows You can see test project in same visual studio solution file. It is enough to run that project to run tests. Building Docs First you need install Sphinx: then: $ cd docs $ sphinx-build source build it will compile docs into build folder, you can run index.html inside that function. How to use If you want to use the inline versions of functions, then include the main header #include <cglm/cglm.h> the header will include all headers. Then call the func you want e.g. rotate vector by axis: glm_vec3_rotate(v1, glm_rad(45), (vec3){1.0f, 0.0f, 0.0f}); some functions are overloaded :) e.g you can normalize vector: glm_vec3_normalize(vec); this will normalize vec and store normalized vector into vec but if you will store normalized vector into another vector do this: glm_vec3_normalize_to(vec, result); like this function you may see _to postfix, this functions store results to another variables and save temp memory to call pre-compiled versions include header with c postfix, c means call. Pre-compiled versions are just wrappers. #include <cglm/call.h> this header will include all headers with c postfix. You need to call functions with c posfix: glmc_vec3_normalize(vec); Function usage and parameters are documented inside related headers. You may see same parameter passed twice in some examples like this: glm_mat4_mul(m1, m2, m1); /* or */ glm_mat4_mul(m1, m1, m1); the first two parameter are [in] and the last one is [out] parameter. After multiplying m1 and m2, the result is stored in m1. This is why we send m1 twice. You may store the result in a different matrix, this is just an example. Example: Computing MVP matrix Option 1 mat4 proj, view, model, mvp; /* init proj, view and model ... */ glm_mat4_mul(proj, view, viewProj); glm_mat4_mul(viewProj, model, mvp); Option 2 mat4 proj, view, model, mvp; /* init proj, view and model ... */ glm_mat4_mulN((mat4 *[]){&proj, &view, &model}, 3, mvp); How to send matrix to OpenGL mat4 is array of vec4 and vec4 is array of floats. glUniformMatrix4fv functions accecpts float* as value (last param), so you can cast mat4 to float* or you can pass first column of matrix as beginning of memory of matrix: Option 1: Send first column glUniformMatrix4fv(location, 1, GL_FALSE, matrix[0]); /* array of matrices */ glUniformMatrix4fv(location, 1, GL_FALSE, matrix[0][0]); Option 2: Cast matrix to pointer type (also valid for multiple dimensional arrays) glUniformMatrix4fv(location, 1, GL_FALSE, (float *)matrix); You can pass matrices the same way to other APIs e.g. Vulkan, DX... Notes - This library uses float types only, does not support Integers, Double... yet - If headers are not working properly with your compiler, IDE please open an issue, because I'm using GCC and clang to test it maybe sometimes MSVC TODO: - ☐ Unit tests (In Progress) - ☐ Unit tests for comparing cglm with glm results - ☑ Add version info - ☐ Unaligned operations (e.g. glm_umat4_mul) - ☑ Extra documentation - ☐ ARM Neon Arch (In Progress). check the LICENSE file Github You may find interesting Releases v0.7.9: ARM Neon + Improvements - 2020-11-18T20:21:53 New Features: - arm neon: support transpose mat4 with neon - arm neon: multiply mat4 with vec4 - Swift Package Manager support, swiftpm package file with module map ( thanks to @smumryakW ) - meson: add 'install' option ( thanks to @Akaricchi ) This is useful for people who want to use cglm as a meson subproject without polluting the main project's install target. Bugfixes and Improvements: - arm neon: move neon-scale to simd header - fix docs for glm_vec2() ( thanks to @emersion ) - simd/x86: fix -Wcast-align warnings (gcc/clang) ( thanks to @Akaricchi ) This modifies glmm_{load,store}3 functions to make the compiler assume the v pointer is appropriately aligned for the type it is being cast to. Not tested with CGLM_ALL_UNALIGNED, but it probably doesn't matter.
https://swiftpack.co/package/recp/cglm
CC-MAIN-2021-10
refinedweb
2,008
52.7
Fundamentals of Front-End Django mkdev.me ・8 min read While Django is useful for writing APIs, its main purpose is as a framework for creating full websites. Rendering HTML is one of Django's fundamental abilities, and it uses Jinja templates to make writing flexible, reusable webpages straightforward. This article will teach you how to make a basic website with Django; we will create a login-protected sales dashboard. This project will demonstrate essential techniques of web development with Django: writing views for HTML, authentication with forms, showing data from the DB, and including static assets. This article will take an iterative approach to developing the webpage. You can start with Python 3 and Django 2.2 installed and follow along, or you can skip ahead and clone the final version from GitHub. If you're building along with me, start by running django-admin startproject dashboard. cd dashboard to enter the directory then python manage.py startapp core will create the app. Make sure to add 'core.apps.CoreConfig' to INSTALLED_APPS in settings.py. From there, you will be able to follow along by modifying the individual files. Whether you started by cloning the project or creating your own, make sure you run python manage.py migrate and python manage.py createsuperuser to finish setup. Run python manage.py runserver to start the Django site. We'll start by writing a simple view for rendering HTML in a browser. Django supports function-based views and class-based views. In these examples we will use class-based views but that decision comes down to personal preference as both provide the same features with different syntax. Class-based views are most useful when you want to support multiple interactions with a single URL, for example, if you need to support several HTTP methods. In this article, we're practicing Django, not HTML or CSS. Thus, we're going to use a fantastic open-source template from Start Bootstrap. The template will provide us with all of the HTML, CSS, and JS that we need for this exercise, allowing us to focus on the Django. If you are starting from scratch, download the template and copy the index.html and the login.html files into /core/templates. While we will leave a lot of the functionality in these templates as placeholders, they will help us write an interactive website. After saving the template to "/core/templates/index.html," we can use the following view in "/core/views.py" to render the page. from django.shortcuts import render from django.views import View class Index(View): template = 'index.html' def get(self, request): return render(request, self.template) Then, add the route to "/dashboard/urls.py" as follows: from django.contrib import admin from django.urls import path from core import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Index.as_view(), name='index') ] With the view written, when we run the server and navigate to, we see the page. Right now, the page doesn't look very good. Fortunately, the template included a bunch of static assets (CSS, JavaScript, and other files) that we can include to improve the site. To do so, first make a folder "static" under "core," then copy the folders "css," "js," and "vendor" into static. Finally, within the html page, you need to prepend "/static/" to the paths of the three CSS imports in the header and the nine JavaScript imports in the footer. Afterwards, the page looks much better. Once we can properly see the contents of the page, it turns out that there is a lot of (fake) sensitive data here! Let's restrict access by implementing a login page, which will serve as a great introduction to using forms within webpages in Django. Start by copying the "login.html" template in to the same "core/templates/" folder as "index.html." You will also want to make the same change as before to the two CSS imports and the three JavaScript sources. We'll add a route and view to support this new page. In urls.py: path('login', views.Login.as_view(), name='login'), In views.py: class Login(View): template = 'login.html' def get(self, request): return render(request, self.template) You'll note that for the moment our login view is nearly identical to our index view. That will soon change to support the actual page. Let's visit the login page at. Try to sign in using the superuser credentials that you created earlier. While the page looks great, it doesn't do anything yet. For that, we will need to use a form. Fortunately, Django provides a great default AuthenticationForm that accepts a username and password. We can add that to the view as follows: from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, authenticate class Login(View): template = 'login.html' def get(self, request): form = AuthenticationForm() return render(request, self.template, {'form': form}) def post(self, request): form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/') else: return render(request, self.template, {'form': form}) This will also require some modifications to the HTML of the login page. Django supports Jinja templating out of the box. Jinja templating is an extension of HTML that allows you include data with a double bracket {{ data }} and expressions with similar syntax {% expression %}. We will use Jinja tags to incorporate the form into the HTML page. <form method="post" action="/login/"> {% csrf_token %} <div class="form-group"> <div class="form-label-group"> {{ form.username }} </div> </div> <div class="form-group"> <div class="form-label-group"> {{ form.password }} </div> </div> <button class="btn btn-primary btn-block" type="submit">Login</button> </form> We can add some css by including this script afterwards. Because Jinja elements are rendered into HTML server-side, we can rely on the element ids existing in the DOM by the time this script runs on the client. <script> document.getElementById("id_username").classList.add("form-control"); document.getElementById("id_password").classList.add("form-control"); document.getElementById("id_username").placeholder = "Username"; document.getElementById("id_password").placeholder = "Password"; document.getElementById("id_username").type = "text"; document.getElementById("id_password").type = "password"; document.getElementById("id_username").required = "required"; document.getElementById("id_password").required = "required"; document.getElementById("id_username").autofocus = "autofocus"; </script> After these changes, visiting the login page will allow us to sign in and view the main dashboard. However, eagle-eyed readers will notice that we have yet to implement any protections for the dashboard. Indeed, anyone could still visit the index and view all of the sensitive information there. Thus, we have to inherit another class in the Index view. from django.contrib.auth.mixins import LoginRequiredMixin class Index(LoginRequiredMixin, View): template = 'index.html' login_url = '/login/' def get(self, request): return render(request, self.template) The LoginRequiredMixin class prevents anyone but authenticated users from accessing the pages that it protects. If someone tries to go to the index before signing in, it will conveniently redirect them to the login page to authenticate themselves. We've used Jinja to incorporate a form; we can also use it to avoid repeated code. Right now, we only have two html pages, but a full implementation of this application would have dozens. Rather than copying and pasting common elements, we can inherit the header from a base template. We'll start by making a new file, "base.html," in "core/templates." This file will include common header information between the two pages. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>{% block title %}{% endblock %}</title> <!-- Custom fonts for this template--> <link href="/static/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="/static/vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> {% block links %} {% endblock %} </head> {% block body %} {% endblock %} </html> Then, future pages can use the following syntax from the modified "index.html." {% extends "base.html" %} {% block title %}Employee Dashboard{% endblock %} {% block links %} <!-- Custom styles for this template--> <link href="/static/css/sb-admin.css" rel="stylesheet"> {% endblock %} {% block body %} <!--html goes here--> {% endblock %} We have one more place to apply Jinja templating in the home page. Currently, all of the figures in the table are hard-coded into the HTML, requiring editing the webpage itself whenever the data changes. Instead, we can store that data in our database and pass it to the view. This will also save us nearly 500 lines of manual HTML with the current data. First, we need a model to represent employees in the database. In "core/models.py", we define an employee as follows. from django.db import models class Employee(models.Model): name = models.CharField(max_length=150) position = models.CharField(max_length=150) office = models.CharField(max_length=150) age = models.PositiveIntegerField() start_date = models.DateField() salary = models.PositiveIntegerField() def __str__(self): return self.name Make sure you register the model in "core/admin.py." from django.contrib import admin from .models import Employee class EmployeeAdmin(admin.ModelAdmin): list_display = [f.name for f in Employee._meta.fields] admin.site.register(Employee, EmployeeAdmin) With the model written and registered, we can make and run migrations (quit the server, python manage.py makemigrations, python manage.py migrate, python manage.py runserver). Navigate to /admin and click on the employees table. Click "Add Employee" in the upper right corner and enter whatever data you want in the form. Do this a few more times until you have a small fake company. Then, return to our "views.py" and modify Index to pass the employee database into the HTML file as a QuerySet. def get(self, request): employees = Employee.objects.all() return render(request, self.template, {'employees': employees}) Finally, delete the entire fake table in "index.html" and replace it with a for loop over the data we entered into the database. <tbody> {% for employee in employees %} <tr> <td>{{ employee.name }}</td> <td>{{ employee.position }}</td> <td>{{ employee.office }}</td> <td>{{ employee.age }}</td> <td>{{ employee.start_date }}</td> <td>${{ employee.salary }}</td> </tr> {% endfor %} </tbody> Django creates the index by rendering from our database instead of simply returning the filler data. All of the search and ordering features still work exactly as they used to, the only difference is that the html is generated server-side from the database rather than hard-coded. We have now seen several powerful patterns for creating web pages with Django and Jinja. Using templates and extensions allows us to reuse common code between pages. Forms allow us to securely collect and transmit user data (when the website is served over HTTPS). We can use server-side rendering to include data in the HTML and send it to the client. These fundamental patterns are the essential skills that will let you create a wide array of web pages in Django. This is an mkdev article written by Philip Kiely. You can hire our Python mentors to learn Python & Django yourself. Enforcing Single Responsibility Principle in Python Single Responsibility Principle (or SRP) is one of the most important concepts in software development. The main idea of this concept is: all pieces of software must have only a single responsibility. Your article is a really great introduction to Django development but I believe that you are mistaken about the template engine. The default template engine in Django is the Django Template Engine. It is, in some respects, similar to Jinja but it is not Jinja. However, Jinja is an optional template engine that can be used and that Django provides built in support for. From what I can tell you do not provide any explanation about switching to Jinja nor do you appear to be using any Jinja specific markup in your templates. If you want information on how to configure Django to use Jinja you should see these documents: docs.djangoproject.com/en/2.2/topi... There actually plenty of ways to build a more efficient Django Front End. I would recommend people check this out: udemy.com/course/build-a-user-auth... This is cool for nwbiee
https://dev.to/mkdev/fundamentals-of-front-end-django-b2k
CC-MAIN-2019-39
refinedweb
2,043
52.05
Dedicated to everyone who dreams big ACKNOWLEDGMENTS I would like to express my sincere gratitude to Lenny Brown, creative director of the Topps Company, whom I consider to be the maestro of the comics, and without whose help this book might not have been written. Special thanks goes to Jim Salicrup, a former editor of Marvel Comics and now associate publisher and editor-in-chief of Topps Comics, for sharing his time and insights with my readers. Thanks also to Darryl Banks and Rich Faber for their contribution to this book. A Note to Readers, Parents, and Teachers Some art materials are unsuitable for young children to use. Children should only use art materials that are labeled as nontoxic and carry the statement "Conforms to ASTM D-4236" or similar wording. All purchase of art materials for and art activities of children under the age of 12 should be supervised by an adult. Senior Editor. Candace Raney Edited by Joy Aqullino Designed by Bob Fillie, Graphiti Graphics Graphic production by Hector Campbell and Sharon Kaplan Chapter title art by Carmine Vecchio Copyright Š1995 by Art Studio, LLC First published in 1995 by Watson-Guptill Publications a division of VNU Business Media, Inc., 770 Broadway, New York, NY 10003 Library of Congress Cataloging-in-Publication Data Hart, Christopher How to draw comic book heroes and villains/Christopher Hart. .p. cm. Includes index. Summary. Covers how to create your own original comic book characters, draw fight scenes, design special powers, and invent imaginary creatures, with a section on how the comic business works. ISBN 0-8230-2245-5 1. Cartooning-Technique-Juvenile literature. 2. Comic books, strips, etc.-Technique-Juvenile literature. 3. Heroes-Caricatures and cartoons-Juvenile literature. [1. Cartoons and comics. 2. Cartooning-Technique. 3. Drawing-Technique.] I Title NC1764.H371995_ 741.5-dc20 95-36859 CIP AC All rights reserved. No part of this publication may be reproduced or used in any form or by any means-graphic, electronic, or mechanical, including photocopying, recording, taping,or information storage and retrieval systems-without written permission of the publisher Manufactured in the United States of America First printing, 1995 10 11 12 13 14 / 06 05 04 03 02 CONTENTS INTRODUCTION THE CONTRIBUTING ARTISTS AWESOME ANATOMY "Pumping up" your drawing skills for the heroic head and figure ZAP! POW! CRUNCH! Creating convincing fight scenes FANTASTIC FOES Inventing bizarre villains, monsters, and mutants BEAUTIFUL BUT DEADLY Drawing ravishing and resourceful heroines-and enticing adversaries POWERFUL PERSPECTIVE Using the rules of perspective to enhance your drawings THE BIG BANG! How and when to use special effects THE PLOT THICKENS The visual art of storytelling SECRETS OF THE PROS Mysteries of inking, shading, and folds revealed FIRE POWER Advanced weaponry and assault vehicles MAKING IT IN THE BIZ The ins and outs of the comic book business I Introduction H ow to Draw Comic Book Heroes and Villains is the ultimate book for anyone aspiring to be a professional comic book illustrator. I'm proud to tell you that these pages feature the work of some of the best talents in the comic book field. You'll. Also, there's a chapter devoted to answering the questions that every serious-minded aspiring artist has. You'll learn what to include in a winning portfolio, what the shortcuts are to landing your first job, and how the business really works. For instance, did you know that the person who draws the covers is rarely the same person who draws the interior pages? This book also features an exclusive interview with Jim Salicrup, the renowned former Marvel editor, and now associate publisher and editor-in-chief, of Topps Comics. He shares his insights on the business as he tells you exactly what qualities he and other comic book editors look for when hiring a new artist. Pencil, paper. And this book. And you're on your way. Dare. THE CONTRIBUTING ARTISTS FRANK McLAUGHLIN Celebrated pen-and-ink artist McLaughlin has 35 years of experience in the comic book industry. Frank has contributed his talents to such famous comic books as Superman, Batman, Wonder Woman, and Green Arrow for DC Comics, as well as Captain America and Iron Fist for Marvel Comics and Femme Fatale for Broadway Comics. He has worked for practically every major comic book publisher, including Valiant, Defiant, Charlton, Seaboard, Dell, and Archie. GRAY MORROW Admired and envied for his ability to draw the most gorgeous women in the comic book field, Morrow has created illustrations for Playboy and Penthouse, and also has the distinction of having worked on Batman and Superman for DC Comics. He worked on the animated TV show Spider-Man, the comic strip Tarzan for United Features Syndicate, Power Rangers for Gladstone Comics, and Creepy and Eerie Comics. FRANK SPRINGER Well known throughout the industry, Springer is highly regarded for his powerful line drawings. Among his best-known work, Springer drew The Hulk, Conan the Barbarian, The Fantastic Four, Spider-Man, Sgt. Fury, and The Invaders for Marvel, as well as The Flash for DC, Elvira for Claypool Comics, and The Adventures of Hedley Kase for Sports Illustrated Kids. J. ALEX MORRISSEY One of the outstanding new artists on the cutting edge of the industry, Morrissey has drawn many Marvel titles, including The Punisher Ghost Rider, Cloak and Dagger, Cage, Iron Fist, and Power Pack, as well as Division 13 for Dark Horse Comics. F YOU WANT TO INFLICT MAXIMUM DEVISTATION on bad guys, then regular anatomy just won’t do. You’ve got to pump up your heroes to awesome proportions. In this chapter, you’ll learn exactly how the pros transform ordinary anatomy into super-powered anatomy. the classic hero’s head B ecause professional comic book artists don't always have access to live models, they've created a system for drawing a perfectly proportioned head. The proportions used in this method of drawing the head can be seen in some of the world's most popular comic book heroes. To make it easier to see how we arrive at these proportions, start by placing the head inside of a rectangle. Then think in terms of halves. Divide the rectangle in half with a horizontal guideline that's where the eyes go. Place the end of the nose halfway between the eyes and the bottom of the chin. Draw the lips halfway between the end of the nose and the chin By drawing guidelines from the center of each eye to the edges of the lips, you get the correct width of the lips. The dotted lines indicate that the eyes are one eye's width apart. The details, such as wrinkles and hair, are added only after the basic form has been established. If your hero's head doesn't look right, check it against these classic proportions and adjust it accordingly. F R O N T S I D E Just as in the front view, the eyes in a side view are positioned in the middle of the head. Much of the head's mass appears behind the ear Only the front portion of the head makes up the face. The bottom of the ear and the bottom of the nose are drawn at the same height, as are the top of the ear and the contour of the eyebrow. The chin should be strong and angular. The neck is thick and muscular. SKETCHING DIFFERENT HEAD SHAPES principal parts of the head T he are the skull and the jaw. The shape of the skull is a globe-sort of. Actually, it's a globe with the sides lopped off, because the sides of a head aren't perfectly round either. Extend a line down the center of the face, then make a few marks along that line to indicate where the hairline, the eyes, the bridge of the nose, the mouth, and the chin will go. By varying the distances among these marks, you can create different characters. Another method for inventing new characters is to change the overall shape of the head. In every comic book or cartoon illustration of the head, the hairline, eyes, nose, mouth, and chin are drawn on different planes. Keep each feature fixed and locked in its own position and the face will read with clarity. facial features MEN'S N0SES AND EARS A s you draw your hero's face, consider the complex angles of his nose and ears. The nose begins at the forehead. About halfway down the nose is a slight indentation-that's where the bone ends and the cartilage begins. Although it isn't always noticeable, it is often indicated in comic book illustration because it gives a dramatic look. Pay close attention to the planes of the nose-top, sides, and bottom. If you look closely at the interior of the ear (below, right), you'll notice a tilted Y shape. Use this shape when drawing your hero in profile. The ears and the nose are the only two parts of the body that never Stop growing. Therefore, when drawing an older character, make his nose and ears larger than normal. WOMEN'S LIPS Female characters are always drawn with full lips, which gives them a pensive, moody quality. The bottom lip is usually fuller than the top one. The lips stretch horizontally around the surface of the face, so it's important to draw them as if they were wrapping around a cylinder. Do not draw the lips as straight lines. To show gleaming, bright teeth, draw the shadows between them. (The shadows should become thinner toward the front of the mouth.) Use more shadows at the edges of the mouth to give the teeth the illusion of roundness. Unless you're trying to draw an angry, frightened, or otherwise severe expression, don't draw each individual tooth. WOMEN'S EYES Breathtaking eyes increase the appeal of any female character, whether she's a good gal or a bad one. Keep in mind that the eyeball is first drawn round, not almond-shaped-it's the way the eyelid is attached to the eye that makes it look oval. The eyelid acts as a hood, creating a shadow along the top of the eyeball. The lashes on both lids become progressively thicker and darker as you work toward the eye's outer corner, though the bottom lashes are somewhat shorter. To make the eyeball appear wet, add a highlight of white to the iris. If the highlight is too big, it will make your character look like she's staring, which will also happen if you show too much eyeball and not enough eyelid. You want to show one-third eyelid to two-thirds eyeball. Get as much expression into the eyebrows as you possibly can. They are the key to conveying emotion. Unless a person is squinting or stunned, the shape of the eye doesn't change as dramatically as the eyebrows, which can be raised, lowered, furrowed, or arched. How to draw hair own hair doesn't look like a hat-why should your Y our character's? First draw the head without hair, then decide what the hair style should be. Lines for hair should flow away from the scalp and continue in the direction(s) set by the particular style. Instead of trying to draw each individual hair, draw large shapes and tufts. Don't make the hair appear too uniform. For women, especially blondes, you can create the illusion of luster by bunching some black lines together, provided that these lines also flow in the same direction as the hair. MEN'S HAIR STYLES Your character can get pulverized in a fight scene, thrown through an exploding building, and dumped in a toxic waste dump, but his hair's still gotta look good. What's more, you've got to make sure that your hero's hair style stays the same throughout the course of his career. Occasionally, a comic book's editorial staff will decide to change or update a character's appearance, in which case the entire character, including his costume, is reevaluated. Notice how this character's careless hairstyle (left) is actually well plotted. Shown on the opposite page are some standard types. You can make up your own, or combine the features of several. WOMEN'S HAIR STYLES There's a wide range of hair styles for women, far more than for men. The one you choose for your character should complement and harmonize with her appearance. A woman's hair is drawn with longer, more flowing strokes than a man's. Notice how the hair cascades off the shoulders (left). Notice, too, how the hairline starts higher on the female forehead, emphasizing its roundness. DON’T outline the hair like a hat---it's not a helmet! CASUAL WILD HIPSTER WAVY WITH A FOREHEAD CURL NEAT BOB FULL WITH A FOREHEAD CURL LONG AND WAVY LONG AND STRAIGHT WITH BANGS PONYTAIL TIED BACK TRENDY POPULAR COMIC BOOK EXPRESSIONS are as many facial expressions as there are T here faces, but some are better suited to comic book illustration than others. You could draw a guy with his eyes popping out and his jaw on the floor, but chances are you'd be better off working in an DISDAIN (ANNOYANCE) Eyebrows curve downward, then level off. The line of the mouth is small and taut. The jaw is wide because the teeth are clenched. SURPRISE animation studio-or locked away where you wouldn't be a danger to yourself or others. Draw only the lines that actually create the expression. The width of the jaw will vary, depending on whether the character is clenching his teeth. Lines on the forehead repeat the shape of the eyebrows, which are severely arched. The face elongates as the mouth opens. RAGE Eyebrows plunge dramatically downward, then flare out at the edges. The teeth are clenched and visible; nostrils are flared. DETERMINATION. Grimaces B close-mouthed, shown from various angles. ANATOMICAL PROPORTIONS drawing a figure, the head is used as the basic unit of W hen measurement. According to some authorities, the average person is 61/2 heads high, while other artists use a standard height of 71/ heads. The proportions of comic book heroes are extremely exaggerated. These figures are typically drawn 8 heads high. The smaller the head, the more powerful the body will appear in contrast. guy is 9 heads high-positively huge. These T his proportions make the figure look massive and unreal-desirable qualities for a comic book hero. Some brutes have been drawn as much as 15 or even 20 heads high, which are highly stylized proportions. BODY BASICS ook at the basic lines of the body. All its forces L. BUILDING AN ACTION POSE C omic book heroes and villains are made to move, jump, leap, and soar. But when you start to position your figure in dynamic poses, things can get tricky-unless you've taken care to maintain its essential building blocks. This is done by taking a moment to sketch out a solid rib cage, collar bone, pelvis, and the other major bones before executing the finished drawing. Contrary to what your instincts might tell you, muscles alone do not make a character appear sturdy. Solid bone structure does. That's because all muscles are attached to bones, so unless you have a solid foundation of bones, those muscles will appear rubbery. But that doesn't mean that you must render a skeleton in painstaking detail. It can be done quickly, in a sketchy shorthand, as in these fine examples. While it's true that you'll erase many of these preliminary steps when you do the final "clean" version of your hero, your drawings will benefit immeasurably from them. THE ACTION FIGURE, STEP BY STEP N ow let's apply what we've learned, taking it step by step, and finish with a detailed figure. Most pros start with the second step, because the first step has become second nature. But no pro starts with the precision of the fifth step. They always sketch roughly first. After you've gotten the hang of it, you'll begin at the second step, too. Start with a simple line drawing. Keep it loose. Try to feel the flow and energy of the pose. Sketch the large muscles and areas first. If a form has two sections, like an arm, sketch each section separately: first the upper arm, then the forearm. Sketch the upper leg, then the lower leg. Sketch the rib cage separately from the waist and so on. Continue to define the form in this way. This will give your drawing more authority. Now start to smooth out the figure by erasing the construction lines. The care you've taken with the underlying framework has paid off in a solidlooking figure. Draw the hands and feet in detail, and begin to indicate some shading possibilities. Suit your character up in an eyecatching outfit and work out the details. The pros always add the fine points last. The beginner typically focuses on the details of the costume and tries to draw them early on, but keep in mind that the figure always suffers as a result. THE HEROIC FEMALE FIGURE T he heroic female figure has a fairly wide collarbone, resulting in square, well-muscled shoulders. A woman's rib cage, bones, and all of her muscles are smaller than a man's. Her torso tapers sharply at the waist, but her pelvis is wider. As a rule, comic book women are drawn with more curves, while the men are drawn with more heavy angles. For detailed information on how to draw comic book heroines, see "Beautiful But Deadly," pages 56-75. BODY LINES The center of balance is an imaginary vertical line drawn through the body. Half of the body's weight is on either side of the line, which maintains the body's balance. If the weight isn't distributed evenly, the figure will fall down, bang her head, and sue. You don't want that. Sometimes, though, it's okay, even necessary, to draw a character with his or her weight off balance. Can you think of an example? How about when a character is in motion? The act of walking is, in reality, a process of falling and catching yourself. If you were always in perfect balance you wouldn't be able to walk, because you couldn't transfer your weight from one foot to the other. There are shoulder and hip lines to be aware of, too. This means that as one shoulder dips, the hip on that side of the body rises to compensate. Also, each time a limb or body mass extends past the center of balance, there must be an equal and opposite movement on the other side of the figure so that its balance is maintained. ARM FORWARD ARM FORWARD ARM BACK ARM BACK CENTER OF BALANCE SHOULDER LINE EXCEPTIONS TO THE RULE HIP LINE SHOULDER/HIP DYNAMICS Notice that this figure's straight leg (her left one) is the weight-bearing leg. It pushes the hips up on that side. To compensate, the shoulder on the same side dips down. Conversely, on the other side, her bent leg is supporting little of her body weight, therefore, the hip on that side dips down. To compensate, the shoulder on the same side rises. We all make these adjustments in our posture constantly, but subconsciously. The human body is very versatile. Some extreme poses can shift the body so that both the shoulders and the hips are at the same angle. Don't be afraid to break the rules if it will make your poses more expressive. ANATOMY OF THE HAND M any above. Familiarize yourself with the arrangement of the bones and joints. DRAWING HANDS AT VARIOUS ANGLES Start with a big shape, then break it down into smaller shapes. Make sure to practice some turnarounds, an artist's term for rotating an object 360 degrees and drawing it from every angle (see pages 30-31). Once you've gained some experience, you can draw "expressions" of the hand that are just as effective at conveying emotion as the face. Note the various planes of the hand. BASIC HAND POSES L earn these basic hand poses and store them in your arsenal of techniques. Notice how all the joints of the fingers are apparent, even when they aren't bent. THE FINGER POINT Best used by an angry boss threatening to fire a reporter. Note how both the heel of the thumb and part of the palm heel are visible in this pose. THE OPEN HAND This is a standard hand pose, for when you don't need a specific hand gesture. Note how flat the tips of the fingers appear THE RELAXED HAND STAGGERED FINGERS For a character who is explaining something. Note the large knuckle at the base of the thumb. Use this one for heroes or villains who have been knocked unconscious by a blow or disabled by nerve gas. Note the severe turn at the wrist, which gives it its limp appearance. To make a more in-depth study of the hand and its many poses, you can purchase a hand mannequin at an art supply store. THE FIST Lifted in rage, or in combat. Note how the thumb overlaps the first two fingers, and how well defined the heel of the palm is. HEROIC HANDS rtist Frank McLaughlin says, "The key to all comic book-style illustration is to exaggerate the form at the outset, then tone down whatever looks too extreme. Don't draw realistically and then try to soup it up. Your drawing will look overworked that way." Below are some helpful hints on drawing the heroic hand. The webbing between fingers strains into straight lines as fingers are spread. The tips of the fingers bend at a more extreme angle than on a normal hand. Massive knuckles on a fist can inflict maximum damage. A powerful fist is always tilted downward, never up. Shading the finger pads at the beginning of each joint gives this open hand a feeling of drama and dimension. This dramatic hand gesture has many planes. The wrist is straight, then drops down on a diagonal to the fingers, which bend in three more angles. Notice how the hand points in perspective. The index finger diminishes in size as it recedes into the distance. FEMALE HANDS While men's nails are drawn as squares, the nails of women are drawn as ovals. F emale hands are more slender and graceful than their male counterpart's. Female hand poses tend to be less extreme, and the palm's thumb muscle is less pronounced. Avoid heavy knuckle lines on a female hand, and leave off the rings and jewelry unless they're part of a secret weapon or power. TURNAROUNDS Y ou must be able to draw your character from every angle. The cut of the costume is different in the front than it is in the back and on the sides. The posture is different, and the muscle groupings that the costume reveals are different, too. The look of the hair and the way that it hangs are also very different. Before you actually begin to draw a story, make sure you've familiarized yourself with every angle of your character's appearance. That way, you won't feel the need to favor the easiest angle. In comic books, excitement is created by varying the angles of the figure on the page. If you can't draw those angles, the excitement will be irretrievably lost. ET’S TAKE THE GLOVES OFF! Comic book fans will wade through any story if there's the promise of a really good fight scene at the end. These characters are built for one thing only---and I don't mean dancing! The key to drawing a great fight scene is understanding how the human figure adapts to motion and momentum. So take off your gloves and let's at 'em! DEVASTATING PUNCHES A devastating punch is an important part of any character's repertoire. A comic book punch consists of two elements: 1. THE WINDUP Imagine that the character's punching hand weighs 50 pounds. As the windup begins, the entire weight of the body is pulled toward the punching hand. 2. THE FOLLOW-THROUGH The follow-through is indicated by the fully extended punching arm and its accompanying speed lines. Note also that the punch is shown after the point of impact. This is the key to a great punch. The point of impact is indicated solely by a starburst. As artist Frank Springer puts it, "The punch should look like it hurts!" Notice how the victim is hurled back by the force, his knees buckling and his head snapping back. THE WRONG WAY TO SHOW A PUNCH This sketch illustrates how not to show a punch. See how weak the punch looks when it's drawn at the exact point of impact? Skip this interim step completely when drawing fight scenes. The follow-through is the most dramatic part of the punch. CLEAN PUNCHES T here are no small punches in a comic book fight. Every punch is a haymaker. Because fight scenes frequently show overlapping figures (as in this series of sketches), be sure to space the characters so that the reader can easily see the completed punch at full extension. Short uppercuts and hooks aren't dramatic. THE LUNGE ATTACK W e're all nice guys in this business, but sometimes we want our characters to go for the kill. Any lunge or attack movement needs to be swift, sudden, and totally forward-moving. Notice that not all of this character's body is attacking at the same time. His hands are out in front, followed by his shoulders, then his torso, and finally by his launching foot. This creates the feeling of movement, like a lion pouncing. It is visually powerful. You can use this technique whether your character is lunging empty-handed, with his fist, or with a weapon. Artist Frank McLaughlin draws some of the meanest-looking figures in the business. In fact, this is a picture of Frank himself before he's had his morning cup of coffee. LEANING INTO THE PUNCH OR KICK I t may seem natural to lean back to throw a kick. But to do so means you're throwing your energy away from the target. Your character should lean into his punch or kick, thrusting all his weight forward. The character who lands the hard punch or kick has both his fists tightly clenched, while the character receiving the blow slackens his fists slightly, a sign of weakness. You can demonstrate the impact on the opponent most clearly by drawing his chin up in the air, as if he'd gotten socked right there. This is a clear sign that the punch was effective. THE JUDO SHOULDER THROW E very comic book artist should know a few martial arts moves. It's a popular belief that a martial arts expert can take on many ordinary street fighters at one time. This makes for great drama, and also boosts enrollment in local karate studios. The judo throw is a stunning way to end a battle by literally tossing an opponent into the air and onto his back. Let's break down the various moves: The Defender sidesteps the Attacker's punch while simultaneously grabbing his punching arm. The Defender begins to turn forward, and as he does, gives a tug, causing the Attacker to lose his balance. The Defender dips his shoulder, getting ready to position it under the Attacker's arm. The Defender now shoves his shoulder under the Attacker’s arm. Now it’s bye-bye to the foolish Attacker, because at this point, it’s all academic. The Defender pitches forward and the Attacker sails overhead... ...and just before the Attacker hits the ground, the Defender lets go, which causes the Attacker to hit the ground harder. Phew! Another dastardly villain has been disposed of. david vs. goliath A n unfair fight is a very dramatic device, and has been since time immemorial. Casting the hero as the underdog, who must win against insurmountable odds, makes us want to root for him, and if he starts the scene by ostensibly fighting a losing battle, only to come from behind to win through sheer heart, the fight will be truly exciting. Make sure the giant nemesis uses his physical advantages of strength and size in the fight scene. When a towering brute fights a smaller man, the latter is usually the hero. The balance of power Y ou don't always have to throw a punch to win a fight-provided you're a comic book character. Super powers, such as body force fields, can repel an attack, hurling someone even farther than the most powerful punch. The most important thing to remember when designing super powers for your characters is this: A character should also have a weakness. Why is that so important? Think about it. If your character is so strong that he or she can't possibly be beaten, then why watch the fight? Even Superman needed Kryptonite to heighten the suspense. The weakness doesn't have to be physical-your character could have a thing for a "bad girl." Design a weakness that's as original as the special powers you've invented. ILLAINS TODAY ARE NOT JUST BAD GUYS. They're vile, repulsive, wicked, sadistic, insane, evil, bad guys. They're worse than the guy who's dating your sister. Here's an important secret about comic book villains: The more powerful and formidable the villain, the greater the hero. Villains have a wonderful time being wicked. So have fun creating an impressive villain. After all, it's an evil job, but someone's got to do it! THE RENEGADE SOLDIER A tough guy with a gun and an attitude. Hey, wouldn't you be pissed if someone blew up your world? These guys roam the earth alone or in splintered battalions after the rubble clears from a nuclear world war. Armed to the teeth, grubby, and mean, they have only one aim: to survive, by any means necessary. Notice that the soldier's gun— and in case you haven't noticed, that's no pistol!-is backed up by ammo hidden all over his uniform, in his belt, shoulder packs, and knee pads. SWORD-AND-SORCERY VILLAINS S word and sorcery is a popular comic book genre. The most notable series of this type is Conan the Barbarian. Villains of the sword-and-scorcery ilk are hulking, prehistoric hunters and fierce, tribal warriors. Clothe them in animal skins and ritualistic ornaments. FORCES OF EVIL I f you ask any Hollywood star what role he or she enjoyed playing the most, the answer will inevitably be, "The bad guy." Bad guys are just more fun because they're so wicked and single-minded. They don't have to worry about being nice. Or playing fair. However, they can be quite charming, elegant, polite—even fastidious. And deadly. Why are we so fascinated with bad guys? Maybe because bad guys come from primitive, subconscious images of evil. The things that go bump in the night-rats, bats, snakes, lizards, wolves, and spiders. If it can make your skin crawl, it can make a great bad guy. Don't be literal in transforming creepy crawlies into villains. The days of giant ants that devour a city are over. Use nightmarish images to suggest a villainous personality. A spidery black cape on a vampire-like woman is much better than giving her eight spider arms. Don't repulse your audience; lure them in. CHARACTERS-THE BADGUYS/GALS CAN BE HUMOROUS, HANDSOME OR HORRID. REFER TO YOUR FAVORITE FILMS AS A GUIDE. A TINGE OF SENSITIVITY OR COMPASSION MAKES THEM MORE BELIEVABLE. (THEY USUALLY DEPLORE VIOLENCE AND ONLY WANT TO BE ADMIRED, IF NOT LOVED.) WHEREVER POSSIBLE USE DRAMATIC LIGHTING. COSTUMING USED PARTIALLY CONCEAL OR EVEN EMPHASISE SOME INFIRMITY. LASER OPTICS, LETHAL PROSTHETICS, OR ARMED CANES OR CRUTCHES SIDELONG GLANCES, SNEERS, THIN LIPS DENOTING CRUELTY, CLAWED HANDS, CURLED LIPS, HIGH FOREHEADS, STRANGE ATTIRE AND ALMOST ANYTHING SUGGESTING CONTEMPT FOR ACCEPTED CONVENTIONS, THESE CREEPS REFUSE TO CONFORM UNLESS IT SUITS THEIR NEFARIOUS PURPOSES. INVENTING A VILLAIN C hances are, your villain started out as an average guy, just like you or me, but somewhere along the line he got dipped into a vat of toxic waste, was exposed to a strange radioactive brew, or became the victim of an industrial accident. He became embittered. Vengeful. Delusional. Insane. As a result, his appearance changed. He may have had to replace parts of his face, or they may have even mutated. So you can start by drawing an ordinary face, and by playing around with it, changing it little by little, you can transform it into the face of a consummate villain. Sometimes it's enough that the evil inside a person shows itself on his or her face. Villains don't always have to be fiery. Sometimes the dispassion they exhibit is evil, too. This is the case with a badguy scientist who cruelly and relentlessly stalks new subjects for his experiments. Take an ordinary person and see what you can contrive when you let your imagination endow him with whatever Characteristics YOU WISH WHEN DOING THE CREATING OF COMICS...”CREATIVE” IS THE OPERATIVE WORD. AS IN FILM YOU, THE ARTIST, ARE THE WHOLE SHOW. DIRECTOR, CHOREOGRAPHER, SET DESIGNER, MAKE-UP ARTIST, SPECIAL EFFECTS TECHNICIAN, THE WHOLE SHEBANG! BEASTLY VILLAINS H alf man and half beast. These villains are totally unpredictable, just like wild animals. You can combine the human form with any animal's to create a convincing foe. This type of villain gives the impression of being physically stronger than its purely human counterpart. It is especially effective if the animal you choose is a predator. A MENACING MENAGERIE Can you spot a leopard, a wolf, hawks, an ape, and a lion on this page? hollywood heavies W hen inspiration vanishes, as it sometimes does, there are ways of getting around it. Pick a silver-screen bad guy-either famous or not-so-famous-and draw a loose likeness. Then start altering his features. You can change them any way you like-make him taller or shorter, fatter or thinner, older or younger-but be sure to maintain that twinkle of villainy in his eye. You won't have to change very much before you've added a new character to your cast. dead-on copy Slightly revised memory swipe altered to represent your script’s villain. Actor reference used only as a “type.” remodeled to suit dressed to kill T he bad guys enjoy their costumes. They love their jobs and they like their uniforms. They are egomaniacs with inferiority complexes. Good guys wear their costumes out of a sense of duty, even though they're frequently no more practical than the bad guys'. When designing a costume for a bad guy, make sure it reflects his or her personality. Is it ostentatious? Dark or sexy? You decide. the movie serials and comics of the ‘30’s and ‘40’s were fond of draping villains and villainesses in cloaks and hoods. more recently, the emphasis seems to be on various kinds of armor and/or circus-type costuming. unearthly creatures E vil creatures are a recurring-and frequent-comic book device. You can find inspiration in the monstrous images of myths and fables, like the Medusa or Cyclops, or you can use your own imagination and any assortment of shapes in your drawings. A word of caution: If you create an ornate, incredibly complex creature with lots of bumps and teeth, just remember that you're going to have to draw it over and over again in every panel. Design something you can live with. Not even a mother could love these faces. Worms sprouting out of heads isn't something you see every day. Shrunken heads may also be a little excessive. But your job as a comic book artist is to elicit a response from the seasoned comic book reader, who has seen just about everything. So take it to the limit-be extreme. Horns, pointed ears, sharp teeth, scales, warts, and fur are all popular. As long as it doesn't make the drawing look cluttered, you can pile on as many of these kinds of features as you want. Design your creature's face to appear frightening at all times, regardless of expression. HAT WOULD A BOOK ABOUT COMIC BOOKS be without a chapter devoted to the gorgeous women who grace their pages? As any fan will tell you, these fabulous females are a large part of the allure of comic books. Just as male comic book heroes are depicted with an exaggerated masculinity, comic book females are drawn in a way that capitalizes on their sex appeal as well as their strength and resourcefulness. comic book beauties then... A rtist Gray Morrow, who is renowned for his illustrations of beautiful women, shares his point of view on the origins of and latest developments in designing and drawing female comic book characters. "In comics as well as in film and other forms of fiction, the femme fatales generally fall into a few stereotypical categories. The provocative good/bad or all-out bad girl in comic books has been with us for quite a while. SOME HEARTHROBS OF EARLIER TIMES. SEXY? WELL, GRAMPS THOUGHT SO. NOTE THE BLACK LIPSTICK, A DEVICE LARGELY DISCARDED TODAY. ...and now “C ertainly not the first, but perhaps one of the earliest to make an indelible impression, was Milton Caniff's 'Dragon Lady.' She remains to this day a model for that eternally mysterious and fascinating example of an independent, self-reliant, and sometimes amoral, if not immoral, female, scornful of all males, except, of course, the 'Good Guy' hero. She and her clones, while somewhat varied, had many similarities." femme fatales yesterday... “T heda Bara, 'the Vamp' of silent films, raised our grandfathers' blood pressures several notches and inspired a number of look-alikes, though she was somewhat toned down in the realm of printed matter. The 'Dragon Lady' type has, in our modern lexicon, become synonymous with the 'vamp.' So how do we recreate her? theda bara, the original film vamp that inspired countless clones. for the ladies it was “The sheik”, valentino, and for the men it was theda, the “sheba”. pulchritude plus poundage ...and today “T he femme fatale must have an exquisite form. In today's more permissive media, we can get nearly as explicit as anyone would want. She should be slinky, catlike in her movements, arched eyebrows, slitted eyes, always posturing, and—even today— smoking! She doesn't give a damn about the 'big C’ or the environment. She can be big-breasted or streamlined, or even very muscular-and therefore doubly dangerous. She just might possibly be a match for the hapless hero. Her costuming should be exotic, alluring, daring, and even alien or offbeat." even with “superwomen”, excessive muscular definition is not desirable. such delineation gives a flayed or ‘ripped’ look distinctly unfeminine. try to “feel” the form and strive for proportions that suggest power without having a figure that looks like an anatomical diagram. the provocative stance, insolent or baleful stare, arch or aloof expression all server to denote her antisocial (a gun helps) personality. study your favorite sultry screen sirens to learn more from their “bag of tricks.” denizen of the street D on't bring this one home to meet your mother. Trust me on this. However, no one said you couldn't have a little fun with her on the pages of a comic book. The "tough" bad girl wears clothes that are so scanty she could cause a traffic accident in a parking lot. She is muscular, but drawn with plenty of feminine curves, lots of legs, and an attitude. She is resourceful and deceitful, and frequently has a crush on the hero, consequently leaving him with a moral dilemma: Does he stay loyal to the good girl, or give in to his darker impulses? Ah, to have such problems. slighty shady ladies G ray Morrow notes, “The good/bad girl, the tramp with a 'heart of gold,' is similar, still seductive, but a bit less obvious. She undoubtedly has designs on the hero, but realizes that because she has a 'past,' she's not worthy. Therefore, she should be depicted as torn, uncertain, and moody, yet still alluring." The classic “good girl” A ccording to Morrow, "The 'Good Girl' is the gal next door: fresh, open, a pal. She's definitely sexy, but less obvious, and less affected, than her 'bad girl' sisters. She's exuberant, perky, sympathetic, pensive, and unsophisticated. The examples below are, of course, all stereotypes, presented as takeoff points or guidelines from which you can extrapolate your own." big eyes, wide-eyed expressions, dimples, carefree or tousled hairstyles all help to define the “good girl”. also check with the women you know for make-up and fashion tips. women’s magazines can be a big help. Beauty in all shapes and colors M orrow observes, "For some strange reason-perhaps because it's a hard skill to master-many, if not most, cartoonists, when drawing their version of a pretty girl, draw virtually the same girl all the time. Clothing and hair styles are changed to make one distinguishable from another, but features and figures remain the same. Since in real life there is an astonishing variety of attractive females, it seems a shame not to indicate that on paper." all different types, all different features, all attractive. variety truly is the spice of life. note that eyebrows are not all solid black lines. liplines vary and the expressive hands add much to conveying the expressions. “A good-looking girl can be short or tall, slender or voluptuous, with a wide array of facial characteristics-a beauty mark, full or thin lips, a cleft chin, an aquiline nose, high cheekbones, full lower lashes, and so on. Look around you and take note of the fact that not all 'gorgeous babes' are cookie-cutter Barbie Doll clones.â€? mother nature is bountiful in her provision of model types. seek to make them convincing by giving them distinctive characteristics, gestures, expressions, attitudes. Costuming is rarely “sensibleâ€?, but not to worry-These gals never seem to catch cold. drawing from photos M orrow suggests: "If, for whatever reason, you don't draw from live models, there is a preponderance of photographic references available to study and draw from. This material can be invaluable in solving problems of perspective and foreshortening-and in saving time. Sometimes just 'making it up' can consume hours, and may not even pay off. Use photographs wherever applicable to create your own sirens." good gal heroes N ow let's see how we get there, step by step. Artist Frank Springer approaches the figure by starting rough in an attempt to capture it in sweeping lines. The comic book heroine has a narrow waist large rib cage, somewhat wide hips (slender hips are less attractive), and muscular legs. Note how the lines that form the hips travel downward to the tops of the feet giving a pleasing curve to the lower leg. The feet are positioned to allow for her highheeled boots, which are added later. (Just because she fights bad guys doesn't mean she isn't a fashion plate.) Shoulder flares serve no purpose except to put a little zing in her look. (Remember: In art form follows function, but in comics, form never follows function!) Even though the cape is flowing, the costume always fits snugly, as if it were painted on. That's why it's so important to concentrate on mastering anatomy. Comic book characters wear extremely revealing costumes. You just can't fake it. A llow yourself the freedom to sketch loosely while you search for the right form. All the initial work on the body pays off in the final costumed figure, which appears solid and proportional. Strong but sexy W omen with muscles are sexy. But don't overdo it and make your heroine into some massive female bodybuilder. Avoid building up the typical male bodybuilder muscles, like the biceps, triceps, pecs, and lats. Instead, give her overall tone and increased definition and size. Concentrate on her delts and quads. In this sketch, the figure is being conceived with vanishing trace lines. These are the lightly drawn horizontal lines that are sketched across the figure as a reference guide for the artist to draw in perspective. As the figure recedes into the distance (the bent leg is farther from us, and therefore recedes; the straight leg is closer to us, and therefore advances), we must make adjustments for perspective. You've no doubt noticed how a row of street lights seems to get smaller as it recedes into the distance. The human figure is affected by the same principle, although to a somewhat lesser degree. Objects that recede into the distance start to converge toward a single point the vanishing point. The figure is being compressed ever so slightly as it recedes, and expanded ever so slightly as it advances. Your characters will become more powerful if you draw them in perspective. (See "Powerful Perspective," pages 76-91.) Add contours with darker lines and shading. It's a good habit to define all of the muscles at this stage. Once you costume the figure, you'll want to retain the definition of the "show" muscles and decrease the articulation of others, but you can't make those decisions until you see how the costume actually looks on the character. The cape hangs like a piece of drapery, folding and curving. It expands as it travels down the body and crushes along the creases. Here is a tighter version of the same drawing with boots, gloves, and short, form-fitting pants. Folds have been added to the cape, and shadows help give a feeling of volume to the form. We've gotten rid of some of the extreme musculature that was used to first construct the body. But the form retains its feeling of strength. And the final version. It has cleaner, bolder lines. We've added a mask and lost the short pants in favor of midthigh boots and long gloves. Now this character is ready for whatever destiny awaits her! a hint about skintight costumes S kintight costumes are popular and easy to draw. The body itself provides the outline for the costume. You only need to draw the lines where the costume ends, as in this example, in which the line of the costume follows the contours of the torso. ENTION THE WORD “PERSPECTIVEâ€? and you send chills down the spines of ordinary men. Never fear. This chapter is easy to understand, but even more important, the information in it is easy to use. Remember, we're drawing pictures here, not designing spacecraft. Stay tuned. This will be short and painless. one-point perspective T he terms horizon line and eye level are used to refer to the line of sight that's created from your position in relation to the scene you're about to draw. A drawing uses a system of one-point perspective when all of the lines that recede toward the horizon line eventually converge at one point, which is called the vanishing point. Note, however, that not every line converges. The vertical and horizontal lines remain parallel to the frame of the panel. These lines don't converge HORIZON LINE OR EYE LEVEL because they're not traveling into the distance. They just go up and down, or from side to side. Once you draw a line that appears to travel from the background to the foreground, or from the foreground to the background, you need to use the principles of perspective. Take a look at the boxes below. Notice how you can extend guidelines to the vanishing point to create the corners within a box, which you normally wouldn't see in a finished illustration. VANISHING POINT two-point perspective T ake this quiz: Two-point perspective means that the picture has: (a) One vanishing point (b) Two vanishing points. If you picked "a," take a lap, give me ten push ups, and sharpen your pencil. If you picked "b," keep reading. In two-point perspective, the objects in the picture are not facing forward, but are turned at an angle so that a corner is pointed at the viewer. Because of this, the horizontal lines no longer vanish toward the center of the page as before, but toward opposite ends of the page, to two separate vanishing points. (These can't be seen here because they're too far off to place in the picture.) If you were to extend every line in this picture (except for < TO VANISHING POINT LEFT the vertical ones) in the direction it's already heading, you'd see that they all converge at either the left or right vanishing point. In illustrations where you want the perspective to appear more gradual, you can place the vanishing points farther away from one another. The closer together the vanishing points are, the more severe the perspective will be. You'll notice that the horizon line runs horizontally across the picture. It doesn't matter where you place the horizon line; that's just your own personal preference. But once you've established the horizon line's position, the rest of the picture must conform to it. Everything below the horizon line vanishes up, while everything above it vanishes down-toward the left and right vanishing points. HORIZON LINE TO VANISHING POINT RIGHT > finding the vanishing points P retty scary-looking, huh? These two scenes may intimidate the ordinary artist, but after reading the preceding page, you can sense the logic behind each one. The horizon lines are the horizontal ones running across each picture. All figures diminish or increase in size relative to their distance from the viewer. If you have more than one figure in a scene, you've got to draw the ones that are supposed to be close bigger, and the farther ones smaller. Don't give me that bit about how your characters are from another planet where the laws of perspective are different. Cute. Notice how all of the figures fall within the parameters of the vanishing points. They have to. It's not a choice-it's a law. A physical law. If you break it, you get a metaphysical ticket. Can you spot the three vanishing points in the illustration at the bottom of the page, and the four vanishing points in the one immediately below? PERSPECTIVE LINES HORIZON LINE HORIZON LINE PERSPECTIVE LINES the horizon line and the figure W here you place the horizon line in a drawing determines whether the viewer looks up at the subject, down at the subject, or straight at it. In other words, the position of the horizon line determines the position of the viewer relative to the picture. In drawing 1, the horizon line is at ground level, which means that the viewer is positioned above the figure, at a high eye level, which creates the illusion that the viewer is looking down at the figure. The ellipses that are used to indicate the figure's underlying form become wider the lower they are within the drawing. Therefore, the ellipse within each calf is rounder than the one within the chest. Because the vanishing points of the perspective lines would run off the page, a rough grid has been drawn over the figure. In contrast, a low eye level places the viewer's eye below a figure, which creates the illusion that the viewer is looking up at the figure, as shown in drawing 2. In both examples, the angle of view distorts the figure slightly. In the example at right, the feet and legs appear larger than the head and chest because they are closer to us. In the other drawing, the effect is reversed, so that the head and chest seem larger, and the legs and feet appear smaller. To determine the proportions of a figure regardless of the location of the horizon line or the eye level, erect a vertical line from the horizon line anywhere along its length. To approximate the points for the top of the head and the crotch, divide the vertical in half. Divide each half in half once more to establish the chest at its broadest point and the position of the knees. A bit of room has been left below the bottom quarter for the feet, which makes the figure slightly taller than 8 heads high-great proportions for a comic book hero. PERSPECTIVE LINES VANISHING POINT HORIZON LINE MULTIPLE FIGURES IN PERSPECTIVE T hese four figures are all standing on a level surface. Assuming that they are all the same height, then the horizon line would pass through their bodies at the same point—in this case, their waists. Alternatively, the horizon line could have intersected the figures at the knees, which would lower the horizon line, making the viewer feel that he or she is looking up at the figures. You have to make slight adjustments when drawing short figures or figures not on the same flat surface. "Eyeball" it-if it looks right, it's right. If a figure looks like he's "floating," he's too high. Lower him, or, as many artists do occasionally, draw a step under him. HANGING FIGURES ON A HORIZONTAL LINE T his is an artist's trick for keeping all the figures on the same ground plane. When you place figures in detailed backgrounds, you have to use vanishing points to indicate perspective. But if there's an open background in a single color, or a background with no hard edges in perspective, such as sand dune, an open field, or just a wall with only straight vertical and horizontal lines, then you can use this technique You can align the figures at any point. In this drawing, they're aligned at the eyes. This assumes that all the figures are generally the same height and on even ground. HORIZONTAL LINE You shouldn't align a four-year-old child's eyes at the same point as a six-foot-tall man's eyes. That would make the child appear to be levitating. Don't want that. Not unless the man were the Amazing Presto. creating volume with perspective T he human body exists in the real world, and, as such, is subject to its immutable laws: Everyone pays taxes, everyone hates gym class, and everything diminishes in size as it travels away from you (toward the vanishing point[s]). If you were drawing a railroad track, you would doubtless draw it so that it appears to diminish in size as it travels into the distance. But when people draw figures, they somehow think that the laws of perspective don't apply. Not so. In fact, there is no more necessary application of perspective than on the comic book figure. Perspective creates much more dynamic, powerful-looking characters. You don't need a lot of perspective for the body; just a little will give your drawings that added air of professionalism. Because the body doesn't cover as much distance as a road, a slight suggestion of perspective will be effective. To find the perspective points on a figure, it's useful to create a mannequin made out of blocks. These blocks have straight lines that can be followed toward a vanishing point in the distance. Each block has dimension-sides, if you will. They're not flat. Remember that everything has a side to it. Even a cylinder, which is rounded, has a "side" that appears closer. Next time you draw a rib cage, remember that you're not just drawing a chest and a back; you're also drawing the sides of the rib cage, which you can shade to create depth and dimension. dynamic angles L eaping, falling, jumping, soaring—these dynamic actions all have one thing in common: They are best expressed by drawing the figure at a severe angle. By angling the body, you heighten the drama of the pose. By loosely dividing the body into building blocks, you can show the angle by revealing the undersides of the blocks. This figure is shown from a "worm's-eye view," which means it's the perspective a worm would have looking up from the ground. Conversely, if we were to show a "bird's-eye view," we would be looking down at the figure from high above, as a bird would see him. In that case, we would see the tops, not the undersides, of the blocks. from start to finish N ow let's build a figure using vanishing trace lines as guides along various planes of the body. The vanishing trace lines (and you can use more) are along the collarbone, pelvis, knees, and feet. Using rectangles and cylinders, construct a body in perspective. Once you flesh out the form, the rectangles and cylinders can be erased, but the foundation of perspective will remain solidly in place. Many beginning artists leave out the first three steps and start at step 4. The body may have all these great-looking details on it but the perspective will be wrong, and its impact will be undermined. Look how much stuff we've already covered by the time we've gotten to this step. Costuming this guy should now be as easy as falling off a log. But to the person who doesn't know about drawing in perspective, this step will be a struggle, as he or she "guesses" how to make the figure look right. Now that we've got the igure in perspective, we can concentrate on the fun stuff-creating the costume. This costume is average in complexity. You can beef it up with more armor, or you can streamline it by eliminating the shoulder shield and some of the hardware on the arms and knees. extreme foreshortening C omic book illustrations are famous for their use of extreme foreshortening. Foreshortening is the way an artist makes an object look like it's coming straight at you, but without making it look like it's flattened out. It's a powerful tool at the artist's command. Gray Morrow points out that foreshortening makes the figure "seem to jump right out of the page. It is difficult to make this effective and, at the same time, believable, because you're attempting to give the impression of three dimensions in a two-dimensional medium." To create the illusion of depth, layer one form on top of another, showing the overlap, and thus tricking the eye into seeing the overlapped shapes as being further away. Always draw general shapes first when building the foreshortened figure. If you go to a finished drawing right away, you'll get stuck in the details, and lose the layering concept. foreshortening is a subject thoroughly covered in a great selection of books on anatomy widely available. how to use it in comics will be our main concern herein. there are many instances in a story where the action can be pointed up to a greater advantage. perhaps the foremost is...the punch... tells the story, reasonably accurate but frankly static... ...now we can see the miscreant is really being knocked into the middle of next week! ...the kick... ...your full-length mirror and the cooperation of friends and relatives willing to model will aid you in achieving almost any pose you can imagine... ...this is acceptable, but... ...this is better for the jump... A SUB-TITLE FoR THiS chAPTEr MighT BE-"cOMin-Atcha”, OR MORE PROPERLY, P.O.V.,(pOint OF VIEW), WITH YOUr CAMERA EYE YOU CAN PLACE THE REader/ViEWER JUST AS A FILM DirEcTOR DOE5, IN ALMost ANY P0siTION THAT WILL ACCENTUATE The AcTION TAKtNG PLACE. ...upshot... ...downshot... ...from behind... ...head-on... a difficult ANGLE oN ONe OF ThE M0st dIFFICULt ANIMALS to DRAW well. take the time and trouble to learn-it will pay off. THE SHAPE5 0F THE PANeLS thEM5ELVES, The WAY You brEAK UP ThE PAGe, CAN HELP YOU detERMINE tHE P.O.V. ANd AMPLIFY YOuR DESIGN OR cOMPOSITIOn OU NEED THEM TO DRAW EXPLOSI0NS. You need them to draw fight scenes. You need them to draw weapons that are firing. And you need them to draw those fantastic spreads that depict colossal action or emotion. What are they? Patterns of energy, visually elegant yet powerful abstract designs that convey mood and impact. These are important tools in your growing arsenal of professional comic book techniques. using pattern and value C omic book artists use patterns to create shading, backgrounds, explosions, space goo, and to decorate empty areas of a page. Let's say that each pattern is a specific value, or degree of lightness or darkness. We'll talk about these as percentages, 0% being pure white and 100% being jet black. Unless you're depicting a gradual transition from light to dark, patterns that appear side by side should always be at least three value steps apart. For example, you could put a 20% value and a 50% value next to each other, or a 30% value and an 80% value. But not a 20% value and a 30% value. Because these values are too similar, there Isn't enough contrast, and the patterns would blur together. Notice how the three bars above, left, appear confusing to the eye. That's because their values are too close to each other. But the six bars above, right, are all distinct because the value of each one is quite different from the one next to it. This is very practical stuff you're learning. If you draw a character in front of a building, you now know that they have to be shaded with values that are somewhat far apart, or they'll blend together. At right are examples of established comic book patterns. But don't stop there. You can make up your own. Keep in mind that your drawings will be reduced to fit on a comic book page, so don't draw the lines of any particular pattern too close together or they'll reproduce as an indistinct mass. 80% 90% 70% 100% 0% 30% 100% 50% Values PARALLEL LINES (20% VALUE) CROSS-HATCH (40% VALUE) CROSS-HATCH WITH VERTICAL LINES, (TRANSITION FROM LIGHT [40%] TO DARK [60%] GRAY) GRADED LUSTER (100% TO 0%) GRADED SPATTER (100% TO 0%) GRADED STROKES (70% TO 0%) RANDOM CIRCULAR PATTERN (10% TO 20%) VINTAGE CROSS-HATCH (30%) SCALES (10% TO 20%) PARALLEL WAVES (40% TO 60%) ROWS OF PARALLEL LINES (40% TO 50%) RANDOM CLOUD SHAPES (10%) 0% special effects in space I f you're a normal person, you probably think of space as vast emptiness. If you're a comic book fan, you know that space is filled with eerie visual effects, unnatural forces, and bizarre energy patterns. Feast on these examples: ENERGY WAVES MILKY WAY MYSTICAL COMIC EFFECTS ALIEN SPACE FORCE SPACE EXPLOSION Unearthly shapes and spheres for strange or weird stories. A crystalline force radiates intense energy illustrated with randomly painted thin white lines across black ink lines. In contrast to an earth-bound explosion, a space explosion expresses pure energy without any haze or smoke-because there's no oxygen in space. Despite the force of the blast its center remains spherical. Draw or paint parallel horizontal lines, then erase or paint in white whatever you want the pattern within the lines to be. You can also spatter the lines with white paint for a random effect. The jagged borders of the black void are flecked with black bubbles. Within the black areas, randomly add stars with white paint. Group the stars instead of spacing them evenly, and brighten a few with large twinkles. GALAXY EFFECT Another version of the Milky Way, but with elliptical instead of round shapes. A funnel effect creates a feeling of movement. bursts T he special effects of yesteryear were sedate compared with the galactic-sized bursts that reverberate throughout comic books today. Bursts are used in fight scenes, to herald the sudden appearance of a powerful figure, to express impact, to draw attention to whatever is at its center, and to illustrate explosions. They add energy, convey action, and create the illusion of motion. Many, but not all bursts, include tiny bubbles. A black background provides maximum contrast for the burst's tiny bubbles, which can be difficult to see in color against a colored background. But if the bubbles appear against a black background, the colorist just adds color to the whole image. Related to the burst is the mind-numbing explosion (shown on the opposite page). This earthly blast exhibits certain hallmarks: Debris flies out of its center, smoke in various shades billows across the scene, and its very center is white, indicating extreme heat. Its surrounding rings— from yellow, to orange, to red at the blast's periphery—show a gradual decrease in heat. putting it all together I n this wonderful illustration, artist Frank McLaughlin has used all of the elements that are covered in this chapter. While the figures and faces in the drawing don't display a lot of action, the special effects create an explosive feeling, as if the entire image were in motion. HAT WAS THE BEST STORY YOU EVER HEARD? My favorite is a supernatural tale of good versus evil that was told by a camp counselor as a group of us sat, enthralled, around the fire. Every word he uttered conjured up an image that created a feeling of urgency. As an artist, that's the kind of life you want to breathe into a comic book script. You want your readers to be captivated by every image. It can be done.... effective composition T he secrets of effective composition are shared among professionals but are rarely found in how-to books. Yet, these rules are essential if you want to create powerful images. You can render the most exquisite drawing, but if the figures aren't positioned well in relationship to each other, the reader, the background, or the panel that frames the scene, then it won't have the impact you're striving for. Don't rob yourself of the effect you've been working so hard to achieve. DO! DON’T! ...put the dominant element in the center. It's just not dynamic. ...divide a panel by three both horizontally and vertically, for a total of nine equal sectors. This is a painter's and illustrator's trick for creating dynamic compositions, and it's worth the price of the book alone. DON’T! ...cut off corners. It's a sign of an amateur. Instead of making the picture more interesting, you've succeeded only in making triangles in the corners of the panel. Less tilt would actually make the drawing more dramatic. DO! ...place the center of interest at any point where these lines intersect. In this case we've placed the hero's head at the intersection of the right vertical and top horizontal guidelines. DO! DON’T! ...cut off hands and feet. What it tells the reader is, "Oh, this guy can't draw hands and feet.” ... vary your compositions. This is a longer shot using the same principle, but whose point of emphasis falls at the intersection of the left vertical and top horizontal guidelines. the establishing shot T he establishing shot does just that: It establishes a scene or the positions of different characters by showing them from a distance where everything and everybody is visible. If you didn't have an establishing shot and used only close-ups, before long the reader would be lost and unable to identify the context in which the scene takes place. On the other hand, too many establishing shots make a story remote and inaccessible because the reader is kept at a distance from the characters. An establishing shot doesn't always have to be at the beginning of a story, although that's usually the case. Sometimes an establishing shot, like the one below, is used in the middle of a story to "widen it out" and let it breathe. You might be illustrating dialogue that takes place in an office, but an office interior can become claustrophobic, so you cut to the exterior of the office and show the city to give the scene some breathing room. In the example below, the exterior is a futuristic city. This professional technique breaks up the monotony and helps to keep the reader's interest. Notice how the dialogue balloons appear to be coming from the office building, but their spouts aren't coming from any particular window. They simply indicate that the dialogue is coming from the general area of the office, and the point comes across clearly. what a comic book script looks like E ach comic book script is different. While some writers offer lots of descriptive detail, others provide very few clues as to how a scene should look. The role of the comic book penciler is part interpreter, part creator. He or she must find the most exciting and effective way to tell the story. HERO VERSUS VILLAIN/SPECIAL ISSUE, VOLUME III PAGE 4 Our Hero reels in agony as the huge, other-worldly villain shoots a cable around his neck, strangling him. Hero grabs knife from his belt and slashes the cable, breaking free. He is now one ticked off guy. He's ruffled, not the smooth, untouchable fighter we are used to seeing. The Hero gives Villain his famous glare of bad intentions. If that won't kill the Hero, this will: with his free hand, the Villain quickly pulls out a heavy gun that FIRES four missiles all at once! The missiles race toward our Hero. Hero leaps into the air - and I mean acrobatics - just as the missiles explode at the exact point where he was. Hero suddenly spins, and with a solid two-handed grip, fires his blaster into Villain's body. Villain is right behind Hero, one more moment, and Hero would have been Spam. A huge explosion fills the panel. Villain is blown back -- the weapon goes flying out of his hand. Nothing could survive that. PAGE 5 Hero slumps to his knees, in the middle of the city street. Villain lays next to him, face down, gone. Hero is exhausted. Crowds peer. Life coming back to the street. Hero whispers: "It's over..." is also import ant. p xplosio anel is an n, then the He reader w il lb I wea ry after ecome a fe pages, and the w explos io lose th ns will eir “po w (pardo n the p â€? un). Villain's arm lays dormant as we see the Hero walking away in the If every background. e The Hero gets on his motorcycle, kick starts it and it hums looks at a kid who is looking at him.Kid says, "Gee mister, thought you was gonna get killed. Hero says, "Thanks for having so much confidence in me. Kid says,"Do you think you could beat him if you fought him again? WE SEE THE VILLAIN'S FINGER TWITCH. The fat lady didn't sing yet. Hero says, "Why do you want to know that?" Kid says, "Because he's right behind you!" And with that, the Villain rises, grabs the motorcycle the Hero is sitting on, and hurls him into the side of a building! thumbnail sketches W hen a penciler starts laying out a page from a script-in this case, page 4-he has many options. He begins by sketching a variety of approaches without committing to any. Some he'll save, some he'll combine, and some he'll tear up into teensy little pieces. Thumbnail sketches are small, quick sketches that show the sequence and general direction of a series of images. It's very important that you don't fall in love with your thumbnail sketches. This would defeat their purpose, which is to give an artist the freedom to throw them away or change them. You're seeking ideas at this point, not finished drawings. The approach above, left, doesn't show enough of the characters' faces to make the action compelling. The approach above, right, has wonderful dramatic angles. But the characters are still too far away to pull us into the story. The approach at right combines medium shots and close-ups with a variety of interesting angles. It's a keeper. the rough layout O nce the penciler decides on the best way to approach the script, he begins the rough layout. The most significant part of this stage is to evaluate the general feeling of the page. Does the story flow, or does it seem like random panels jumbled together? Is it dramatic, or does it meander from picture to picture? Are the images within each panel clear or cluttered? Does the largest panel contain the most important action? Notice how a heightened sense of urgency is achieved by alternating close-up shots with full shots, as well as by alternating the angles. We're either looking up at someone or down at someone, but rarely are we looking at them head on. Also notice that the panels vary both in dimension and size. Variety keeps readers on the edge of their seats. preparing a pencil layout for inking A fter the rough layout, the penciler starts to work "tight." This means that everything must be precise, because the inker, who works on it next, can't read the penciler's mind. If a line is missing, the inker may not put it in. If a sloppy line is there, the inker might ink it anyway. So the page should be perfect. Now is the time to work on the details. This is when it really counts. Notice how much care is taken to save room for the large inked areas. Black areas add weight and melodrama to a scene and create contrast when juxtaposed with white or light colors. Note also the striking negative (white) space among the billows of black smoke in the bottom panel. An experienced penciler works to create such areas for the colorist, who can have a field day with them. the final inked page I nking is a tremendous skill. Professional pencilers know how valuable a good inker is, and they actively lobby the publisher to get the best inker to ink their pencil drawings. The inker does more than just trace pencil lines in ink. He gives them shape and crispness. He is also constantly on the alert, making sure that drawings read clearly in terms of ights and darks. In doing so, he may make small adjustments to the pencil drawing. The following are some of the flourishes that Frank McLaughlin, known for his deft pen work, has made to Alexander Morrissey's excellent pencil drawings. Textural detail was added to the whip, and a touch of white was added to the character's beard for contrast. Frank added a burst of energy around the character to heighten the urgency in the scene. The cartridges around the missiles were left out because the image was sharp and effective without it. The buckles on the hero's boots are rendered in white and black. If they were left black, they would blend into the black background. Burst lines were added between the clouds of smoke to fill in the page. HERE ARE CERTAIN SKILLS that can't be mastered unless you're working in the comic book field. That's because these techniques don't fit neatly under one category, but instead are acquired over the course of a career. These techniques are usually shared over coffee with fellow cartoonists, as everyone discusses what they're working on. If you were there at that table, at that diner, this is what you would have overheard.... inking like a pro M any people break into the business by inking other people's pencils, so it's important to at least acquaint yourself with the subject. But inking is an art in itself. Even the most dramatic comic book illustrations can achieve their full impact only when a talented inker adds his magic. The ink line has a crispness, boldness, and variety of thickness that a pencil line can't produce. As shown in the illustrations at right, there are three basic types of ink line. By varying its thickness, we get bolder or softer lines. Just using one thickness of line leaves a character looking lifeless. The magician's adage "It's all in the wrist" also applies to inking. The more you bend your wrist, the less control you'll have. Of course, the line will remain straight up to a point. But when you bend your wrist too much, the line becomes wobbly. The solution is to keep your wrist locked, your hand loose, and move your whole arm instead. With a little practice, it'll become second nature to you. A few more points: Hold the pen or brush straight up and down. Feel free to move the page around, so that your arm is always at a comfortable angle. HOLD THE PEN OR BRUSH PERPENDICULAR TO THE PAPER THICK TO THIN EVEN THIN TO THICK DON'T BEND YOUR WRIST OR THE LINE WILL BECOME WOBBLY stuff you need to know COMIC BOOK PAGE WITH DRAWN PANELS TRIANGLE T-SQUARE D oesn't a T-square look serious? But hey, if comic book artists use one, how complicated can it be? It's a great tool. You'll actually like it when you use it. Scary thought. All horizontal lines are drawn with a T-square; all vertical lines are drawn against a triangle. This eliminates the fuss of measuring. Lucky you. Just when you were wondering when we were going to get back to this subject, here it is again: more gray tones! In black-andwhite drawings, tones are created by adding shaded sheets that come in various percentages of gray. If you look closely at a newspaper image, you'll see that the shades are all made up of black dots called screens. The bigger and closer together the dots are, the darker the shade. After your drawing is finished, carefully cut a sheet of screen so that the piece fits precisely within the area to be shaded, then burnish it down. 20% 30% 40% 50% In addition to drawing your own patterns for shading, you can use screens. art supplies shopping list Y ou don't have to commit this stuff to memory. Just bring this book into any art store and the salespeople will help you find the items you need. Before you purchase any art materials, check the labels to make sure they're nontoxic. You shouldn't buy or use anything that has a warning label on it. Use only nontoxic inks and materials with all the instruments listed in this chapter. The brush preferred by many inkers is the BRUSH Winsor & Newton Series 7 watercolor brush. The best sizes are the No. 1 and the No. 2. Experiment to find the size that works for you. The advantage of a brush is that it gives you thin and thick lines without changing instruments. It gives your line a softer edge, and a brush line dries faster than a pen line. But the thing that the pros like about it is that it's fast. However, a brush takes time to master. Be sure to wash the ink out of your brush before it dries or it'll be ruined, and brushes are expensive. Just dab it in a jar of water immediately after using and dry it with a clean rag. FRENCH CURVE NIB HOLDERS PEN NIBS PEN NIB FINE-LINE MARKER PEN NIBS TECHNICAL PEN Professional inkers also use pens, which are easier to use than brushes. Starting out you'll feel more confident using a flexible-point pen that has removable tips. There are many pen tips to choose from. Try starting with Joseph Gillott Nos. 170, 290, and 404. If your local art supply store doesn't carry this brand, ask the manager to help you choose something comparable. CIRCLE GUIDE Use a technical pen with a nontoxic ink to give you an even-weight line. Its points are interchangeable and come in varying degrees of thickness. It has a rigid feel. You should also buy a few nontoxic fineline markers in different widths. Use a nontoxic India ink for inking and Pro White for whiting out. If you use nonwaterproof ink, your drawing will smear if it gets wet after the ink has dried. Waterproof inks, on the other hand, are permanent. French curves, available in many sizes and shapes, are used by pencilers and inkers for drawing smooth, curved lines. ELLIPSE GUIDE Drawing circles and ellipses can take a long time if done freehand. So we cheat a little. We use circle and ellipse guides, which are plastic and translucent. For inking straight lines, use a raised 6-inch plastic ruler. A T-square is too unwieldy to use for drawing short lines. Turn the ruler upside down and run your pen against the edge. If the pen weren't raised off the paper surface, the ink would blot and you don't want that. RAISED PLASTIC RULER reflections B oth glass and water reflect light. A glass skyscraper should be drawn so that it either reflects what's across the street, or so you can see through it, but not a combination of the two. Think of windows as a big sheet of glass interrupted by little strips of nonreflective material. Don't shade each pane differently. Also, be sure to show a slight rippling effect, which helps it to "read" as glass. For the most part, water reflects the sky and surrounding foliage, depending, of course, on the character of its surface. If the water is smooth, it will reflect like a mirror. If it's rough or choppy, you'll get a broken reflection. LIGHT SOURCE S hadows can heighten the visual appeal of a character by making him or her seem more intense, more urgent. It also makes objects appear three-dimensional, because an object must have mass to cast a shadow. But you can't determine where shadows go without first deciding where the light source is. What are some light sources? The sun is a light source. Lamps and street lights are light sources. A partially opened window shade during the day is a light source. An explosion is an excellent light source, one so intense that it creates deep shadows. Once you've decided on the direction and location of your light source, place your shadows away from it. Note that there may be more than one light source in a scene, and that they may differ in intensity. The brighter light source will cast shadows over the dimmer light source. If you draw a shadow on the far side of a face, as shown in the two examples on this page, the face will tend to recede because darker images draw the eye toward the background. If, on the other hand, you wanted this character's face to pop out at you, you would move the light source from the right side of the page to the left. Then the far side of the face would be bathed in light, and the near side would be cloaked in shadow. This dramatic effect draws readers into an image by emphasizing a detail. Just as with hair, costume, and other details, draw shadows after you've first completed the full image. SHADING T here are several styles of modern comic book shading to choose from. Except for hollow shading, you can combine the techniques illustrated below according to your personal taste. Here's the basic guy. (Even when relaxing, a comic book hero's muscles are always flexed!) The minimal shading here is loose and natural in appearance. Hollow shading gives a reflective appearance. It makes the character look like he's made of plutonium. Notice that the shaded areas have sharp edges; they're not gentle pools of black shadow. This is a crisp, metallic, and severe look. This is cross-hatching. It's more ruggedlooking than the hollow style. This technique would work well on a down-in-thetrenches street fighter. A word of caution— this style can look too busy if you overdo it. This is the standard comic book-style shading-old, reliable, and still as popular as ever. This approach combines light crosshatching with pockets of solid black. CROSS HATCHING NO SHADING HARD SHADOWS COMBINATION: CROSS HATCHING AND POOLS OF SHADOWS VARYING AN INK LINE T he figure below, left, looks flat and dull. That's because it's drawn with only one thickness of line. So that your drawing has life, it's important to vary the thickness of a line. But you've got to have a plan. You can't just alternate thin and thick lines with no underlying purpose, because that would look weird. The figure below, right, looks three dimensional. And there's some logic to it. If the source of light is above the figure, which is generally the case, the thinner lines are drawn toward the light, and the thicker ones are drawn away from it. More lines are usually apparent on the folds of the shaded side. The light source for the example below, right, is above and to the right of the figure. Can you see that? With the exception of heavy folds, the lines within a figure are lighter than the lines on its perimeter. folds and drapery N ot all clothes or fabrics fold the same way. Because many beginning artists draw only skintight plastic suits for their comic book heroes and heroines, they're at a loss when they have to draw a character in something as simple as a button-down shirt. Take a moment to notice the kinds of folds made by different types of clothes. This character is outfitted in a baggy costume based on a biblical or Middle Eastern theme. Its folds, therefore, are soft and loose. This character is outfitted in a fantasy style. Flowing and ornate, her costume is based on ancient Greek and Roman clothing. It is best served by a feeling of gravity pulling on it eliminating the folds you'd find in a baggy costume. The fabric ends up as inert folds around the bottom of the costume, where it bunches up. This character is dressed in modern, tailored attire. The synthetic fabric creates crisp folds in shorter, straighter lines. designing costumes C ostumes are fashioned in one of two ways: skintight, as if they were painted on; and loose. Skintight costumes are easier to draw, but require heavy shading to give them a slick, three-dimensional quality. Loose clothing requires more planning to show the correct flow of the folds. Try both textures on your characters before deciding. By costuming your characters in different looks, you can see how clothes really do make the character. You can invent large accessories for costumes that have no useful function except making your characters look tough. The metallic look, as shown in this character's armor collar, requires shading to indicate glints of light. EAPONS HAVE ALWAYS BEEN POPULAR comic book props, since they heighten the stakes in a story. If one character has a serious weapon, then the motivation for winning-and the fear of losing-is much greater. Whoever holds the bigger weapon takes on the role of the hunter, while the character who is out-gunned becomes the prey. If two characters have equally powerful weapons, the city will be annihilated during a shattering fight scene. rapid fire W hen drawing any weapon, the method is the same. Start with rectangular shapes, combine them until the general outline of the entire weapon becomes recognizable, then blend them together. Then go to work on the fun stuff, and put on all the bells and whistles. in the crosshairs J ust as the cowboys were devoted to their horses, heroes and villains are very attached to their weapons. If you want your hero to be able to blast a villain at 100 yards, give him a weapon with greater range. A longrange rifle has pinpoint accuracy. You can get ideas of how to draw weapons from other drawings, or you can start a cartoonist's morgue. Morbid as it may sound, a morgue is a useful tool for the pro. A morgue is a collection of images of various objects that you may be called on to draw from time to time. Whenever you need an image of something, from a machine gun to an amphibious assault vehicle, it should be there in your morgue. The character using a rifle should be considered by all to be an accomplished marksman. A rifle without a scope becomes a generic weapon, good for any dangerous situation. hidden danger I n a pinch, when your hero is cornered, out of luck, and has nowhere to turn, he just may be hiding a pistol under a pant leg. Small, but deadly, the pistol is a great last-ditch weapon. Spent cartridges fly off as a gun fires, which is indicated by a burst. A double image of the gun shows its kick. Smoke rises delicately from a gun that has just been fired. aggressive assault vehicles N ot all heroes can fly. But when duty calls, your hero can't very well buy a ticket on Amtrak. So how does he get from here to there? In a hightech, fortified, ground assault vehicle. Some comic book vehicles, like the Batmobile, have become so famous they are almost characters in and of themselves. Alexander Morrissey can draw military vehicles as well as anybody in the comic book field today. Notice how he achieves his results: 1. Start by outlining the large shapes. Sketch in huge, knobby tires that will allow the vehicle to drive over literally anything. The key is to overlap the tires. Add protruding forms such as guns and fenders. Begin to sketch in the design of the vehicle's body. 2. Refine the forms to give them dimension. Sketch in some details, but keep the drawing loose. You can clearly see the complex layers that make up this type of tank. 3. Now for the fun stuff. tire treads, weapon systems designs, buttons, hatches, and radar. 4. Add the correct shading. 5. Finish up by inking. The vehicles should look convincing and state of the art, fully armed with a variety of weapons. One look at an assault vehicle should send chills through the enemy camp. A comic book hero in an assault vehicle would have no compunction about driving right through the window of a restaurant if a bad guy were inside. off-road E ven heroes without super powers, such as a band of teenagers, can become exciting characters in a comic book. But they need to be given the tools to fight crime. An off-road truck can help accomplish this. An off-road truck should have huge tires, a souped-up chassis, and heavyduty fenders, perfect for ramming. This kind of vehicle gives the reader the sense that its driver is ready for action, that he or she can and will go anywhere the action is taking place. mean machines M otorcycles convey a feeling of speed, power, and freedom, and embellish a character's personality. After all, Clark Kent never rode a hog. What your character rides says a lot about who he or she is. A motorcycle also allows the reader to see the character's body while he or she is driving. In a car, the character is mostly hidden from view. Give your hero's bike a beefed-up look that's built for speed. A motorcycle is exciting because of the way it can weave between pedestrians on sidewalks and make impossible jumps over open drawbridges. sky patrol G reat chase scenes can be created when you combine two entirely different modes of transportation; for example, a helicopter chasing a motorcycle. The two vehicles have different strengths and weaknesses, and just as with superheroes, the weaknesses are as important to the drama of the chase as the strengths. For instance, the chopper's strength is immediately apparent: It can fly faster and has a greater capacity for spotting a target. The chopper might also be equipped with guns. The pilot has a radio that he can use to call for backup. The chopper's weakness is chilling: It might have to fly dangerously low to follow the motorcycle and get sandwiched between two tall skyscrapers. Splat city. The motorcycle's advantage is that it can drive through places like tunnels, buildings, and malls that the helicopter can't. It's easy for the driver to ditch his motorcycle, but not so easy for a chopper pilot to get out of his chopper whenever he feels like it. The motorcycle's potential drawbacks are oil slicks, traffic jams, crashes, and police cars that enter the fray as the motorcycle whizzes by at 100 m.p.h. or more. fighter planes W hen you want to blow something up—and who among us hasn't had that desire at one time or another?—then it's time to send in the fighter aircraft. Notice the perspective of the wings. The far wing is all but hidden by the body of the aircraft. Note the tilt of the aircraft. It's drawn at an angle, as if it were ascending. A horizontal view would be much less interesting. Also, its weapons are in full view. An aircraft doesn't need to have a lot of gizmos drawn on it. Its high-tech look is implied by the graceful lines of its form; for example, in the way its nose tilts downward in an aggressive posture. O YOU WANT THE INSIDE STORY on how the comic book biz works? Smart thinking. You'll need to know what happens in the real world so that you won't be lost when you get your first job. You've come to the right place. Keep reading, because here is the inside, professional scoop. 4. THE EDITOR for his HOW THINGS ARE SUPPOSED TO GET DONE approval, and if he likes the pencils, he shoots it over to— P utting together a comic book is a big job. Many talented people—and maybe a few not-so-talented ones— are involved in producing it. What follows is a step-by-step chronology of the birth of a comic book issue. Take note that there are job titles listed here that you may not have considered for yourself but that may appeal to you, such as writer, editor, or computer colorist. 3. THE PENCILER, who illus- 1. THE EDITOR has a deadline to deliver a new comic book issue, so he quickly calls trates all the action in the script in pencil, placing everything in panels and leaving room for the dialogue balloons. Once he's done, it goes quickly back to— 5. THE LETTERER, who letters the dialogue in ink, and then gives it to (guess)— 2. THE WRITER, who writes the story and dialogue and indicates the action. The script is then sent to— 7. THE INKER. By now everything is usually running behind schedule. The inker inks the book and erases the pencil lines, then hands it back to— 6. THE EDITOR, who checks the details. Then it's on to 9. THE COMPUTER COLORIST, who puts in all those nifty tints we love so much. The colorist gives it right back to— 8. THE EDITOR, who checks it again, and then fires it off to— 11. THE PRINTER 10. THE EDITOR, and this is the last time he can make any changes. If he says the word, it gets shipped to— who's about as exciting a guy as your uncle in the men's wear business. Meanwhile, back at Comic Book Headquarters, they're having a— 13. THE ARTISTS, 12. COVER CONFERENCE. The executives are trying to decide what the cover should look like, and when they can break for lunch. A different artist does the covers because the publisher wants all their covers to have a similar look. Once that's decided, it's time to do it all over again with another issue. So what happens to the original artwork? It goes back to— and gets divided between the penciler and the inker, for them to keep, frame, or sell. hoW TO GET YOUR FIRST JOB Y ou're already on the right track. You're drawing and educating yourself with this book, while other guys are at the beach, preparing themselves for the future by deciding what number sunblock they should use. The next thing you might want to consider is getting an art education, by attending classes at an art school, continuing ed, or the university you're enrolled in. In art school, you'll be inspired by your classmates. You'll strive to increase your ability because you'll want to keep up with everybody, or be just a little better than they are. Take classes in drawing, perspective, design, and anything else that interests you, but don't focus solely on what type of class to take. Look for the instructors who have the most to say and can challenge you. If an instructor loves everything you do and thinks that art is self-expression-and that therefore no one should judge anyone else's work—run the other way. Everyone judges everyone else's work—that's how you get hired, because your work is better than the next guy's. ORGANIZING A PORTFOLIO If you're going to convince someone to hire you, you've got to show them your stuff. One way to make a portfolio is to collect copies of your best drawings (never include original art in a portfolio because you may be asked to leave it behind for review) and arrange them in a nice-looking carrying case that you can buy at an art store. The largest size an individual piece of art should be is 11 by 14 inches, and the smallest is 8½ by 11 inches. Show between ten and twenty pages, and include color pieces if you have them. To prepare a portfolio that is more specific to the comic book field, try revamping a character that a comic book publisher already owns. Don't use a superstar character like Superman, but someone less popular that has been lying dormant for a few years. Create a whole new approach for the character. Write a two-page story synopsis and reinvent the costume and supporting characters. But don't reinvent any popular characters with whom the character interacts (no editor wants to reinvent something that's working). This type of portfolio shows the editor that you can draw his characters, which is what he wants. In addition, if you can bring new life to a tired formula, you might be the answer to an editor's prayers. MEETING THE PUBLISHER Once you have your portfolio together, you can try calling the publisher for an appointment to show your stuff. But it's not always easy getting through. If you can't arrange for a meeting, send a copy of your portfolio with a cover letter and a self-addressed stamped envelope. You can get the publisher's name and address by looking at the small type at the bottom of the first page of a comic book. If you do get to meet with a publisher, or with someone else at the company, make sure you leave something behind that is representative of your best work. DOING YOUR HOMEWORK By visiting a comic book store and combing through new and obscure issues, you can find smaller comic book publishers that may be willing to take a chance on you. But most important, you'll get the latest info at a comic book shop. Everyone there is a fan. And every fan knows a comic book artist or two. You can make connections. But while you're in there, be sure to find out where the next comic book convention is being held. That's where the action is. COMIC BOOK CONVENTIONS There are always pros roaming the conventions, so bring your portfolio. Many comic book publishers set up booths at conventions to interview new artists. You want to find a pro who needs an assistant. Try to show your stuff and see if you can get phone numbers. Then be sure to call after the convention is over. Don't expect a pro to call you. He's got a job. You're the person who wants one. APPRENTICING Once you're apprenticing for a pro, you can pester him with all the questions you've ever had, and he'll probably answer them. When he gets busy, he'll start to throw smaller jobs your way, and maybe he'll even help you to set up your own studio. As you improve, you'll graduate from backgrounds to more impressive stuff. Then one day, as you're roaming a comic book convention, some kid will walk up to you and ask you to look at his portfolio. And you'll realize that you're so busy, you need an assistant to do your backgrounds. When that happens, you've arrived. INTERVIEW WITH A NOTED COMIC BOOK EDITOR AND PUBLISHER A s an editor at Marvel Comics, Jim Salicrup presided over such famous titles as The X-Men, The Fantastic Four, Captain America, Iron Man, Thor, and many others. He left Marvel to become the associate publisher and editor-in-chief of Topps Comics, where he has ushered in the successful comic book titles Bram Stoker's Dracula, Jurassic Park, Duck Man, Mars Attacks, and Zorro. Jim shares with us his views on the origins of comic books, where they're headed, and some of the opportunities available to the aspiring comic book artist today. Hart: Jim, what makes a great penciler? Salicrup: Each case is different. You could take someone I think is a brilliant penciler, a dark superhero avenger-type artist, and you give them a romance story that's supposed to be nice, bright, innocent, and light, and they make it seem like a Martin Scorsese film-that might be interesting but it may not be what you're looking for. So it always depends on the project. If you have a western, obviously it helps to find an artist who, number one, is very passionate about that period. Hart: Can you comment on the traps beginning artists tend to fall into? Salicrup: When they get their first script, it's a strange phenomenon. They almost look at it the way my daughter looks at her homework assignment-the priority is to get it done. I mean, they have that deadline looming over them, and they want to get their paycheck-all that I can understand. And if the script says, "the hero's looking out the window, then he talks to his best friend, then he makes a phone call," beginners could say that the story is just dull-there's no fighting, no action-and they'll just draw the first thing that pops into their heads. And I'll have a dull page. And if I say that it doesn't look as exciting as I thought it would, they'll immediately blame the writer: "Well, what do you want me to do? This is a dull script. Give me something exciting to draw." And to me that's not really an acceptable response. The top artists in the business could make a splash page out of that. They could have this breathtaking cityscape. They could have other things going on that are totally fascinating, and you pull back, and the hero is talking to his friend. And there's a way to do a sequence where making that phone call is a turning point in the story, and the way that the characters move, and their responses, and the way that the frames are cut and the panels are designed-suddenly this phone call is as important as any fight. Hart: Can artists today hope to own their own characters? I know that in the past that was impossible. The guys who invented Superman were cut out of the whole thing. Salicrup: It's a tricky thing. Siegel and Shuster [the creators of Superman] are a good example, in the sense that their undoing was not so much the "evil publishers"-although I'm not going to defend the publisher's actions in this case-but their sheer frustration. They had a character that they were really excited about. They tried for years-I believe it was about five years-to sell it, and it's something that they really felt strongly about. Just to see it in print, and at that point as a comic book, meant so much to them that they were willing to sign almost any deal. And the same thing could happen today. It happens a lot with creative people. If they have a passion for something, whether it's to star in a movie or sign a recording contract, they have to be very careful about the kind of deal they make. A lot of creators may feel, "Well, this is just one of my characters. I'll give that one away, but the next one I'll own." Hart: And there never was another Superman. Salicrup: The environment has changed a lot for the better. There are more cases today where people publish their own work and make better deals with publishers to retain all sorts of rights. And even if artists are creating characters for comic book companies, they could make better deals than have ever been made before. When I started twenty years ago, a lot of those options were the stuff dreams were made of. It wasn't as easy as it is today. Hart: Would you recommend art school to someone who wants to be in this field? Do you think a formal education in art is beneficial? Salicrup: Definitely, but it's not essential. There have been a lot of great comic book artists that were totally self-taught. It's like any great talent: If the ability's there, education will hone it and make it better, perhaps. If someone doesn't have the talent, but has the money to take classes, it could be a sad thing to look at that graduate's work. It may be lacking some kind of spark. But what tends to be the best part of attending an art class or a school is seeing real artists, either instructors or guest lecturers. Once the student starts in anything that resembles a real situation where he or she has to create comic books, that experience can be really beneficial, as opposed to just working in your basement. Hart: How have women's roles as comic book heroines changed through the years? Salicrup: It tends to reflect what's going on in society in general. In the early 1960s, probably the most telling example of this was the female character in The Fantastic Four. She was called the "Invisible Girl"-someone you don't see. And she's not a woman, she's a girl. She's the girlfriend. She's the sister. Her powers are to fade away. Often what happens in pop culture is that one stereotype is replaced by the latest, newer stereotype. So now you get a lot of sexy, aggressive, powerful female characters. Hart: Do you have any advice for aspiring comic book artists? Salicrup: When I review portfolios, I tell artists that they should show me what they truly think they're best at and most passionate about. Although "What are you looking for?" is a very valid question, sometimes I may not know what our next project is going to be. If an artist feels he's the best at funny animal cartoons, or moody atmospheric pieces, or whatever, the best tip I could give is to include a couple of pages that represent what he would really want to do under ideal circumstances. Chances are that the work might be a lot better than his samples of the top company's popular superheroes and typical action and talking pages. If he could really show me something that makes him unique, that he's the only guy who can do this kind of work, that has a far more lasting impression on me than if he gives me something that's kind of generic and looks like what everyone else has shown me. Try to find out as much about the field as possible. This can be done just by visiting the local comic book shop, finding out everything about every detail. The more you know, the better you'll be able to figure out what your next step is, whether it's presenting artwork to publishers, contacting writers directly, perhaps writing and publishing your own comics, whatever is best for you. The more you find out about the field, the more informed your decisions will be. $19.95 U.S.A. H ow a script, depicting advanced weaponry, and much, much more. You'll learn what to include in a winning portfolio, the shortcuts to landing your first job, and how the business really works. Also featured is an exclusive interview with Jim Salicrup, the renowned former Marvel editor and now associate publisher and editor in-chief of Topps Comics, who shares his insights on the business, revealing the qualities that he and other comic book editors look for when hiring new artists. Every comic book fan, collector, and artistic hopeful will find this essential reference impossible to put down. MEET AUTHOR CHRISTOPHER HART Christopher Hart is the bestselling author and artist of a popular series of how-todraw books published by Watson-Guptill Publications: How to Draw Cartoons for Comic Strips, Everything You Ever Wanted to Know About Cartooning But Were Afraid to Draw, How to Draw Cartoon Animals, and Christopher Hart's Portable Cartoon Studio. Hart's company, The Idea Workshop, Inc., creates how-to-draw art products for the aspiring cartoonist. He has also hosted several videos on popular cartooning. Hart has worked on the staff of the world-famous Blondie comic strip, and is a regular contributor to Mad magazine. His humorous articles and illustrations have appeared in numerous publications. Hart is also a writer and director of film and television. He directed and co-wrote the feature film Eat and Run, and has written for many other Hollywood studios, including 20th Century-Fox, Paramount Pictures, MGM, NBC, and Showtime, as well as for PBS. Hart resides in Connecticut with his wife and two daughters. 144 pages. 8Âź x 11 " (21 x 28 cm). 64 color and 375 black-and-white illustrations. Cover design by Bob Fillie, Graphiti Graphics Cover art by Frank McLaughlin Watson-Guptill Publications 770 Broadway, New York, NY 10003 Printed in USA OTHER CARTOONING BOOKS FROM CHRISTOPHER HART Published on Jun 29, 2015
https://issuu.com/miguelmartin43/docs/christopher_hart_-_how_to_draw_comi
CC-MAIN-2017-30
refinedweb
18,775
72.36
Hey guys, I need help with this program which I have a function that calculates this formula for total house cost and then have an instruction function that asks for the input, then in main has the output. Can anyone tell me waht I am doing wrong, I think I have to return something in the instructions function but I don't know what! Please help! Thanks! #include <iostream> #include <cmath> using namespace std; float totalHouseCost (float initial, float fuel, float taxRate) { float totalFuelCost = fuel * 5; // Fuel for 5 years float totalTaxes = taxRate * initial * 5; // Taxes for 5 years float totalCost = initial + totalFuelCost + totalTaxes; /*Initial House cost + fuel cost for 5 years + Tax Rate for 5 years */ } void displayInstructions () //defining instructions { float initial, fuel, taxRate; cout << "The following program will display 3 homes." << endl; cout << "Determine which is the best buy after 5 years of cost." << endl; cout << " Enter initial cost of house" << endl; cin >> initial; cout << " Enter fuel cost of house for 5 years" << endl; cin >> fuel; cout << " Enter tax rate of house for 5 years" << endl; cin >> taxRate; } int main() { float initial, fuel, taxRate; displayInstructions(); //call on instructions for user cout << "House of intial cost of " << initial << ", annual fuel cost " << fuel << " and annual tax rate" << endl; cout << taxRate << " Has a 5 year cost of: " << totalHouseCost(initial, fuel, taxRate) << endl; cout << "\n\n\n\n"; cout << "\n\n\n\n"; cout << "Jordan McGehee Lab2Pb8JM.cpp " << endl; cout << "Lab 2 Problem 8 pg. 159 Due 03-03-08 " << endl; system ("pause"); return 0; }//end main
https://www.daniweb.com/programming/software-development/threads/184283/help-with-house-program
CC-MAIN-2017-39
refinedweb
255
52.97
First of all: I start hating libxml2/libxslt. It's increadibly badly documented and the only way to implement something with it is to read the documentation, try hard to figure out what it may well mean (and which functions may get you where you want when applied in which order) and then still go for trial-and-error. Great. That said... Stefan Behnel wrote: > What about introducing a Namespace class at the module level that you can > instantiate with a namespace URI as argument and then register different types > of 'things' with it? [...] > ----------- > ns1 = etree.Namespace('') > ns1.update(my_dict_with_subclasses_of_ElementBase) > ns1['some_element'] = MyAdditionalElementImpl > ... > > ns2 = etree.Namespace('my:extensions:to:xslt') > ns2['func1'] = some_function > ... > ----------- I've created a new branch scoder2 (from scoder1) and taken this approach. "Namespace" became a module level function that returns a dictionary-like object, a _NamespaceRegistry. That object internally splits its values up by inheritance/callable checking, so there currently is an internal dictionary for subclasses of ElementBase (i.e. XML elements), for callables (i.e. extension functions) and for superclasses of XSLTElement, i.e. XSLT element extensions, but the latter are currently not implemented/used. Fits perfectly into the interface, though. The update() method is forgiving, i.e. if things don't match the requirements, they are thrown away. This allows you to write implementation classes/modules and then run Namespace('').update(vars(myclass())) to register the methods of that object or module (names starting with '_' are entirely ignored). I didn't test that yet, but it's intended. Kasimier (and possibly others) may hate me for this, but I think it's a nice feature. For compatibility, the XSLT and XPath classes still have the "extensions" keyword argument, but these are mixed with the globally registered ones (they take precedence, though). I'd personally argue for removing them since I largely prefer the new interface, but that would break backward compatibility (in case someone actually uses the old interface). Note that this is the only reason why I left them in. They are not needed IMHO and make things a bit more ugly. (I mean, really, why would you want to register extension functions for each call? What are namespaces for, hu?) Another problem is that XSLT doesn't currently check which namespaces are actually used in the stylesheet, it just registers all extension functions it finds. It *could* try to deduce the right namespace URIs from the ElemenTree/Document it works on, but that's not currently implemented. The current implementation is already ugly enough (although not toooooo bad) and the accompanying refactoring of the existing code was again rather extensive (the patch has some 900 lines against scoder1 - don't want to count the trunk). I may have to rework some things, but I'll still check it in for now, so that others can try it and comment on it. I will also start to use it in MathDOM, so we will see how it works out. Stefan
http://codespeak.net/pipermail/lxml-dev/2005-November/000674.html
crawl-002
refinedweb
498
55.34
With web components, developers now have the ability to create their own HTML elements. In this ultimate guide, you'll learn everything you need to know. On this page, we'll cover what exactly web components are, the benefits of using them, and the elements that make them up. Then you'll learn how to build your own components in two short tutorials – on page 2 you'll learn how to building a component with the HTML templates and shadowDOM APIs, and on page 3 you'll got one step further and learn how to build a customised, built-in element. Finally on page 4 you'll find some frameworks and tools to get you started, and examples of existing elements to try to today. (For more tools, see our web design tools roundup and our pick of the best website builders.) While you're here, you might also want to take a look at our guide to the top HTML APIs, and how to use them, as well as our top examples of parallax scrolling. What are web components? Developers love components. They are a great way to define blocks of code that can be dropped in and reused anywhere they are required. Over the years, there have been a few attempts to convey this idea on the web, with varying degrees of success. Mozilla's XML Binding Language and Microsoft's HTML Component specifications date back all the way to Internet Explorer 5 almost 20 years ago. Unfortunately, both attempts proved unwieldy, failed to gain traction in other browsers, and ultimately were removed. While they may not be around today, their concepts formed the basis of the modern approaches in use. JavaScript frameworks such as React, Vue or Angular follow a similar approach. One of the main reasons for their success is the ability to contain common logic in an easily shareable pattern in one form or another. While these frameworks can improve the developer experience (as can the perfect web hosting service), they do so at a cost. Language features such as JSX need to be compiled, and many frameworks rely on a runtime to manage all of their abstractions. Wouldn't it be easier if there was a way to get the benefit without all that heavy weight? Web components allow us to do just that. Creating an media-heavy site? Get the back up you need with these cloud storage options. The 4 pillars of web components The concept of a web component consists of three APIs – Custom elements, HTML templates and the shadow DOM – with JavaScript modules gluing them together. By combining the benefits that these technologies provide, it's possible to start building custom HTML elements that look and behave just like their native counterparts. Using a web component is much like using any other existing HTML element. They can be configured using attributes, queried for using JavaScript, and even styled through CSS. As long as the browser knows they exist, they are treated no differently. This also allows web components to play well with other frameworks and libraries. By using the same communication mechanisms as any other element, they can be used alongside any framework that exists today or in the future. Most importantly of all, these are all built upon web standards. The web is built on a concept of backwards compatibility, and by building a web component today, it will carry on working for years to come. But before going any further, we should take a look at what makes up these specifications, and how you can get creating and using one today. 01. Custom Elements Key features: - Define an element's behaviour - React to attribute changes - Augment existing elements When you hear people talk about 'web components,' quite often they are referring to the workings underneath – the custom elements API. With this API, it is possible to create classes that power the inner workings of an element. They detail exactly what to do when an element is added, updated or removed. class ExampleElement extends HTMLElement { static get observedAttributes() { return […]; } attributeChangedCallback(name, oldValue, newValue) {} connectedCallback() {} } customElements.define("example-element", ExampleElement); Each custom element has a similar structure. They extend an existing HTMLElement class, which provides the groundwork for how an element should behave. Inside, there are a few methods called reactions that are called in response to something about that element changing. For example, connectedCallback will be called when the new element appears on screen. These work similarly to the lifecycle methods found in most JavaScript frameworks. Updating the attributes on an element can change how it behaves. When an update happens, the attributeChangedCallback reaction will fire, which details the change. This will only happen for an attribute that is defined inside the observedAttributes array. An element needs to be defined before the browser can do anything with it. The define method here takes two arguments – the tag name, and the class it should use. All tag names must contain a - character to avoid any clashes with any future native elements. <example-element>Content</example-element> The element can then be written anywhere in the page as a regular HTML tag. Once a browser has an element defined, it then finds any of these matching tags and links up their behaviour to the class in a process known as 'upgrading'. There are two types of custom element – 'autonomous' or 'customised built-in'. Autonomous custom elements, which have been covered up until now, are not related to any existing element. Much like a <div> or <span> they do not provide any meaning to their content. A customised built-in element – as the name implies – can enhance an existing element with new functionality. They maintain that element's normal semantic behaviours, while also being open to change. If an <input> element was customised, for example, it would still be picked up and submitted as part of a form. class CustomInput extends HTMLInputElement {} customElements.define("custom-input", CustomInput, { extends: "input" }); The class of customised built-in component extends the class of the element it is customising. The definition also needs to define the tag of that element through its third argument. <input is="custom-input" /> They are also used slightly differently. Instead of a new tag, they extend the existing tag by using the is attribute. The browser can read this, and upgrade them in the same way as it can an autonomous component. While most browsers support autonomous custom elements, Only Chrome and Firefox support customised built-in elements. If used in a browser that does not support them, they will fall back to the regular versions of the elements they customise, which can make them safe to use. 02. HTML Templates - Create ready-made structures - Inert until called upon - Contains HTML, CSS and JS Historically, browser-based templating involved stitching strings together in JavaScript, or using a library like Handlebars to parse a block special markup. More recently, the HTML templates specification defined the <template> tag, which can contain anything likely to be reused. <template id="tweet"> <div class="tweet"> <span class="message"></span> Written by @<span class="username"></span> </div> </template> On its own, it has no appearance and remains inert, meaning nothing inside is parsed or executed until told to, including requests for external media such as images or video. JavaScript cannot query the contents either, as browsers will only see it as an empty element. const template = document. getElementById("tweet"); const node = document. importNode(template.content, true); document.body.appendChild(node); A regular query will pick up the <template> element itself. The importNode method creates a copy of its contents, with the second argument telling it to take a deep copy of everything. Finally, it can be added to the document like any other element. Templates can contain anything an HTML page can, including CSS and JavaScript. As soon as the element is applied to the page, those styles apply and the scripts execute. Bear in mind that these will run globally and so can override styles and values if care isn't taken. The best part about templates is that they are not just limited to web components. The examples here apply to any web page, but become particularly powerful when paired with web components, in particular the shadow DOM. 03. Shadow DOM - Avoid styles leaking out - Naming becomes simpler - Keep implementation logic inside The Document Object Model – or 'DOM' – is how the browser interprets the structure of a page. By reading through the HTML, it builds up an idea on what elements in the page contain what content, and uses that to decide what to show. When using something like document.getElementById() the browser is actually looking through the DOM. That may be okay for the layout of a page, but what about the implementation details inside an element? Pages shouldn't need to worry about what makes up the interface inside a <video> element for example. That is where the shadow DOM comes in. <div id="shadow-root"></div> <script> const host = document. getElementById("shadow-host"); const shadow = host.attachShadow ({ mode: "open"}); </script> A shadow DOM is created when applied to an element. Any content can be added to the shadow DOM just like the regular – or 'light' – DOM, but it has no effect on what's happening outside of it. Likewise, nothing in the light DOM can access the shadow DOM directly. This means we can add classes, styles and scripts anywhere in the shadow DOM without worrying about clashes. The best use of the shadow DOM with web components comes when coupled with a custom element. By having a shadow DOM in charge of the content, any time this component is reused, its styles and structure will not affect the rest of the page. 04. ES and HTML Modules - Add in where needed - No build step requirement - Keep everything in one place While the previous three specifications have had relatively straightforward paths to success, the packaging and reusability of them has long been a sticking point. Originally, the HTML Imports specification defined a way for browsers to include HTML documents, much like CSS or JavaScript is already today. This would allow custom elements, along with their templates and shadow DOM, to live elsewhere and imported as needed. Firefox chose not to implement HTML Imports in its browser, and instead favoured a newer specification around JavaScript module importing. export class ExampleElement extends HTMLElement {…} import { ExampleElement } from "ExampleElement.js"; Modules do not apply their content globally by default. By marking certain variables, functions or classes as exported, they can then be imported by anything that needs them and used as if they were local. This is a great help to web components, as a custom element containing a template and a shadow DOM can be exported from one file and added to another. As long as it gets defined somewhere along the line, it is ready to use. import { ExampleElement } from "ExampleElement.html"; An extension to this specification has been proposed to bring back some of the ease of HTML imports, alongside module imports. They will allow web components to be written using declarative and semantic HTML. Spearheaded by Microsoft, this feature is soon coming to Chrome and the Chromium-powered Edge browser. Next page: How to build you own components
https://www.creativebloq.com/features/web-components
CC-MAIN-2021-31
refinedweb
1,886
62.58
I recently finished writing Mastering Perl, the third in the progression of Perl tutorial books from O'Reilly Media. In Learning Perl, we wanted to show the 80 percent of Perl that most people use all of the time. That's good enough to write short script of around 100 lines or so. Next, in Intermediate Perl, we showed how to write reusable code that you could share with others, as well as how to write more complicated programs. When it came to writing Mastering Perl, I considered all of the things that were usually missing from the Perl applications I saw in code reviews. What were Perl programmers missing? I thought about the life cycle of a typical Perl program. You write a quick hack on Friday afternoon to get something done and then leave for the weekend having accomplished your job, leaving the world a better place. Next Monday, you mention it to Adele, a colleague, and she wants to use it too, so you send her a copy. Another programmer, Bob, wants to use it too, but needs it to work a bit differently. He's a Java guy and doesn't know that much Perl. The change isn't that bad, so you make the modification and send it to him. In the meantime, Adele made her own modifications and passed it on to Charlie. Pretty soon, your Friday afternoon hack has become mission critical software--how'd that ever happen? Besides your regular work, you're now supporting this script in all of its forms. Dave, the sysadmin, uses find and discovers 17 similar versions of your program--and that's just on one machine. Now, instead of getting your own work done, you are helping everyone else get his or her work done. What seemed to be a timesaver for your immediate problem is now sucking away your time. I've been in a couple of situations like this when I was a beginning Perler, and along the way I've picked up some things to avoid these situations. You don't have to start every program with the five features I'll show, but once you start using a program for more than just a quick hack, these tips can save you a lot of time supporting your Perl application. Next to the headings, I've provided the corresponding chapter number from Mastering Perl. Everyone writes sloppy code. It just goes with the territory. You start testing an idea, then replace half of that code with something else, and all the while the braces, indents, and idioms get more and more out of sync. You can't be bothered to worry about those with lunch coming up in a half hour! But now other people are looking at your code. It's time to impress them with your beautiful coding style! In addition, other people might have an easier time working with your code when it's easier to read. perltidy, which you get by installing the Perl::Tidy distribution, reformats your code to look consistent. Write a bunch of slop and run it through perltidy, and it comes out sparkling clean with things aligned and indented. By default it uses the style outlined in the perlstyle documentation, but it's also configurable. It puts the reformatted script in a new file so you don't lose the original. I've intentionally obfuscated this word counting program, which I now want to reformat: #!/usr/bin/perl;} perltidy turns it into a much more readable form: % perltidy word_counter.pl # output in word_counter.pl.tdy % cat word_counter.pl.tdy #!/usr/bin/perl # yucky; } Many editors have perltidy plug-ins too, such as emacs and vim, so you can apply it to a section of code as you edit. You don't have to tell anyone you got help with the formatting. Just say that you always code like that. That's only for the format of the code, though--what about cleaning up the actual code? The perlcritic program, which comes with Jeffrey Thalhammer's Perl::Critic module, finds violations of Damian Conway's Perl Best Practices. You can set the severity level to get the granularity you want. Start with the worst offenses first, because it gets really picky in the end. The severity levels start at 5 for the worst violations, and go down to 1 for the very picky warnings: % perlcritic -severity 5 program.pl You can then work your way down to the annoying nits (that you fix to make it seem like you're working between checkups on your World of Warcraft character). perlcritic is highly configurable too, and you can write your own subclasses to check things in your local coding policy, modify or turn off the policies already in place, or use third-party policy modules. The cute hack you did Friday afternoon is now running all over the company, and maybe even some of your friends outside of work have heard about it and want it too, but with a couple of changes. Why can't everyone just use the same script? The trick is to change the behavior of the script without changing the code, saving you the effort of editing the script every time a new person wants to use it. Luckily, Perl comes with a number of ways to make your code configurable. For example, have you ever looked at Perl's -s switch (see the perlrun documentation)? It's the poor man's option parsing, although that's often enough to get started. It turns single-hyphen switches on the command line into package variables: #!/usr/bin/perl -sw use strict; use vars qw( $a $abc ); print "The value of the -a switch is [$a]\n"; print "The value of the -abc switch is [$abc]\n"; Perl has several modules for more powerful parsing of command-line options (89 last time I counted). However, you can probably get everything you want from either Getopt::Std or Getopt::Long, both of which come with Perl. The Config::Inifiles module handles the format that Windows made popular, and it gives values a scope: [Debugging] ;ComplainNeedlessly=1 ShowPodErrors=1 [Network] email=brian.d.foy@gmail.com [Book] title=Mastering Perl publisher=O'Reilly Media author=brian d foy Once you use Config::Inifiles to load the configuration information, you use its val method to specify a section and value to access: #!/usr/bin/perl # config-ini.pl use Config::IniFiles; my $file = "mastering_perl.ini"; my $ini = Config::IniFiles->new( -file => $file ) or die "Could not open $file!"; my $email = $ini->val( 'Network', 'email' ); my $author = $ini->val( 'Book', 'author' ); print "Kindly send complaints to $author ($email)\n"; There are several other Perl configuration modules, and there's probably already one for the format that you're using. Check out the Config:: namespace on the Comprehensive Perl Archive Network for more details. I wish I had known how easy logging could be when I was starting to use Perl. It's even easier with Michael Schilli's port of log4j, the Java logging package, to Perl. With Log::Log4perl, you can easily log messages of different priorities using almost any format you like, and send those messages to one or more destinations (or even no destination at all.) For instance, you can send very important messages to the pager of the operator on duty, but normal messages to a logfile. The easy method takes no configuration. Here's the quick-n'-dirty example from the Log::Log4perl documentation: use Log::Log4perl qw(:easy); Log::Log4perl->easy_init($ERROR); DEBUG "This doesn't go anywhere"; ERROR "This gets logged"; You can configure the logger minutely, and you use the same methods to send messages. I won't go into the details of the configuration format here (there are more than enough examples in the links on the log4perl project page), but you can define different loggers. This one is called root.logger.rhea. use Log::Log4perl; Log::Log4perl::init_and_watch('/etc/log4perl.conf',10); $logger = Log::Log4perl->get_logger('root.logger.rhea'); $logger->debug('This is a debugging message'); $logger->info('This is just for information'); $logger->warn('etc'); $logger->error('..'); $logger->fatal('..'); Inside your program, that's all you have to do. When you want to see the debugging messages, you change the configuration to do something with the messages sent to the debug method. Otherwise, the logger ignores those. No more commenting out those print STDERR statements. Log::Log4perl can even check the configuration file periodically at an interval you define, so you can change the logging behavior on the fly. You don't have to take down your application to increase the logging level it is using. Persistence lets your program pick up where it left off, among other things. You can save data in one run of a program and use it in another run of the same program, or even in a different program. You can even use the data with a different program on a different machine. Unfortunately, there isn't a good way to re-create sockets, filehandles, or other such features, but that's life. The Storable module, which comes with Perl, can "freeze" data in a machine-readable and platform-neutral manner. The result of nfreeze is a string. You can send that over a socket, store it in a file, or anything else you can do with a string. Once you want it back, you thaw it: #!/usr/bin/perl # storable-thaw.pl use Business::ISBN; use Data::Dumper; use Storable qw(nfreeze thaw); my $isbn = Business::ISBN->new( '0596102062' ); my $frozen = eval { nfreeze( $isbn ) }; if( $@ ) { warn "Serious error from Storable: $@" } my $other_isbn = thaw( $frozen ); print "The ISBN is ", $other_isbn->as_string, "\n"; The DBM::Deep module makes disk-based data available to your program as a regular Perl data structure. You create the database with DBM::Deep, which returns a hash reference. You treat that as a normal hash reference and DBM::Deep stores or fetches the data on disk. The data sticks around until you delete the file: use DBM::Deep; my $isbns = DBM::Deep->new( "isbns.db" ); if( $isbns->error ) { warn "Could not create database: " . $isbns->error . "\n"; } $isbns->{'0596102062'} = 'Intermediate Perl'; For the past couple of years, I've been writing all of my Perl programs as modulinos, or modules that can act like programs depending on how I call them. You can look at my Perlmonks article, "How a script becomes a module," for more details . If I call it as a program, it runs like a program, but if I use it as a module, it loads its subroutines without running. In C or Java (among other languages), you use a main() routine to specify where the program should start. Perl, being the "do what I mean" sort of language it is, simply treats everything in the file that isn't a routine as the main program. In C, you have to use a main subroutine that the program automatically calls for you when you run it: #include <stdio.h> int main( void ) { printf( "Hello World!\n" ); return(1); } In Perl, you don't need to do all that extra typing. Perl wants to get you to the solution as soon as possible, so it does away with C<main> by wrapping a virtual routine around the entire file: #!/usr/bin/perl print "Hello World!\n"; You could do a bit more work to get it back to the explicit definition of a C<main> subroutine, which you then have to call yourself to get the program to do anything: #!/usr/bin/perl main(); # executes at run-time sub main { print "Hello World!\n"; } Here's where it starts to get interesting. When you put all the functionality into subroutines, you've really written a library (or a class). You can make the function look more like object-oriented code because you're already thinking about letting other users override parts of it through a subclass. Thinking that, you only execute the main subroutine when you call the file as a program directly, and not when you use it like a module. The caller function takes care of that: package Local::MyProgram; __PACKAGE__->main() unless caller; # executes at run-time, unless used as module sub main { my $self = shift; print $self->string, "\n"; } sub string { "Hello World!" } When Adele wants to change something in the program, she doesn't have to edit the source. She just subclasses your module and overrides the parts that she wants to change: package Local::AdeleProgram; use base qw(Local::MyProgram); __PACKAGE__->main() unless caller; # executes at run-time, unless used as module sub string { "Guten Tag!" } Besides this benefit, you also have an easier time testing your program because you've broken it into distinct parts that lend themselves to unit testing. You can test the parts without running the entire program. brian d foy is a Perl trainer for Stonehenge Consulting Services and is the publisher of The Perl Review. Return to ONLamp.
http://www.oreillynet.com/lpt/a/6987
CC-MAIN-2014-15
refinedweb
2,184
62.07
FUNK OFF :chart_with_upwards_trend: An over-powered engine to evaluate mathematical graph functions. :chart_with_upwards_trend: About :books: The other day I wanted to compute a number of values for a function formula. I wondered how I could implement a function that handles cubes, squares and linear functions fed into a code function as a string and produce a list of values as Ys from a given list of Xs. Funk Off is that library. It supports linear functions, quadratic functions, and cubic functions! Installation :inbox_tray: Adding to your project To add Funk Off to your project's dependencies, add this line to your project's pubspec.yaml: From GitHub depdencies: ... funkoff: git: git://github.com/iamtheblackunicorn/FunkOff.git From Pub.dev depdencies: ... funkoff: ^1.4.0 Usage :hammer: Importing Import the engine-API like this: import 'package:funkoff/funkoff.dart'; Note :scroll: - Funk Off :chart_with_upwards_trend: by Alexander Abraham :black_heart: a.k.a. "The Black Unicorn" :unicorn: - Licensed under the MIT license.
https://pub.dev/documentation/funkoff/latest/
CC-MAIN-2021-31
refinedweb
159
51.04
STANDARDIZED OCCUPATION & INDUSTRY CODING SOIC Manual SOIC Manual Appendices NOTE: This page is archived for historical purposes and is no longer being maintained or updated. APPENDIX A: Installing the SOIC System on Your Computer To install the SOIC System, your computer must have Microsoft Windows 95, 98, 2000, Millennium, or NT, and at least 30 megabytes of free disk space. We also recommend that your computer have at least a 90MHz Pentium CPU with 32 megabytes of RAM. We have not established any minimum CPU and RAM requirements over and above the CPU and RAM requirements of Windows itself. However, the program has not been tested on anything less than a 486 DX2/66 with 32 megabytes of RAM, and we make no guarantees of performance on older, slower systems. The SOIC System requires Microsoft Internet Explorer (IE). The SOIC System is not Internet enabled and does not make use of the IE browser. Nevertheless, the program must have certain supporting files that are used by a variety of Windows applications, and these files are normally distributed with IE. Note that if you access the Internet from the same computer that runs the SOIC System, you do not need to use IE as your browser! You can, for example, use Netscape Navigator as a browser even if IE is also installed on the system. The version of IE that you must have varies with the version of Windows that you are running. To determine which version of Internet Explorer you have, open Internet Explorer, then go to Help on the menu bar, then "About Internet Explorer." - Windows 2000: Internet Explorer 5.0 or higher - Windows ME: Internet Explorer 5.0 or higher - Windows NT: If you have a version of Internet Explorer that is less than version 5.5, you must run the file scr55en.exe, which is located in the SOIC_Install.ZIP file. - Windows 98: You must have Internet Explorer 4.0 or higher. If you have a version that is less than version 5.5, you must run the file scr55en.exe, which is located in the SOIC_Install.ZIP file. - Windows 95: You must have Internet Explorer 5.0 or higher. If you have a version less than version 5.5, you must run the file scr55en.exe, which is located in the SOIC_Install.ZIP file.. A2.. A3. it. APPENDIX B: SOIC System Data File Formats To be successfully imported into the SOIC System, a text file must be in a text format that the SOIC System can understand. That is, a file must be an "ASCII text file." ASCII (the American Standard Code for Information Interchange) is the standard method of representing alphabetical and numerical characters on mid-sized and small computers, including PCs, Unix systems, the Apple Macintosh, and VAX minicomputers using the VMS operating system. ASCII is not used to represent text on IBM compatible mainframe computers-these computers use an alternate system called EBCDIC. Software programs that copy files from mainframes to smaller systems can almost always translate text files from EBCDIC to ASCII. These programs, however, typically have the option of not translating files, and from time to time an EBCDIC text file is copied to a small system by mistake, and cannot be read. When transferring text files between different types of systems, therefore, always make sure that the transmitting software is set to "text" or "ASCII" (depending on the software), not "binary" or "image." A binary transfer will not translate your file. A second problem is that even systems that use ASCII do not always use the same set of invisible characters to mark the end of a line of text. MS DOS and Microsoft Windows use an invisible carriage return symbol plus an invisible linefeed symbol to make up a combined "carriage return." Pressing ENTER in text entry mode in almost all DOS and Windows programs inserts the combined end of line marker, and ordinarily the way of marking the end of a line is not something you need to worry about. ASCII based operating systems other than DOS or Windows, however, may only use a single invisible carriage return symbol, or a single linefeed symbol. A binary transfer of such a file preserves the foreign end of line marker. Again, a text or ASCII file transfer solves this problem by converting the end of line marker to the DOS standard. For an import to succeed, all lines in the imported text file must be the same length. Some software automatically trims trailing spaces from lines. Each line of the text file must end with the standard DOS carriage return (carriage return + linefeed) in the space immediately after the last space used for field information. If the lines in the text file are 211 spaces long, for example, the DOS carriage return must be in space 212. A text file must also not contain any of the non ASCII formatting characters often inserted by word processing programs. Make sure that the software used to create the file saves it as a pure text file, without formatting characters. Finally, the text file must be organized so that the SOIC System can tell where one field of data ends and another begins, and where one record ends and another begins. The SOIC System expects a text file in which each record consists of a single line, ending with a standard DOS carriage return. The individual fields of each record are in a "columnar" format. That is, each field is identified by its location on the record line, in spaces. For example, in the SOIC System internal format, the first field, Local ID, takes up spaces 1 through 4 of the line. The second field, Temporary ID, takes up spaces 5 through 10. Underlying Cause is in spaces 207-210, and Autopsy is in space 211. It is not necessary that the fields in the imported text file be in the same order as the fields in an internal SOIC System table. Of course, you may find it convenient to keep the fields in that order. If that is not convenient, the field mapping function on import can reorder the fields. The mapping function can also handle cases where imported fields have different lengths than the fields in an SOIC System table. If an imported field contains more characters than the SOIC System allows, the extra characters are trimmed on import. If you attempt to import a text file with lines more than 211 characters long, the SOIC System will ignore all data located past space 211. The import will otherwise succeed. For general information on how the SOIC System handles files, see Section 2.3, "How the SOIC System Manages Tables and Files". For specific information on importing text files into the SOIC System, see Section 2.4.7, "The Import Option". The following table gives the location of the fields in an internal SOIC System data table. For reference, we also give information on the text file format used by the National Center for Health Statistics (NCHS). The SOIC System internal format is based on the NCHS text file format, though the SOIC format has been modified where necessary. Notably, it contains many additional fields. Non-displayed fields that the SOIC System uses for internal purposes are not exported. The exceptions are the fields "ostatus" and "istatus," which are exported but not displayed. The following table gives the code structure for the fields of the NCHS Mortality File. The code structure indicates the possible valid responses and, where the fields are coded, what the codes mean. APPENDIX C: The 998 Insufficient Information Code Based on recommendations from the SOIC Policy Committee, the SOIC Software was designed to assign a code of 998 when there is insufficient information present to reliably assign an informational code. 998 can be assigned to either industry or occupation. The meaning of a 998 assignment is different from that of a 990/999 assignment. 990/999 will continue to be used for blanks, unknown, refused, etc. 998 is not technically a code assignment, but rather an indicator that although there was some information present in the industry or occupation descriptions, that information was insufficient for ascertaining a code. All decisions regarding the criteria by which a case is to be assigned 998 were made by the SOIC Technical Committee. The committee was formed in 1997 and was comprised of a panel of coding experts from the Bureau of the Census (BOC), the National Institute for Occupational Safety and Health (NIOSH), and the National Center for Health Statistics (NCHS). The committee was responsible for reviewing coding conflicts and hard to code cases, and was instrumental in improving the quality of the SOIC software. The use of 998 provides two key benefits: the ability to measure the overall quality of information in a data set, and the ability to identify cases with insufficient information so that they can be returned to their source for clarification whenever possible. The SOIC software offers several features to assist in working with 998 cases. The Find Record option (Section 2.6.6 on page 83) allows you to search for individual records assigned 998 in either industry or occupation. The Print option (Section 2.4.9) allows you to print only 998 cases. For data stored as internal SOIC tables, the Save 998 Codes option (Section 2.4.4.3) allows you to save 998 cases as a separate SOIC or Access
http://www.cdc.gov/niosh/soic/manual/SOIC_Manual11.html
CC-MAIN-2014-23
refinedweb
1,579
62.27
![if !IE]> <![endif]> Sockets A full treatment of socket programming is beyond the scope of this book. However, sockets remain an important way that processes or threads can communicate, so it is worth examining the use of sockets for communication within the same system. A particular advantage of using sockets for communication is that scaling beyond a single system becomes a relatively minor change to the code. The use of sockets is different from other communication mechanisms because the client that opens the socket has different responsibilities than the server connected to the socket. So, it is appropriate to tackle the client and server as two entirely separate applications. The first thing that any process that uses sockets has to do is request a socket. The socket is a potential connection to the network. The call to socket() takes three parameters: the family of socket being requested, the type of socket within that family, and the protocol. The protocol should usually be set to zero to indicate that the default protocol should be used. The protocol family should be AF_INET or AF_INET6, and the protocol type for these two families is either SOCK_STREAM for TCP/IP or SOCK_DGRAM for UDP/IP. Once a socket has been established, it is necessary to connect it to an address. We can best illustrate this by initially working through the code necessary to write a server process that waits for a connection from a client, before discussing the code that would be found in such a client. This makes sense because the two scenarios have little code in common. A server will call bind() with the address of the local host and the port on which it will listen for connections. The function bind() takes as parameters the previously established socket, a pointer to a structure containing the details of the address to bind to, the value INADDR_ANY is typically used for this, and the size of the structure. The par-ticular structure that needs to be used will depend on the protocol, which is why it is passed by the pointer. Once a server has been bound to an address, the server can then call listen() on the socket. The parameters to this call are the socket and the maximum number of queued connections as a parameter. After a call to listen, the server can wait for a connection from a client by calling accept(). The parameters to the accept() call are the socket, an optional pointer to a socket address structure, and the size of the structure. If the pointer to the socket address structure is not zero, the call to accept() will write details of the client into the socket address structure. The call will return a new socket descriptor that is the connection to the client. The server can read from or write to the new socket until the connection is termi-nated by either the client or the server calling close() on the new socket. Data can be sent through the socket using either the write() call or the send() call. The send() call affords some additional flexibility in sending data. Similarly, data can be received from the socket using either the read() or recv() call. A socket that has been closed is indicated by a return of an error from the calls. The code in Listing 5.72 shows the part of the server code that handles echoing data back. While there is still data in the socket, the thread will read that data, write it to stdout, and then echo it back to the socket where it came from. One complexity is that we do not want the server process to call pthread_join() for every thread that it cre-ates to handle an incoming connection. To avoid the call to pthread_join(), each thread immediately calls pthread_detach() once it has been created. This detaches the thread and ensures that any resources that the thread uses are returned to the process when the thread terminates. Listing 5.72 Code for Echo Server Thread #include <pthread.h> #include <stdio.h> #include <unistd.h> void * handleecho( void * param ) { char buffer[1024]; int count; pthread_detach( pthread_self() ); int s = (int)param; while ( count = read( s, buffer, 1023 ) > 0 ) { buffer[count] = 0; printf( "Received %s \n", buffer ); write( s, buffer, count ); } close( s ); } The more interesting part of the code is the code to set up the server, as shown in Listing 5.73. The server sets up a socket and binds this to port 7779. It also configures the socket to hold a queue of up to five connections. The server then listens on the socket for incoming connections. When a connection arrives, the server creates a new thread to handle this connection and passes the socket number as a parameter to the new thread. The resulting application needs to be linked with the socket library (-lsocket) and the network services library (-lnsl). Listing 5.73 Code to Set Up the Server #include <sys/types.h> #include <sys/socket.h> #include <strings.h> #include <arpa/inet.h> int main() { int newsocket; int s = socket( AF_INET, SOCK_STREAM, 0 ); // TCP/IP socket struct sockaddr_in server; bzero( &server, sizeof(server) ); // Clear address structure server.sin_family = AF_INET; // TCP/IP family server.sin_addr.s_addr = INADDR_ANY; // Any address server.sin_port = 7779; // Port to bind to bind( s, (struct sockaddr*)&server, sizeof(server) ); listen( s, 5 ); // Queue of five outstanding connections while ( newsocket = accept( s, 0, 0 ) ) { pthread_t thread; pthread_create( &thread, 0, handleecho, (void*) newsocket ); } } Listing 5.74 shows the client code. In a similar way to the server, the client sets up a socket. However, the client calls connect() with the address and port of the system that it wants to connect to. Once the call to connect() completes, the client can start sending data to the server and receiving data back from the server using the socket. In Listing 5.74, the client sends a string to the server and then prints out the data returned by the server. Listing 5.74 Client Code That Sends Data to a Server and Prints Response #include <sys/types.h> #include <sys/socket.h> #include <strings.h> #include <arpa/inet.h> #include <unistd.h> #include <stdio.h> int main() { int s = socket( AF_INET, SOCK_STREAM, 0 ); // TCP/IP socket struct sockaddr_in server; bzero( &server, sizeof(server) ); // Clear address structure server.sin_family = AF_INET; // TCP/IP family server.sin_addr.s_addr = inet_addr( "127.0.0.1" ); // Local machine server.sin_port = 7779; // Port to bind to if ( connect( s, (struct sockaddr*)&server, sizeof(server) ) == 0 ) { printf( "Sending 'abcd' to server\n" ); char buffer[1024]; strncpy( buffer, "abcd", 4 ); write( s, buffer, strlen(buffer) ); int count = read( s, buffer, 1024 ); buffer[count] = 0; printf( "Got %s from server\n", buffer ); shutdown( s, SHUT_RDWR ); } } Sockets represent a convenient way of communicating between a number of inde-pendent processes that are spread over one or more systems. They are a good approach if it is expected that the application will end up scaling beyond a single system. Related Topics Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.
https://www.brainkart.com/article/Sockets_9465/
CC-MAIN-2019-51
refinedweb
1,183
63.9
Custom ASP.NET controls The ASP.NET controls in the Toolbox panel are the controls provided by the Microsoft .NET Framework Versions 2.0 and 3.5. At times, you might need functionality in a control that is not provided by the built-in ASP.NET controls. In those cases, you can use a custom ASP.NET control created by a developer or a third party software vendor. You can use custom controls developed by others, such as those featured in the Control Gallery on the Microsoft ASP.NET website, or create custom controls by using a visual design tool such as Microsoft Visual Studio. Working with custom ASP.NET controls To work with a custom ASP.NET control in Microsoft Expression Web, you need to do three things: Make the custom control available to Expression Web. To do this you can add the custom control's assembly to your website's bin folder or install the custom control into the Global Assembly Cache (GAC) on both your computer and your web server. For information, see Add a custom ASP.NET control to a website. Reference the custom control in your page or website. To do this you can either add a register directive in the pages you want to use the control or specify the tag prefix and namespace mapping in your website's web.config file. For information, see Reference a custom ASP.NET control. Add the custom control to the Code view of your page. For information, see Add a custom ASP.NET control to a page. Support for custom ASP.NET controls Once you've completed the steps under Working with Custom ASP.NET Server Controls, Expression Web provides virtually the same support for your custom ASP.NET control as is provided for the default set of ASP.NET controls. The only exception is custom ASP.NET controls don't appear in the Toolbox panel or on the Insert menu; Expression Web provides the following for custom ASP.NET controls: ASP.NET IntelliSense and syntax checking in the Code view of your page. Property editing in the Tag Properties panel. Preview in the Design view of your page. Common Tasks smart tag menu in Design view. ASP.NET error messages in Design view. For information about adding a custom control to a web page, see Add a custom ASP.NET control to a page.
http://msdn.microsoft.com/en-us/library/cc295536(v=expression.40).aspx
CC-MAIN-2014-52
refinedweb
398
60.72
Welcome back to Twisted Conch in 60 Seconds, a series about writing custom SSH software with Twisted. Last time, I showed you how to set up a basic SSH server which could accept connections and then reject all authentication attempts. This time we'll extend that server to support password authentication. Let's consider the factory created in the first example: factory = SSHFactory() factory.privateKeys = {'ssh-rsa': privateKey} factory.publicKeys = {'ssh-rsa': publicKey} factory.portal = Portal(None) The object in this snippet responsible for authenticating the client is Portal(None). However, this portal is missing two things it really needs in order to be useful. First, it's missing a username/password checker. Twisted includes one that's easy to use and reads credentials out of a file, so we'll start with that one: from twisted.cred.checkers import FilePasswordDB factory.portal.registerChecker(FilePasswordDB("ssh-passwords")) FilePasswordDB will now try to read information from ssh-passwords in order to authenticate SSH client connection attempts. The file should be populated with lines like this: alice:goodpassword bob:badpassword jpcalderone:supersecretpassword The second thing the Portal needs is a Realm. After the FilePasswordDB says a user supplied the correct username/password combination, Conch needs an object that will represent the user who just authenticated. This object will be used to determine what actions the SSH user is allowed to take, and what consequences they will have. A realm only needs to implement one method: from twisted.conch.avatar import ConchUser def nothing(): pass class SimpleRealm(object): def requestAvatar(self, avatarId, mind, *interfaces): return IConchUser, ConchUser(), nothing After authentication succeeds, requestAvatar is called. The avatarId parameter tells the realm the name of the user who just authenticated successfully. The mind isn't used by Conch. The interfaces indicate what kind of user is being requested; in this case, it will include twisted.conch.interfaces.IConchUser (and we just assume that it does for now). The method must return a three-tuple. The first element is the kind of user the realm decided to give back (this must be one of the requested interfaces - again, we're assuming IConchUser for now). This just lets the calling code know what kind of user it ended up with. The second element is the user object itself. Conch conveniently provides us with a basic user class that implements almost no behavior, so it's suitable to be used directly in this simple example. The final element of the tuple is a logout callable. This will be invoked for us when the user logs out. This example has no custom logout logic, so we return a no-op function. Portal construction will now look like this: factory.portal = Portal(SimpleRealm()) These are all the pieces necessary to do username/password authentication of SSH users. Here's the full code listing for this version: from twisted.cred.portal import Portal from twisted.cred.checkers import FilePasswordDB from twisted.internet import reactor from twisted.conch.ssh.factory import SSHFactory from twisted.conch.ssh.keys import Key from twisted.conch.interfaces import IConchUser from twisted.conch.avatar import ConchUser SimpleRealm(object): def requestAvatar(self, avatarId, mind, *interfaces): return IConchUser, ConchUser(), nothing factory = SSHFactory() factory.privateKeys = {'ssh-rsa': privateKey} factory.publicKeys = {'ssh-rsa': publicKey} factory.portal = Portal(SimpleRealm()) factory.portal.registerChecker(FilePasswordDB("ssh-passwords")) reactor.listenTCP(2022, factory) reactor.run() If you run this server and connect to it with one of the credentials in the password file you provide, then you should receive an extremely gratifying result along the lines of: channel 0: open failed: unknown channel type: unknown channel Sorry! Tune in next time to learn what a channel is and how to define one. Hi Jean-Paul, Is there a simple way to view the passwords handled by the portal? I would like to create a basic ssh honeypot that will log username and password combinations. I am however having a bit of trouble understanding how the authentication is handled (or rather structured) in twisted.conch. I'm aware of kippo, but I require something lighter. Thanks for the great introductions, they are concise, well structured and informative. Hi Samuel. The "credentials checker" gets the username/password information. In this example, `FilePasswordDB` is the credentials checker. This is a well-defined interface and you can supply your own kind of object here, which validates credentials however you like, logs them, etc. The interface is defined here: There's also a more complete introduction to cred in the Twisted docs:
http://as.ynchrono.us/2011/03/twisted-conch-in-60-seconds-password.html
CC-MAIN-2015-11
refinedweb
751
50.33
Provided by: libgit-raw-perl_0.79-6_amd64 NAME Git::Raw::Reference - Git reference class VERSION version 0.79 DESCRIPTION A Git::Raw::Reference represents a Git reference. WARNING: The API of this module is unstable and may change without warning (any change will be appropriately documented in the changelog). METHODS annotated_commit( ) Create a Git::Raw::AnnotatedCommit from the reference. lookup( $name, $repo ) Retrieve the reference with name $name in $repo. create( $name, $repo, $object [, $force, $symbolic] )( ) Delete the reference. The Git::Raw::Reference object must not be accessed afterwards. name( ) Retrieve the name of the reference. shorthand( ) Get the reference's short name. This will transform the reference name into a "human- readable" version. If no shortname is appropriate, it will return the full name. type( ) Retrieve the type of the reference. Can be either "direct" or "symbolic". target( [$new_target] ). peel( $type ) Recursively peel the reference until an object of the specified $type is found. Valid values for $type include: "commit", "tree" or "tag". reflog( ) Retrieve the Git::Raw::Reflog of the reference. Shortcut for "Git::Raw::Reflog->open()". owner( ) Retrieve the Git::Raw::Repository owning the reference. is_branch( ) Check if the reference is a branch. is_remote( ) Check if the reference is remote. is_tag( ) Check if the reference lives in the "refs/tags" namespace. is_note( ) Check if the reference lives in the "refs/notes" namespace..
http://manpages.ubuntu.com/manpages/disco/man3/Git::Raw::Reference.3pm.html
CC-MAIN-2019-30
refinedweb
225
54.08
AnnoCPAN::Control - Main AnnoCPAN Web Interface Control Module # in the simplest case, this is all you need... use AnnoCPAN::Control; AnnoCPAN::Control->new->run; This is the main module that handles the AnnoCPAN web application. It handles getting the CGI parameters, running the appropriate handlers, and making sure that the appropriate templates are processed. Create a new AnnoCPAN control object. Options: cgi => cgi object tt => template object Process the request. This includes figuring out the runmode, checking if the user is logged in, running the handler, printing the headers, and processing the template. Return the runmode. Runmodes must be made of word characters, begin with an uppercase letter, and be a method in $obj. Returns the CGI object. Returns the Template object. Get CGI parameters. Delegated to $self->cgi. Return HTTP headers as a string. Delegated to $self->cgi. Print a 303 HTTP redirect header, including the cookies in $obj->cookies. Process a template. Delegated to $self->tt. Return a hashref with the default template variables, common to all runmodes (for example, the user object). Returns the value for a given user preference. Return an arrayref with the current cookies (which are CGI::Cookie objects). Create a cookie. It will be later pushed to the client with the HTTP headers, and it is immediately available via $obj->cookies. Issue an expired cookie with a given name, forcing the client to forget it (one use is for logging out). Check if the user is logged in (by checking the login, time, and key cookies); Returns an AnnoCPAN::DBI::User object if logged in, or false if not. Creates the login cookies for $user (which should be an AnnoCPAN::DBI::User object). May be used to set an arbitrary user (to force a login). If no $user is provided (and none has been provided before), returns whatever check_login would return (a user object or false). Returns a login key as a string. Depends on the "secret" configuration option. A runmode method has the following characteristics: 1) Its name matches /[A-Z]\w+/ 2) Returns a list ($vars, $template, $type). $vars is a hash reference of variables that should be passed to the template; $template is the name of the template that should be processed (sans the extension). $type is the MIME type that should be given in the header. $type is optional; it defaults to text/html. If $template is false, no headers will be printed and no template will be processed. 3) Takes an optional parameter $vars. If given, it is expected to be a hash reference which will be appended to the variables normally returned by the method. It is used when one mode decides to fall back to another but wants to add or override some variables of its own. For example, the Main method could be: sub Main { my ($self, $vars) = @_; $vars ||= {}; my @recent = AnnoCPAN::DBI::Note->search_recent; ({recent => \@recent, %$vars}, "main"); } Warning: the documentation below may be slighly incomplete or outdated: The front page. Provides the "recent notes" list. Displays one POD page. Uses the pid CGI parameter. Displays the POD page that is the "main reference" for a given note. Uses the id CGI parameter. Displays one distribution (distver) page. Uses the id CGI parameter or $vars->{distver}. The edit screen (like Show, but includes the edit form). The "about" page. Uses the about.pod file. Save a new note (comes from the Edit mode). Uses the pid, pos, id, and note CGI parameters. "Create new user" screen. Coming from the New_user form, create a new account. Uses the login, passwd, passwd2, and email CGI parameters. Checks that the login and password are not blank, that the passwords match, and that the login is not already taken. Log in; comes from the login form on login_form.html. Uses the login and passwd CGI parameters. Log out. Clears the authentication key. AnnoCPAN::DBI,.
http://search.cpan.org/dist/AnnoCPAN/lib/AnnoCPAN/Control.pm
CC-MAIN-2014-41
refinedweb
647
68.87
The uncompromising code formatter - with single quotes as default. Project description The Uncompromising Code Formatter “Any color you like.” ...as long as it has single quotes. This is an alternative to the official black formatter, which is letting line len configurable but (too?) strict about single quotes, unfortunatelly. We do hope they change their minds so this fork is not necessary any more. This version based on a PR fixing this. Morevover we made single quotes even default. axblack - Default Style """ Module doc """ def foo(): """func doc""" # double quotes for docstrings s = 'hello world' # single quotes for code m = {'a': 'b'} Note that we wanted to keep the offset minimal and not deviate more than necessary. Therefore via the vim plugin and also the blackd server you do not have the option to set double quotes - you have to use the --double-quotes command line flag as only way to get them. Should you prefer them for private projects or find them in project policies, by any means, use the official black version then. Changelog [2019-11-24 11:21] - Set single_quotes as default in black.py class File, so that it works also in vim. [2019-11-24 11:21] - Recreated repo as direct fork of psf/black, with adapted master branch for easier future merges from them (and getting their newest improvements) [2019-11-23 21:16] - Dropped the -s in favor of the long argument "double-quotes" - to never collide with any argument of theirs. Default for double-quotes: False - Bugfixed the parsing of single-quotes - Added the cf tool. [2019-11-23 18:05] - Added more README (Usage) [2019-11-23 15:05] Initial version after: git clone axblack git reset --hard configure-quote-style git reset --hard remotes/origin/configure-quote-style - Set default=Trueinto black.py - Created axblack pip and pushed to pypi. Installation pip install axblack into a python3 v(irtual)env or conda environment. See also original docu below - exchange "psf/black" with "axiros/axblack". Vim Setup Install black into a python environment and refer to it via g:black_virtualenv as shown in the example, then the plugin will install a venv into .vim/black! Also, note that it proves very handy to have formatting being done at each file write. Suggested vim setup Plug 'axiros/axblack' " not black related but useful: autocmd FileType python map <Leader>e Otry:<Esc>j^i<TAB><Esc>oexcept Exception as ex:<CR>print('breakpoint set')<CR>breakpoint()<CR>keep_ctx=True<Esc>^ " defaults: let g:black_linelength = 88 let g:black_fast = 1 " set appropriately: let g:black_virtualenv = "<set to base dir of a py3 environ with black installed>" " Clean whitespace at saves: "autocmd BufWritePre * execute ':RemoveWhitespace' fun! Blackify() if &ft =~ 'python' :Black endif endfun " blackify at any write of a python file: autocmd BufWritePre * call Blackify() " Using pythonmode? Keep it happy: let g:pymode_options_max_line_length = 88 let g:pymode_lint_options_pep8 = {'max_line_length': g:pymode_options_max_line_length} let g:pymode_options_colorcolumn = 1 Usage In Projects pyproject.toml Create a pyproject.toml file in the toplevel directory of your project as shown below and adapt the exclude directories according to your needs. Example `pyproject.toml` [tool.black] line-length = 88 target-version = ['py37'] include = '\.pyi?$' exclude = ''' ( /( \.eggs # exclude a few common directories in the | \.git # root of the project | \.hg | \.mypy_cache | \.tox | \.venv | _build | build | dist )/ | foo.py # also separately exclude a file named foo.py in # the root of the project ) ''' Then black . will reformat from the current directory, recursively (not above this directory). If you have a mix of python2 and python3 in your project then create a specific pyproject.toml within the respective top level directory and run black for each of them seperately. black always searching up the specified directory on the command line for the first project toml file and uses it. Conversion of Large Existing Code Bases Black ensures to not break anything, by comparing ASTs before and after formatting - which slows it down a bit. If the code base is large you want to normally have fast mode on, therefore, in daily work. This is what you do: Create your project toml file with excludes which shall never be formattet. Run black with --safeon. If all can be converted then good, you can add --fastfrom now on or put it even into your toml file. Should you have errors from the AST check then, before any run in fast mode either - exclude those files within the toml - fix them. From experience this often hints to bugs. Example: error: cannot format .../sleekxmpp/thirdparty/gnupg.py: INTERNAL ERROR: Black produced different code on the second pass of the formatter. Again: Do not run black in fast mode if you had errors in safe mode! It will produce source code which is potentially off, behaviourally, from the original! Coding Policy Enforcement With more collaborateurs on the same repo (e.g. at a customer site) you may want to consider enforcing your code style via a repo hook: Repo Hook Example # cat .git/hooks/pre-commit #!/bin/sh # We reject any commit for unformatted source code # We can't fix here since we might have partial hunks, which after reformat, which is # global, would differ in the non committed hunks from the state in the FS: /dev/null || exit 1 echo "Accepted." done || { echo "Commit rejected - not all files formatted correctly." echo "Please do so now: $black -h" exit 1 } Wrapper Tool If you - can't adopt pyproject.toml but want to stick to shell sourceable config and /or environ based config - require composition of such config - easily want to run in client server mode, for speed - require automatically created skip lists then have a look at this code formatter tool we created, which wraps black and blackd. The tool is not installed by pip currently. Original docu follows...: | Code style | pyproject.toml | Editor integration | blackd | Version control integration | Ignoring unmodified files | Used by | Testimonials | Show your style | Contributing | Change Log |was used). NOTE: This is a beta product Black is already successfully used. # in: l = [1, 2, 3, ] # out: l = [1, 2, 3] If not, Black will look at the contents of the first outer matching brackets and put that in a separate indented line. #. A compatible `.isort.cfg` [settings] multi_line_output=3 include_trailing_comma=True force_grid_wrap=0 use_parentheses=True line_length=88 The equivalent command line is: $ isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --use-parentheses --line-width=88 [ file.py ]instead. Example `pyproject ) ''' Lookup hierarchy Command-line options have defaults that you can see in -: - Install black. $ pip install black - Make sure it runs from the command line, e.g. $ black --help - - Select a file in the editor and press F1 , or whatever key binding you selected in step 3, to reformat the file. Vim Commands and shortcuts: :Blackto format the entire file (ranges not supported); :BlackUpgradeto upgrade Black inside the virtualenv; :BlackVersiontocommandheader: []() Using the badge in README.rst: .. image:: :target:. Change Log unreleased added black -casblocks with comments (#829) removed unnecessary parentheses around yieldexpressions (to control which Python versions Black-formatted code should target (#618) deprecated --py36(use --target-version=py36instead) (#724) Black no longer normalizes numeric literals to include _separators (#696) long delstatementsnow supports CORS (#622) 18.9b0 numeric literals are now formatted by Black (#452, #461, #464, #469): numeric literals are normalized to include _separators on Python 3.6+ code added --skip-numeric-underscore-normalizationto for more info (#349) adjacent string literals are now correctly split into multiple lines (#463) trailing comma is now added to single imports that don't fit on a line (#250) cache is now populated when --checkwhen directly preceding yieldand other nodes (#385) fixed formatting of lambda expressions with default arguments (#468) fixed async forstatements:and # fmt: onare -hequivalent to --help(#316) fixed improper unmodified file caching when -Swand --exclude(#270) added --skip-string-normalization(#118) added --verbose(#283) the header output in --diffnowsections (is removed on Python 3.6+ only code and Python 2.7+ code with the unicode_literalsfutureand --diffarenotwithusageand # fmt: onareor **kwargsused. 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/axblack/
CC-MAIN-2019-51
refinedweb
1,354
53.81
- NAME - DESCRIPTION - Core Enhancements - Security - Incompatible Changes - Modules and Pragmata - Documentation - Diagnostics - Configuration and Compilation - Platform Support - Internal Changes - Selected Bug Fixes - Known Problems - Acknowledgements - Reporting Bugs - SEE ALSO NAME perldelta - what is new for perl v5.23.7 DESCRIPTION This document describes differences between the 5.23.6 release and the 5.23.7 release. If you are upgrading from an earlier release such as 5.23.5, first read perl5236delta, which describes differences between 5.23.5 and 5.23.6. Core Enhancements New . Security] Incompatible Changes Modules and Pragmata Updated Modules and Pragmata The cpan/podlators/ bundle has been upgraded from version 2.28 to 4.04. B has been upgraded from version 1.61 to 1.62. B::Deparse has been upgraded from version 1.36 to 1.37. Benchmark has been upgraded from version 1.21 to 1.22. bignum has been upgraded from version 0.41 to 0.42. Data::Dumper has been upgraded from version 2.159 to 2.160. ExtUtils::ParseXS has been upgraded from version 3.30 to 3.31. ExtUtils::Typemaps has been upgraded from version 3.30 to 3.31. File::Find has been upgraded from version 1.32 to 1.33. File::Spec has been upgraded from version 3.60 to 3.62. Math::BigInt has been upgraded from version 1.999710 to 1.999715. Math::BigInt::FastCalc has been upgraded from version 0.38 to 0.40. Math::BigRat has been upgraded from version 0.260801 to 0.260802. Module::CoreList has been upgraded from version 5.20151220 to 5.20160120. Pod::Usage has been upgraded from version 1.67 to 1.68. Test::Harness has been upgraded from version 3.35 to 3.36. Unicode::Normalize has been upgraded from version 1.24 to 1.25. Unicode::UCD has been upgraded from version 0.63 to 0.64. utf8 has been upgraded from version 1.18 to 1.19. Documentation Changes to Existing Documentation perlsyn Fixed a broken example where =was used instead of ==in conditional in do/while example. perlfunc Better explain meaning of negative PIDs in waitpid. [perl #127080] perlgit Move sample commands into verbatim paragraphs. Improve hyperlinks for all email addresses, RT tickets and commit hashes. Consistently refer to bisect.pl as Porting/bisect.pl Miscellaneous grammar and POD fixes. perlreftut perlrebackslash Clarify that in languages like Japanese and Thai, dictionary lookup is required to determine word boundaries. Diagnostics The following additions or changes have been made to diagnostic output, including warnings and fatal error messages. For the complete list of diagnostic messages, see perldiag. Changes to Existing Diagnostics Accessing the IOpart of a glob as FILEHANDLEinstead of IOis no longer deprecated. It is discouraged to encourage uniformity (so that, for example, one can grep more easily) but it will not be removed. [perl #127060] Configuration and Compilation Configure no longer probes for libnm by default. Originally this was the "New Math" library, but the name has been re-used by the GNOME NetworkManager. [perl #127131] No longer generate EBCDIC POSIX-BC tables. We don't believe anyone is using Perl and POSIX-BC at this time, and by not generating these tables it saves time during development, and makes the resulting tar ball smaller. The Win32 miniperl now has a real getcwdwhich increases build performance resulting in getcwd()being 605x faster in Win32 miniperl. Platform Support Platform-Specific Notes. Try more crypt algorithms in the tests, for OpenBSD. OpenBSD implements the Blowfish algorithm, but not the MD5 one used by glibc. Enhance the crypt and taint tests to try both algorithms. If neither works, fall back to no algorithm. The Blowfish salt is taken from the OpenBSD crypt(3)page. Use the fdclose()function from FreeBSD if it is available. [perl #126847] Internal Changes The obscure PL_timesbufvariable, effectively a vestige of Perl 1, has been removed. It was documented as deprecated in Perl 5.20, with a statement that it would be removed early in the 5.21.x series; that has now finally happened. [perl #121351] Remove unwarranted assertion in Perl_newATTRSUB_x(). If a stub subroutine definition with a prototype has been seen, then any subsequent stub (or definition) of the same subroutine with an attribute was causing an assertion failure because of a null pointer. [perl #126845] Replace ::with __in ExtUtils::ParseXSlike it's done for parameters/return values. This is more consistent, and simplifies writing XS code wrapping C++ classes into a nested Perl namespace (it requires only a typedef for Foo__Barrather than two, one for Foo_Barand the other for Foo::Bar). Deprecate the to_utf8_case()function, see. Selected Bug Fixes] Fixed some problems introduced in 5.23.2 with list assignment dealing with magic and XS functions returning their arguments. [perl #126633]] Known Problems Statically building perl is not currently working due to a problem related to multiple definitions of the cp1252_encodingin the Encodemodule. Acknowledgements Perl 5.23.7 represents approximately 4 weeks of development since Perl 5.23.6 and contains approximately 87,000 lines of changes across 450 files from 21 authors. Excluding auto-generated files, documentation and release tools, there were approximately 67,000 lines of changes to 320 .pm, .t, .c and .h files. Perl continues to flourish into its third decade thanks to a vibrant community of users and developers. The following people are known to have contributed the improvements that became Perl 5.23.7: Aaron Crane, Andreas König, Andy Dougherty, Chris 'BinGOs' Williams, Craig A. Berry, Dagfinn Ilmari Mannsåker, Daniel Dragan, David Golden, David Mitchell, James E Keenan, Jarkko Hietaniemi, Karen Etheridge, Karl Williamson, Lukas Mai, Mattia Barbon, Ricardo Signes, Stevan Little, Steve Hay, Todd Rinaldo,.
https://metacpan.org/pod/release/STEVAN/perl-5.23.7/pod/perldelta.pod
CC-MAIN-2018-30
refinedweb
943
53.37
Premiere Elements 2009 Premiere Elements MOV to Adobe Premiere, How to convert/import MOV to Adobe Premiere? MOV to Adobe Premiere converter is the greatest converting program to assist you to convert MOV to Adobe Premiere to import MOV to Adobe Premiere including Adobe Premiere Elements, Adobe Premiere Elements 7.0/8.0 and Adobe Premiere Pro, Adobe Premiere Pro CS3/CS4/CS5. Besides, MOV files to Adobe Premiere converter empowers you to input other popular formats like HD video, WMV, AVI, MPG, MP4, FLV, etc and convert them to enjoy video files on iPod, iPhone, PSP, iPad, Apple TV, BlackBerry, iRiver, Creative Zen, Zune, Samsung Propel, Nokia and varied Mobile Phones. The problem you may encounter when you try to edit MOV video with Adobe Premiere. Issue1. Premiere CS3 is giving me a "file format not supported" message when I try to import MOV into a project! Issue2. My friend has given me a lot of footage to edit for him, its HD and all MOV. Does anyone know how to get .MOV Files to import onto Adobe Premiere Pro CS3? Are there any Plug-ins or anything? Issue3. I'm working in Adobe Premiere 1.5 .Every time I import a MOV file it plays back jumpy/ jerky. Any ideas? Download MOV to Adobe Premiere converter here for evaluation. How to solve these problems? MOV to Adobe Premiere converter is the greatest converting program that can accept MOV video files to convert MOV to Adobe Premiere supportable WMV, AVI to import MOV files to Adobe Premiere and edit MOV video with Adobe Premiere. It has an easy-to-use interface for both novice and veteran to handle. MOV to import to Adobe Premiere has many powerful functions to help you crop, trim and add effects. If you need some still images, you can capture your favorite pictures with built in camera in JPG, BMP, PNG format. What's more, you can adjust video resolution, frame rate, bitrate, aspect ratio (original, full, 4:3, 16:9) and audio bitrate, sample rate, channel to get a better watching effect. MOV to Adobe Premiere converter is 100% safe without any virus attached. It could finish the whole conversion with just a few mouse clicks at super high speed. How to convert MOV to Adobe Premiere to edit MOV video files with Adobe Premiere step by step? Step one: Download Download MOV to Adobe Premiere converter and double click .exe to install Step two: Add MOV video files Press "Add Video" button to load MOV files to converter. You can load many files at one time, because it supports batch mode. Step three: Select Adobe Premiere format In the drop down list of Profiles, select WMV, AVI format for AP if you are using windows Note:if you are using Mac,select DV format Step four: edit video files Press "Edit" button to get rid of unwanted objects by cropping and add special effects by effects. You are supposed to adjust aspect ratio among original, full, 4:3 and 16:9. Press "Clip" button to split videos into segment that you want to convert. Step five: start conversion Press "Start" button to start to convert MOV to Adobe Premiere format. About the Author import MOV to Adobe Premiere I want my video to be split, automatically, into clips when I import them into Adobe Premiere Elements? When I import my video into Adobe Premiere Elements I'm left with the full hour long blocks of video. I can sit through it and create my own clips but i want elements to split it into manageable clips for me. I don't have adobe elements, but there is usually a config that allows you to choose how the import is split. eg splitting on clips you have taken using the date/time like when you pressed the record button, or maybe a change of scene, or sometimes just by hitting the space bar each time you want a split. I am used to Pinnacle Studio and it's possible in that program. Try the adobe website Green Screen & Adobe Premiere Elements
http://www.ninjagraphx.com/premiere-elements/
crawl-003
refinedweb
688
69.62
0 I am working on a project that requires a CSV file to be read into a multidimensional array. I loop through the array, and set multidimensionalarray[x][n] to the corresponding data in the CSV file, but I keep getting IndexError: list index out of range. I can't figure out why, and I've tried a number of different ways to fix it. Naturally, I took to the internet and found several forum posts that were almost, but not quite applicable to this. The code is as follows: def load(): x = 0 if not os.access('Database.csv', os.F_OK): commands.getoutput('touch Database.csv') file = csv.reader(open('Database.csv', 'rb')) for row in file: retArr[x].append([]) retArr[x] = row x = x + 1 return retArr Any help or pointers to where I might get the information would be greatly appreciated.
https://www.daniweb.com/programming/software-development/threads/404400/indexerror-in-reading-a-csv-into-a-multidimensional-array
CC-MAIN-2017-13
refinedweb
144
63.9
Configuration¶ Qtile is configured in Python. A script ( ~/.config/qtile/config.py by default) is evaluated, and a small set of configuration variables are pulled from its global namespace. Configuration lookup order¶ Qtile looks in the following places for a configuration file, in order: The location specified by the -cargument. $XDG_CONFIG_HOME/qtile/config.py, if it is set ~/.config/qtile/config.py It reads the module libqtile.resources.default_config, included by default with every Qtile installation. Qtile will try to create the configuration file as a copy of the default config, if it doesn’t exist yet. Default Configuration¶ The default configuration is invoked when qtile cannot find a configuration file. In addition, if qtile is restarted via qshell, qtile will load the default configuration if the config file it finds has some kind of error in it. The documentation below describes the configuration lookup process, as well as what the key bindings are in the default config. The default config is not intended to be suitable for all users; it’s mostly just there so qtile does /something/ when fired up, and so that it doesn’t crash and cause you to lose all your work if you reload a bad config. Key Bindings¶ The mod key for the default config is mod4, which is typically bound to the “Super” keys, which are things like the windows key and the mac command key. The basic operation is: mod + kor mod + j: switch windows on the current stack mod + <space>: put focus on the other pane of the stack (when in stack layout) mod + <tab>: switch layouts mod + w: close window mod + <ctrl> + r: restart qtile with new config mod + <group name>: switch to that group mod + <shift> + <group name>: send a window to that group mod + <enter>: start terminal guessed by libqtile.utils.guess_terminal mod + r: start a little prompt in the bar so users can run arbitrary commands The default config defines one screen and 8 groups, one for each letter in asdfuiop. It has a basic bottom bar that includes a group box, the current window name, a little text reminder that you’re using the default config, a system tray, and a clock. The default configuration has several more advanced key combinations, but the above should be enough for basic usage of qtile. See Keybindings in images for visual keybindings in keyboard layout. Mouse Bindings¶ By default, holding your mod key and clicking (and holding) a window will allow you to drag it around as a floating window. Configuration variables¶ A Qtile configuration consists of a file with a bunch of variables in it, which qtile imports and then runs as a Python file to derive its final configuration. The documentation below describes the most common configuration variables; more advanced configuration can be found in the qtile-examples repository, which includes a number of real-world configurations that demonstrate how you can tune Qtile to your liking. (Feel free to issue a pull request to add your own configuration to the mix!) In addition to the above variables, there are several other boolean configuration variables that control specific aspects of Qtile’s behavior: Testing your configuration¶ The best way to test changes to your configuration is with the provided Xephyr script. This will run Qtile with your config.py inside a nested X server and prevent your running instance of Qtile from crashing if something goes wrong. See Hacking Qtile for more information on using Xephyr. Starting Qtile¶ There are several ways to start Qtile. The most common way is via an entry in your X session manager’s menu. The default Qtile behavior can be invoked by creating a qtile.desktop file in /usr/share/xsessions. A second way to start Qtile is a custom X session. This way allows you to invoke Qtile with custom arguments, and also allows you to do any setup you want (e.g. special keyboard bindings like mapping caps lock to control, setting your desktop background, etc.) before Qtile starts. If you’re using an X session manager, you still may need to create a custom.desktop file similar to the qtile.desktop file above, but with Exec=/etc/X11/xsession. Then, create your own ~/.xsession. There are several examples of user defined xsession s in the qtile-examples repository. If there is no display manager such as SDDM, LightDM or other and there is need to start Qtile directly from ~/.xinitrc do that by adding exec qtile at the end. In very special cases, ex. Qtile crashing during session, then suggestion would be to start through a loop to save running applications: while true; do qtile done Finally, if you’re a gnome user, you can start integrate Qtile into Gnome’s session manager and use gnome as usual.
https://docs.qtile.org/en/v0.18.0/manual/config/index.html
CC-MAIN-2021-39
refinedweb
801
61.46
this approach is usually not as speedy as trusty findstr. The natural solution? Implement our own utility in F#! In this blog we will develop a Windows Powershell cmdlet in F# which offers both the features and the performance that we need, and we will do it in fewer than 200 lines of code. These are the parameters we will be able to specify: - The pattern to search for - A file name or extension filter to control which files are considered in the search - Whether to search recursively from the current directory - What file encoding to use - Whether to do a case-sensitive or case-insensitive search - Whether to do a verbatim plain-text search, rather than a regex search And these are the pieces of data we will be able to process from the output - The file path - The line number - The full line from the file - The substring which matched - Regex match groups Some basic usage samples we will be enabling: # find all public class declarations in .cs files in the current directory PS C:\src> Search-File 'public class' *.cs # find all failure messages from .fs and .fsx files recursively PS C:\src> Search-File 'failwith "(?<message>[^"]*)"' *.fs,*.fsx -Recurse If you aren’t familiar with Powershell, it’s the next-generation (current-generation, really) command-line shell and scripting framework for automating Windows tasks and IT workflows. Powershell has shipped in-the-box as a default Windows component since Windows 7, and has since attracted a large following of scripters, administrators, and developers. Powershell v3 is built into Windows 8 and Windows Server 2012. The primary type of utility in Powershell is not an executable, but a cmdlet. Powershell is built entirely on .NET, and every scriptable entity is a full-fledged .NET object. Users have full access to types, properties, methods, events, etc, all from script. Cmdlets, too, are implemented as .NET classes, inheriting from System.Management.Automation.Cmdlet (or PSCmdlet). Following standard Powershell naming conventions, we will call our cmdlet “Search-File.” Cmdlet parameters are implemented as public properties on the cmdlet class and tagged with the [<Parameter>] attribute. Our cmdlet class thus looks like this (taking advantage of the new F# 3.0 syntax for auto-properties): namespace FSUtils open System.Management.Automation open System.Text open System.Text.RegularExpressions /// Grep-like cmdlet Search-File [<Cmdlet("Search", "File")>] type SearchFileCmdlet() = inherit PSCmdlet() /// Regex pattern used in the search. [<Parameter(Mandatory = true, Position = 0)>] [<ValidateNotNullOrEmpty>] member val Pattern : string = null with get, set /// Array of filename wildcards. [<Parameter(Position = 1)>] [<ValidateNotNull>] member val Include = [|"*"|] with get,set /// Whether or not to recurse from the current directory. [<Parameter>] member val Recurse : SwitchParameter = SwitchParameter(false) with get, set /// Endcoding to use when reading the files. [<Parameter>] member val Encoding = Encoding.ASCII with get, set /// Toggle for case-sensitive search. [<Parameter>] member val CaseSensitive : SwitchParameter = SwitchParameter(false) with get, set /// Do not use regex, just do a verbatim string search. [<Parameter>] member val SimpleMatch : SwitchParameter = SwitchParameter(false) with get, set /// Called once per object coming from the pipeline. override this.ProcessRecord() = // check if simple match is possible, even if not specified explicitly let simple = this.SimpleMatch.IsPresent || (fun s -> s = Regex.Escape(s)) (Regex.Replace(this.Pattern, "\s", "")) let searcher = FileSearcher(this.Pattern, this.SessionState.Path.CurrentFileSystemLocation.Path, this.Include, this.Recurse.IsPresent, this.CaseSensitive.IsPresent, simple, this.Encoding) searcher.Search() |> Seq.iter(fun item -> this.WriteObject(item)) Although this tool will be invoked from the command line, we don’t need to do any argument parsing ourselves. All argument processing will be handled by the Powershell runtime. When ProcessRecord is called, we can assume all applicable [<Parameter>] properties have been set according to user input. The cmdlet class is just a simple Powershell interop wrapper around the real workhorse, the FileSearcher class, which we can write in somewhat more idiomatic F# code. For the objects which are actually returned by the cmdlet, we define the LineMatch class, which exposes all of the properties we are interested in. To meet our performance goals, we parallelize the entire workflow with F# async and Tasks. The enumeration of files will be done in an async block, and each discovered file will then be processed in its own dedicated Task. As matching lines of text are found, LineMatch objects are constructed and dumped into a BlockingCollection, which handles synchronization for us. The elements of the BlockingCollection are meanwhile streamed back to the user on the calling thread, so results appear as fast as they are found. Here’s the code: namespace FSUtils open System open System.Collections.Concurrent open System.IO open System.Management.Automation open System.Text open System.Text.RegularExpressions open System.Threading.Tasks // holds info about lines of files matching the provided pattern type LineMatch(filePath : string, currentPath : string, lineNumber : int, line : string, subStr : string, mo : Match option) = member val Path = filePath member val RelativePath = filePath.Remove(0, currentPath.Length + 1) member val LineNumber = lineNumber member val Line = line member val Match = subStr // .[] access to match groups member this.Item with get(i : int) = match mo with | Some(m) when m.Groups.[i].Success -> m.Groups.[i].Value | _ -> null member this.Item with get(i : string) = match mo with | Some(m) when m.Groups.[i].Success -> m.Groups.[i].Value | _ -> null /// Class for doing regex searches of files on disk. type FileSearcher(pattern : string, startingDirectory : string, includePatterns : string[], recurse : bool, caseSensitive : bool, simpleMatch : bool, encoding : Encoding) = /// Function used to match individual lines of text let doMatch = match (simpleMatch, caseSensitive) with // full regex match, the slowest option | (false, _) -> let r = Regex(pattern, RegexOptions.Compiled ||| if caseSensitive then RegexOptions.None else RegexOptions.IgnoreCase) fun line -> match r.Match(line) with | m when m.Success -> Some(m.Value, Some(m)) | _ -> None // case-sensitive match with String.Contains, the fastest option | (true, true) -> fun line -> match line.Contains(pattern) with | true -> Some(pattern, None) | false -> None // case-insensitive match with String.IndexOf, the second fastest opton | (true, false) -> fun line -> match line.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) with | i when i >= 0 -> Some(line.Substring(i, pattern.Length), None) | _ -> None /// Returns all files in the specified directory matching /// one or more of the wildcards in "includePatterns." let GetIncludedFiles dir = includePatterns |> Seq.collect (fun p -> Directory.EnumerateFiles(dir, p)) /// Pattern which matches a directory path with either /// Contents(<files in the directory>, <directories in the directory>) /// AccessDenied if unable to obtain directory contents let (|Contents|AccessDenied|) dir = try Contents (GetIncludedFiles dir, if recurse then Directory.EnumerateDirectories(dir) else Seq.empty ) with | 😕 UnauthorizedAccessException -> AccessDenied /// Enumerates all accessible files in or under the specified directory. let rec GetFiles dir = seq { match dir with | Contents(files, directories) -> yield! files yield! directories |> Seq.collect GetFiles | AccessDenied -> () } /// Scans the specified file for lines matching the specified pattern and /// inserts them into the blocking collection. let CollectLineMatches (collection : BlockingCollection<LineMatch>) file = try File.ReadAllLines(file, encoding) |> Array.iteri (fun i line -> match doMatch line with | Some(str, mtch) -> collection.Add( LineMatch(file, startingDirectory, i + 1, line, str, mtch)) | None -> () ) with | 😕 IOException -> () // if we have issues accessing the file, just ignore /// Initiates the search for matching file content, /// returning an enumerable of matching lines. /// Note that the search is executed in parallel and /// thus the order of results is not guaranteed. member this.Search () = let bc = new BlockingCollection<LineMatch>() async { let tasks = GetFiles startingDirectory |> Seq.map (fun file -> Task.Factory.StartNew(fun () -> CollectLineMatches bc file) ) |> Seq.toArray if tasks.Length = 0 then bc.CompleteAdding() else Task.Factory.ContinueWhenAll(tasks, fun _ -> bc.CompleteAdding()) |> ignore } |> Async.Start bc.GetConsumingEnumerable() The F# code is concise and very readable. Language features such as active patterns, sequence expressions, and matching keep the code fairly tidy compared to equivalent C#. And of course, we can test the different bits in F# Interactive as we code. Developers already familiar with F# might be curious why Tasks were used for processing files, rather than F# async expressions. We needed to fire off file processing jobs immediately as each file path was enumerated, rather than waiting until all files were enumerated, since this could potentially take a long time. The Task Parallel Library provides great APIs for exactly this kind of parallel processing. The F# async API, on the other hand, provides an experience geared more toward enabling asynchronous processing, especially the usage of Begin/End .NET APIs. The difference between parallel and asynchronous is subtle, but significant. Suffice it to say, Tasks were simply the better tool for the job in this case. Some good discussion on exactly this topic can be found here. Compiling these classes into FSUtils.dll, we can now consume them from Powershell command line or script by calling the cmdlet Import-Module. PS C:\src> Import-Module .\FSUtils.dll The output from our “failwith” sample search is a collection of LineMatch objects which look something like this: Path : C:\src\fs3sample\SampleProviders\Shared\ProvidedTypes-0.2.fs RelativePath : SampleProviders\Shared\ProvidedTypes-0.2.fs LineNumber : 924 Line : | _ –> failwith "at most one constructor allowed" Match : failwith "at most one constructor allowed" The output can be condensed to 1 line per match by either piping to Format-Table, or by defining a format file which specifies exactly how to display objects of the LineMatch type. Comparing performance against standard Powershell cmdlets, traditional findstr, and GNU grep, we do very well. Search-File was a bit faster than findstr and grep when searching the F# team source tree for both plaintext and regex patterns. All three handily beat Select-String. Where we really see Search-File pull ahead is when chewing through a larger set of files, in this case the C# source tree for another project. The benefits of parallelization become more pronounced in this case. There we have it! In under 200 lines of F#, a highly usable and very speedy file search utility. I look forward to combining the strengths of F# and Powershell again soon. Download the full source code here. Lincoln Atkinson Visual Studio F# Test Team PS: The code provided here will compile against .NET 4+. Powershell v3 supports .NET 4 by default, but in order to import this to Powershell v2 (e.g. on a Windows 7 machine), you will first need to take some manual steps. Join the conversationAdd Comment Have you considered testing this against a windows build of GNU grep as well? Great example Lincoln, thanks for posting it. I'm guessing an F# type provider could be surfaced in a similar way? Thanks Doug BTW the code is getting cut off on its RHS. You need a pre.code { overflow-x: auto } in the CSS. @Justin – Great idea! I've added the results to the charts. @Doug – Maybe, what do you have in mind? @rjcox – Thanks for the heads up. I've broken the long lines up, it should be more readable now. I was thinking about this: F# 3.0 Freebase Type Provider Sample – Integrating Internet-Scale Data Sources into a Strongly Typed Language This sounds really interesting, but I'm still having a problem using copy-paste w/ this code. Could you make the code downloadable seperately? For example, pasting the 2nd implementation into VS 2010, the "open System" and "open System.Collections.Concurrent" lines are run together after pasting it into VS, and even when I fix that I get an "Unexpected keyword 'val' in member definition" on the declaration of Path (line 19.) I've added a link just above my signature to download the source code in a single file. The code will not compile in VS 2010 as is, since it takes advantage of new F# 3.0 syntax in a few places, in particular "member val." Check out our earlier blog post (blogs.msdn.com/…/announcing-the-release-of-f-tools-for-visual-studio-express-2012-for-web.aspx) to find out how to get a free version of Visual Studio 2012 with the F# 3.0 compiler. Or convert the code to the older property syntax, documented here: msdn.microsoft.com/…/dd483467(v=vs.110).aspx Great article! Unfortunately I've run in to a small problem! When I try to load the module in PS, I get an error saying that the "Strong name validation failed for System.Management.Automation". When I check it using sn -vf it turns out that System.Management.Automation.dll is only "delay-signed"! What am I doing wrong or missing? Thank you in advance! – Morten Lund Thank you! I've solved the problem! The System.Management.Automation.dll wasn't referenced from GAC as it should have been! – Morten Thanks for the post Lincoln. I'm a Powershell enthousiast, and at the same time I've been developing this 'functional itch' since I've read about Erlang (amongst other). I think however that in a Windows environment nobody better than MS itself to deliver a language in the functional paradigm. Greetings. I run this cmdlet built in F# (.NET 4.6) against a 1 GB text file and performance results using Measure-Command are the following: 1st: findstr -> 2 sec 2nd: select-string -> 7 sec 3rd: Search-File -> 13 sec Why is the search performance different ? @PSTester – The code is written to do fast parallel searching of a large directory tree with many directories and files. It is not optimized for fastest-possible searching of a single large file.
https://blogs.msdn.microsoft.com/fsharpteam/2012/10/03/rethinking-findstr-with-f-and-powershell/
CC-MAIN-2016-50
refinedweb
2,236
50.12
. Basic Python recipe¶ - Create a new Python recipe by clicking the « Python » Python code. First of all, you will need to load the Dataiku API (the Dataiku API is preloaded when you create a new Python recipe) import dataiku You") Interaction with the Dataset can be made in two flavors : - Using the usual core Python langage - Using Pandas Using Pandas¶ Pandas is a popular python package for in-memory data manipulation. Using the dataset via pandas will load your dataset in memory, it is therefore critical that your dataset is « small enough » to fit in the memory of the Data Science Studio server. The core object of Pandas is the DataFrame object, which represents a dataset. Getting a Pandas DataFrame from a Dataset object is straightforward: # Object representing our input dataset cars =_from_dataframe output_ds = Dataset("myoutputdataset") output_ds.write_from_dataframe(my_dataframe) Writing the output schema¶ Generally, you should. # Set the schema of ‘myoutputdataset’ to match the columns of the dataframe output_ds.write_schema_from_dataframe(my_dataframe) You can also write the schema and the dataframe at the same time # Write the schema from the dataframe and write the dataframe output_ds.write_with_schema(my_dataframe) Using the native. from dataiku import Dataset from collections import Counter cars = writer = output.get_writer() for (origin,count) in origin_count.items(): writer.write_row_array((origin,count)) writer.close() Note Don’t forget to close your writer. If you don’t, your data will not get fully written. Setting the schema¶ Generally, you should declare the schema of the output dataset prior to running the Python code. However, it is often impractical to do so, especially if your code generates Shaker processors. In these cases, rather than creating a Python recipe, you should consider using a Python UDF within the Shaker. For simple operations, using a Python UDF has several advantages over the Python recipes: - You do not need an « intermediate » dataset after the Shaker
https://doc.dataiku.com/dss/2.0/code_recipes/python.html
CC-MAIN-2019-26
refinedweb
310
62.48
pipe() Create a pipe Synopsis: #include <unistd.h> int pipe( int fildes[2] ); Arguments: - fildes - An array where the function can store the file descriptors for the ends of the pipe. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The pipe() function creates a pipe (an unnamed FIFO) and places a file descriptor for the read end of the pipe in fildes[0], and a file descriptor for the write end of the pipe in fildes[1]. Their integer values are the two lowest available at the time of the pipe() function call. The O_NONBLOCK flag is cleared for both file descriptors. (You can use fcntl() to set the O_NONBLOCK flag.) You can write data to file descriptor fildes[1] and read it from file descriptor fildes[0]. If you read from file descriptor fildes[0], it returns the data written to fildes[1] on a first-in-first-out (FIFO) basis. The pipe buffer is allocated by the pipe resource manager. You typically use this function to connect standard utilities acting as filters, passing the write end of the pipe to the data-producing process as its STDOUT_FILENO, and the read end of the pipe to the data-consuming process as its STDIN_FILENO (either via the traditional fork() , dup2() , or exec*, or the more efficient spawn* calls). If successful, pipe() marks the st_ftime, st_ctime, st_atime and st_mtime fields of the pipe for updating. Returns:.
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/p/pipe.html
CC-MAIN-2020-05
refinedweb
248
70.02
Another new RPi.GPIO feature that I discovered last week is GPIO.getmode(). This appeared in RPi.GPIO 0.5.11 and allows you to query RPi.GPIO to see whether GPIO.setmode() has been set up as BCM, BOARD, or UNSET mode. This could be useful if you are running a suite of scripts or modules which work together. GPIO.getmode() returns… -1 if GPIO.setmode() is not set 11 if GPIO.setmode(GPIO.BCM) is active 10 if GPIO.setmode(GPIO.BOARD) is active Below you can see a live python session showing what you get when you use GPIO.getmode() with different modes set… Why Did You Bother Setting Up An Input? Good question. Glad you asked. Once you’ve set the mode, you can only change it once you’ve done a GPIO.cleanup(). But you can only do GPIO.cleanup() once you’ve configured a port. So you can’t flick between GPIO modes without first setting up a port, then cleaning up. Apart from testing, as I’m doing here, it’s most unlikely anyone would actually want to do that. So it’s probably a bit of a non-issue. I always use BCM numbering, so wouldn’t need to do that. Let’s have a closer look at that live Python session to see what’s happening… >>> from RPi import GPIO # bring in the needed library >>> mode = GPIO.getmode() # read the mode into variable >>> print mode # print the value -1 # -1 is the output >>> GPIO.setmode(GPIO.BCM) # set BCM mode >>> mode = GPIO.getmode() # read the mode into variable >>> print mode # print the value 11 # 11 is the output Now we need to configure an input port because we can’t switch between modes without using cleanup(), which won’t work unless we’ve configured a port. >>> GPIO.setup(24, GPIO.IN) # set up an input >>> GPIO.cleanup() # clean up >>> GPIO.setmode(GPIO.BOARD) # set BOARD mode >>> mode = GPIO.getmode() # read the mode into variable >>> print mode # print the value 10 # 10 is the output How About A Little Script? Let’s write a little script that we can use to show all of this in action. from RPi import GPIO from time import sleep modes = {-1:"Unset", 11:"BCM", 10:"BOARD"} mode = GPIO.getmode() print("Your Pi is in ", modes[mode], " mode") sleep(3) print("Changing to BCM mode") GPIO.setmode(GPIO.BCM) mode = GPIO.getmode() print("Your Pi is now in ", modes[mode], " mode") sleep(3) GPIO.setup(24, GPIO.IN) # configure a port so can cleanup GPIO.cleanup() # cleanup so can set mode again print("Changing to BOARD mode") GPIO.setmode(GPIO.BOARD) mode = GPIO.getmode() print("Your Pi is now in ", modes[mode], " mode") sleep(3) print("Exiting - we're done!") The output from this script looks like this… It may not be something you’ll use every day – or even at all. But it’s good to know it’s there in case you need it. I include it for completeness as I like to document all the features of RPi.GPIO. RasPiO® GPIO Reference Aids Our sister site RasPiO has three really useful reference products for Raspberry Pi GPIO work... Looking at (which is part of the changes made when getmode() was added) it looks like you can just use the constants GPIO.UNKNOWN, GPIO.BCM and GPIO.BOARD rather than the hard-coded values -1, 11 and 10; which is both more flexible and IMHO much easier to read :-) Could you show us an example of how you’d use that Andrew? I don’t quite understand. Sorry, perhaps that wasn’t the best link to use. This might be easier to read It means you could e.g. change your ‘modes’ dictionary to: modes = {GPIO.UNKNOWN:”Unset”, GPIO.BCM:”BCM”, GPIO.BOARD:”BOARD”} i.e. GPIO.BCM (internally) has the value 11, and IMHO checking if mode == GPIO.BCM looks much neater than checking if mode == 11. Yeah – that makes sense. Thanks. :) I saw the brief documentation mentioning those constants, but when I came to actually view the values of getmode() I got the numbers. I can now see how they relate. It wasn’t immediately obvious to me how to use GPIO.UNKNOWN etc. And if it wasn’t obvious to me, you can bet it wasn’t obvious to a whole load of other people. I think this is likely to be a “useful to some but not used widely” feature. I like to try to document all the features though. (Pity I can’t fit more on the ruler – then again – maybe it’s not!) You’ll just have to bring out a 12″ ruler as a sequel… ;-)
http://raspi.tv/2015/rpi-gpio-function-gpio-getmodev2
CC-MAIN-2018-17
refinedweb
787
76.62
[All the other Parts: History of Visual Studio] Visual C++ 2.0, “Dolphin” was a very ambitious release. We were really happy with VC1 but there were quite a few things that were entirely unsatisfactory. One of them, maybe the most important, was the fact that window management in the thing was just a nightmare. VC1 used the standard MDI interface for all the windows, including the tool windows like registers, watch, output, and so forth – that was just not adequate because you found key display windows were swimming in a sea of documents many of which had been opened by the debugger and so forth. It was quite bad. But let’s talk about some of the other things that had been going on before we get into that. The BASIC compiler team (the non-visual basic?) delivered another solid release, but that didn’t integrate with the VC shell. It was for making standalone executables ala the other command line tools. On the other hand the FORTRAN team delivered the first Fortran Powerstation release – a little miracle in its own right. It used a lot of Dos Extension technique and some slick remote debugging tricks to debug in it from the GUI and tweaked the visual project system and yowsa you get a modern looking (at that time) Fortran release. Pretty impressive stuff. COBOL was still humming along at a regular cadence and let’s not forget MASM, the ultimate (literally) release I think and the little known other assembler ML that I think had only one release – but it was quite a feat in and of itself. Try rationalizing all the ad hoc parsing rules for MASM and ML is what comes out. But maybe we didn’t really need another macro assembler very badly by then; it’s late 1993 now remember. Speaking of 1993, there were new versions of Office out there and they had a slick feature – docking toolbars. We decided that was the answer to the windowing problems we had in VC – go one up on docking toolbars and allow docking windows. Now you could dock your window to the side, bottom, top… really slick. I say “we decided” but I should probably say that the foundation of this ambitious effort didn’t actually come directly from the VC team, it was the App Studio team that suggested it and built the initial scaffolding. And the ambition was even bigger. Previously our IDE was a suite of integrated applications but we wanted to change that. The shell’s plans were to allow us to host all our features in one application that included resource editing (forms too), plus text, project, debug, build, and help all in one application. And – wait for it – it had to be modular so that other languages like Fortran, Basic, and COBOL could plug in. This shell provided a core set of services those packages could use, like menus, toolbars, toolwindows, and so forth. Does this sound at all familiar VS Extenders? More on that later. But wait, that’s not all! We also wanted to deliver tools for the Macintosh, anybody remember WLM? I wrote some Mac apps with it myself! PowerPC, 680×0 compilers and debuggers, no problem. Remote debugging to the rescue! Oh and let’s not forget support for the MIPS and Alpha as well. Do you think we’re nuts yet? Because we aren’t done. While we’re at it, the Visual C++ codebase, which was written in C (remember the C++ compiler wasn’t yet done when it started and it began life as Quick C for Windows), had to be first ported to C++ (which helpfully found lots of bugs) and then turned from a regular windows application into an MFC library that could be used by the new shell. And the whole product had to basically keep working while this was going on because VC2 had to be able to build and debug itself. Oh and naturally we’re delivering new libraries, and a new MFC (MFC 3.0) plus since we’re going to touch all that code anyway may as well port it all to 32 bits (we had Barracuda to start with but many of the other pieces that were merging in were only 16 bit). I’m still not done yet. We also had some big themes around “edit and go”, “simplifying OLE”, and “beyond files” – meaning we wanted the build cycle to be tight and easy, and fast, we wanted to make all those new OLE features like embedding and whatnot simpler, and we wanted you to be able to navigate your codebase as much as possible without worrying about what files you had put it in. I added more browsing features, many C++ oriented ones at that time; we did some cool debugging across OLE RPC channels, and more. I remember a lot of debugging features because I was close to them. Things like data tips, and autoexpand, and the automatic watch window – I was the lead debugger developer during this time. Think that’s enough for one release? We’re still not done! More language features hit the tools, just in case you think those guys are slacking off – namespaces was the first I think but this version also lands the major language features — Templates and Exception Handling. Hugely valuable and EH was fully integrated into the Windows NT SEH model which was no mean feat! We’re going to have one worldwide binary, the same bits ship in Japan, Europe and the US except for localized resources – the J version and the English version are the same! That had never been done before to my knowledge. And, the cherry on top, there was a little operating system release coming out that you may have heard of, we called it “Chicago”, but it hit the market as Windows 95. We had to be the main SDK for that operating system, which meant fixing all kinds of bugs because Chicago was much less forgiving than Windows NT. Wow, that seems totally nuts but we did that, and more. We did only minor things to the 16 bit tools from that point forward, servicing VC 1.52 (1.52a, b, and c) but we did wicked demos for the 32 bit suite, so many platforms, and a truly unified IDE, all the tools in one place. We caught some breaks in the industry at that time as well, 32 bit was hot, 1.52 was good enough, that other tool vendor was spending a lot of time thinking about (ironically) OS/2, which, being who we were, we thought was a losing strategy. But wow, the Delphi demos! Amazing stuff! It’s a good thing the VB team was getting busy too – 32 bit tools, and OCX story to compliment their VBX story, a great ecosystem. I think Visual C++ 1.0 may have been the most technically challenging IDE we ever delivered because of the amazingly weird things we had to do to make it work on that operating system. But I think Visual C++ 2.0 was just as important, if not more so, because of how much we moved our own technology forward and the sheer massive volume of deliverables. Both were a lot of long hours; and there were subscription releases 2.1 and 2.2 yet to come. [See The Documentary on Channel 9! What I remember most about VC++1.0 (the UI, at least, which was my domain) was the code we inherited [names removed -ed] _loved_ global variables. In particular, [there was] a single (global) string buffer. This worked out OK as long as the function currently using the buffer didn’t call some other function that wanted to use the buffer. Which was, as it turned out, not an infrequent occurrence. It sure was fun fixing _that_. I also remember that we ended up shipping it as a debug build (sans symbols, of course) because we never saw to it to deliver a release build to testing. Dave W. had a few choice words to say about that, as I recall. [Matt refers to the fact that we forgot to turn on the optimizer in the release configuration (!) and having gone through our whole test cycle with it off couldn’t then turn it on at the finish line!] [quote]It’s a good thing the VB team was getting busy too – 32 bit tools, and OCX story to compliment their VBX story, a great ecosystem.[/quote] I think you got too ironic in that sentence. How clumsy of me, I didn’t mean to be ironic, I meant it as a genuine compliment. Having lost track of how many s/w projects I’ve worked on (i.e. I’m really old), VC2 remains as one of my favorites. We had such an experienced team across the board that we were able to do all you write about <strong>without a spec!</strong> It was to great to put another nail in Phillipe’s coffin.
https://blogs.msdn.microsoft.com/ricom/2009/10/07/my-history-of-visual-studio-part-2/
CC-MAIN-2016-50
refinedweb
1,520
70.63
Building a Twitter Client with NodeJS and Angular Free JavaScript Book! Write powerful, clean and maintainable JavaScript. RRP $11.95 In this tutorial, we’re going to look at how to build a basic Twitter client with NodeJS, and an Angular application to display your home timeline of tweets. This is a rapid tour with things to consider while setting up your own Twitter client and Angular application. First, we’re going to build a NodeJS server, which will handle communicating between the Twitter API and the Angular application. Then, we’ll build up the Angular application to display and interact with your Twitter timeline. While you may be able to go through this tutorial without any prior NodeJS or Angular experience, I’ll assume some prior knowledge in the article. Setting Up the Project You’ll need a recent version of NodeJS set up on your machine. Then ensure you have the Angular CLI. The links provided give you a good place to start if you need help with either of those tasks. The project source code can be found on GitHub. You can get it all running locally by either cloning it with Git or downloading the files from the repo’s GitHub archive. git clone Once you have the files, from your terminal you’ll need to run npm install to get all of the dependencies installed. Then we can get to work! Creating a Twitter Client in NodeJS To access Twitter’s API, we need to register for a new “app”, which is essentially a way for Twitter to give us a set of credentials. These are unique for your application, so don’t share them publicly anywhere. You must, of course, have a Twitter account to access the data. To start, go to and select Create New App. You can fill out the name, description, and website URL for your app. (You can use a fake URL for now. If you publish your app it should be your actual website.) From there, you’ll see the new app page with your details. Go to the Keys and Access Tokens page, where you can see a button to Create my access token near the bottom. Click the button, and then you should see four values: Consumer Key (API Key), Consumer Secret (API Secret), Access Token, and Access Token Secret. We’ll use these in a moment, so be sure to keep this information handy. Creating the Twitter Client in NodeJS Now it’s time to dig into our NodeJS server, which will bridge the gap between Twitter’s API and the Angular app. In the project, you should see the server.js file, which you’ll need to open and tweak. First, you’ll need to update the block that contains the credentials you received from the Twitter app earlier. You should copy those values into the block here. We’re using a Twitter package called Twit to help us connect to Twitter, though there are others available with various levels of functionality. const client = new Twitter({ consumer_key: 'CONSUMER_KEY', consumer_secret: 'CONSUMER_SECRET', access_token: 'ACCESS_TOKEN', access_token_secret: 'ACCESS_TOKEN_SECRET' }); Now we should be able to connect to Twitter. We’re also using the popular ExpressJS to create and manage our server. Now that you have the credentials installed, you can run the server. node server Our next step is to make several routes that will handle the HTTP requests our Angular application will need to make to load the Twitter data. Our first route is to get the current user, and validate their credentials. The Access Token and Secret you provided are linked to your Twitter account, so you’ll be the authorized user in this case. When this route is called, it will call the Twitter account/verify_credentials endpoint and return an object containing your user data. app.get('/api/user', (req, res) => { client.get('account/verify_credentials').then(user => { res.send(user) }).catch(error => { res.send(error); }); }); The next route we’ll create is to get your home timeline. It requests the statuses/home_timeline endpoint, and passes a few parameters to give us more of the data we need. Due to rate limiting on the Twitter API, we’ve implemented a simple cache that will only request new data once a minute (which is the max rate before you receive errors). It basically keeps track of the last response and the time it was requested, only allowing new requests to Twitter to run after a minute. Rate limiting is a primary design consideration to have when building a Twitter app. let cache = []; let cacheAge = 0; app.get('/api/home', (req, res) => { if (Date.now() - cacheAge > 60000) { cacheAge = Date.now(); const params = { tweet_mode: 'extended', count: 200 }; if (req.query.since) { params.since_id = req.query.since; } client .get(`statuses/home_timeline`, params) .then(timeline => { cache = timeline; res.send(timeline); }) .catch(error => res.send(error)); } else { res.send(cache); } }); Finally, we create a set of routes to handle like/unlike and retweet/unretweet actions for a tweet. This will allow us not only to read data, but also take action. These will require that you’ve set the application Access Level to Read and write (in case you changed it in the Twitter app settings). app.post('/api/favorite/:id', (req, res) => { const path = (req.body.state) ? 'create' : 'destroy'; client .post(`favorites/${path}`, {id: req.params.id}) .then(tweet => res.send(tweet)) .catch(error => res.send(error)); }); app.post('/api/retweet/:id', (req, res) => { const path = (req.body.state) ? 'retweet' : 'unretweet'; client .post(`statuses/retweet/${req.params.id}`) .then(tweet => res.send(tweet)) .catch(error => res.send(error)); }); There are many Twitter APIs for engaging with Twitter data, but the fundamental rules remain the same. The only major issue here is we’ve hard-coded credentials to a single user, which you’d need in order to set up your own OAuth server (or use an existing one) to handle the authentication aspects, which you can learn more about on Twitter Authentication documentation. Creating the Angular App Now it’s time to turn our attention to the Angular application that uses the server we created. We’ll take a look at the key aspects of the application and how they work to create the final result. We’ve built this application using Clarity for the UI layer (it gives us many useful layout components), but otherwise everything is just Angular. To run the Angular application, just run the following command and then open up: ng serve Inside of the application, we have a model at src/app/tweet.ts which contains the TypeScript interface that describes most of the properties of a tweet (some have been omitted). I believe it’s essential to describe your types properly for large-scale Angular applications as well as smaller ones, so this interface gives us the shape of a tweet. Angular TwitterService First, we’ll need a service that can make requests to our NodeJS server to get the latest tweets. In Angular, the HttpClient is the utility you use to make HTTP requests, so I’ve created an Angular service to encapsulate the logic for these calls. Open up src/app/twitter.service.ts and you’ll see the following code: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from '../environments/environment'; import { Tweet } from './tweet'; export interface TwitterResponse { data: any; resp: any; } @Injectable() export class TwitterService { constructor(private http: HttpClient) { } user() { return this.http.get<TwitterResponse>(`${environment.api}/user`); } home(since?: string) { return this.http.get<TwitterResponse>(`${environment.api}/home?since=${since}`); } action(property: 'favorite'|'retweet', id: string, state: boolean) { return this.http.post<TwitterResponse>(`${environment.api}/${property}/${id}`, {state}); } } This is a fairly basic service, which has methods to build a request for each API that we’ll support. The user method will return the current user (which will always be you). The home method will return the latest 200 tweets in your home timeline (or how ever many appeared since the last tweet specified). Finally, the action property handles making either a favorite or retweet call, by sending a boolean state value to toggle the status. This service is generic, and each of these methods returns an Observable. If you want to learn more about them, you can read about Functional Reactive with RXJS, but the way they’re used here is similar to how a promise works. We’ll see how to use them in a moment. Using the Angular TwitterService to load user We’ll use the TwitterService in a few places, starting with loading the AppComponent. We’ll use it to load the user details (which appears in the top corner), and to load the list of tweets for the home page. Open up src/app/app.component.ts and you should see the following code: import { Component , OnInit } from '@angular/core'; import { TwitterService } from './twitter.service'; import { Tweet } from './tweet'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], providers: [TwitterService] }) export class AppComponent implements OnInit { user; constructor(private twitter: TwitterService) {} ngOnInit() { this.twitter.user().subscribe(user => this.user = user.data); } } The AppComponent does one main thing using our TwitterService. The ngOnInit method fires as soon as the component has initialized, and requests the user data. Here we’re using the Observable returned by the TwitterService.user method, and when we use subscribe it will trigger the actual HTTP request to fire. Once it’s returned, the callback function stores the user property, which is used to display content in the navbar. You can see the user property bindings in the component template below, such as user.profile_image_url_https: <clr-main-container> <clr-header <div class="branding"> <a class="nav-link"> <div class="title">Twangular</div> </a> </div> <div class="header-actions" * <a class="nav-link"> <span class="nav-text"> <img [src]="user.profile_image_url_https" class="avatar" /> @{{user.screen_name}} </span> </a> </div> </clr-header> <div class="content-container"> <main class="content-area"> <app-tweets></app-tweets> </main> </div> </clr-main-container> Also, the use of <app-tweets></app-tweets> will insert the TweetsComponent, which handles the actual loading and display of tweets, so let’s take a look at it now. Displaying the list of tweets To help separate our logic, we actually have two components to display the list of tweets. The TweetsComponent manages the list of tweets and also handles making requests to our NodeJS service for liking or retweeting a tweet. Then the TweetComponent is used to display the actual tweet formatting and display. I always recommend trying to separate components into distinct roles, and in this case the TweetsComponent is in charge of handling data interaction, such as loading and retweeting, and the TweetComponent has no knowledge of loading data but only displays content. We’ll start by looking at the TweetsComponent, so below are the contents of src/app/tweets/tweets.component.ts: import { Component, OnInit, Input, OnDestroy } from '@angular/core'; import { Tweet } from '../tweet'; import { TwitterService } from '../twitter.service'; @Component({ selector: 'app-tweets', templateUrl: './tweets.component.html', styleUrls: ['./tweets.component.scss'] }) export class TweetsComponent implements OnInit, OnDestroy { inflight = false; tweets: Tweet[] = []; ids = []; timer; since = ''; constructor(private twitter: TwitterService) {} ngOnInit() { this.getTweets(); this.timer = setInterval(() => this.getTweets(), 61000); } ngOnDestroy() { if (this.timer) { clearInterval(this.timer); } } getTweets() { this.twitter.home(this.since).subscribe(tweets => { tweets.data.reverse().forEach(tweet => { if (this.ids.indexOf(tweet.id_str) < 0) { this.ids.push(tweet.id_str); this.tweets.unshift(tweet); } }); this.since = this.tweets[0].id_str; this.cleanUp(); }); } cleanUp() { if (this.tweets.length > 1000) { this.tweets.splice(1000); this.ids.splice(1000); } } action(action, index) { if (this.inflight) { return; } const stateKey = (action.property === 'favorite') ? 'favorited' : 'retweeted'; const newState = !action.tweet[stateKey]; this.inflight = true; this.twitter.action(action.property, action.tweet.id_str, newState).subscribe(tweet => { this.tweets[index][stateKey] = newState; this.tweets[index][action.property + '_count'] += (newState) ? 1 : -1; this.inflight = false; }); } } This component takes the role of handling all of the loading and interacting with the list of tweets. In the ngOnInit method, we call the method to get the tweets, as well as set an interval that reloads the latest tweets every 61 seconds. Remember, there’s a rate limit on how many requests we can make, so this helps keep us under the limit. The ngOnDestroy method just unsets the timer when the component is removed, which is good practice to always do to prevent memory leaks. Then we have the getTweets method, which uses the TwitterService to request the home timeline. It also passes a string that contains the last tweet ID that was received, so we can request only the tweets since that ID was created. When we subscribe, the request is made and the callback gives us the list of tweets. Since we want to show the most recent tweets first, we reverse the array and then push them onto the existing list of tweets, update the latest tweet ID reference, and then do some cleanup. If we have over 1000 items, we drop the remainder to help keep the memory consumption in check. It’s important to note that we’re using the id_str property from the tweets. This is because JavaScript (and subsequently JSON) cannot accurately process numbers above 53 bits (or in other words, JavaScript cannot process extremely large numbers, see Snowflake IDs). The action method will be used to handle calling the TwitterService to favorite or retweet a tweet. It takes the action (a favorite or retweet) and then toggles the state of the property. (If you previously retweeted, it would unretweet, for example). A tweet contains metadata about whether or not you’ve already favorited or retweeted, as well as the counts of how many favorites or retweets exist. Since your action of favoriting or retweeting changes that state, this method also updates the tweet values accordingly. The template for the component can be found at src/app/tweets/tweets.component.html and is shown below. It’s fairly simple, as it iterates over a list of tweets, and displays an instance of the TweetComponent for each tweet. If the tweet is a retweet, it binds the retweeted status as well. Twitter adds a retweeted_status property with the original tweet’s data if it’s a retweet, and if it’s what we really want to display. Since we want to display the retweeted status, it actually replaces the actual tweet when it’s present. <div class="tweets"> <div class="card" * <app-tweet *</app-tweet> <app-tweet *</app-tweet> </div> </div> The template shows the use of input and output bindings on the TweetComponent. The inputs [tweet] and [retweet] pass data into the TweetComponent, and the output (action) calls the action method on TweetsComponent when an action occurs (either a favorite or retweet action). To see how the tweets are displayed, let’s move to the the TweetComponent, which binds a lot of data into a card component and can be found at src/app/tweet/tweet.component.html. <div class="card-header"> <img [src]="tweet.user.profile_image_url_https" class="avatar" /> {{tweet.user.name}} (@{{tweet.user.screen_name}}) <span *<clr-icon</clr-icon> Retweeted by {{retweet.user.name}} (@{{retweet.user.screen_name}})</span> <div class="card-header-actions"> <button type="button" class="btn btn-icon" [ngClass]="{'btn-success': tweet.favorited}" (click)="toggleAction('favorite')"><clr-icon</clr-icon> {{tweet.favorite_count}}</button> <button type="button" class="btn btn-icon" [ngClass]="{'btn-success': tweet.retweeted}" (click)="toggleAction('retweet')"><clr-icon</clr-icon> {{tweet.retweet_count}}</button> </div> </div> <div class="card-block"> <div class="card-img" * <img [src]="tweet.entities?.media[0].media_url_https" (click)="media = true" /> </div> <p class="card-text" [innerHTML]="tweet | tweet"></p> </div> <div class="card-footer" * {{tweet.created_at | amTimeAgo}} <clr-icon</clr-icon> {{tweet.created_at | date:'medium'}} </div> <div class="card-footer" * {{retweet.created_at | amTimeAgo}} <clr-icon</clr-icon> {{retweet.created_at | date:'medium'}} </div> <clr-modal [(clrModalOpen)]="media" * <h3 class="modal-title"><img [src]="tweet.user.profile_image_url_https" class="avatar" /> {{tweet.user.name}} (@{{tweet.user.screen_name}}) <span *<clr-icon</clr-icon> Retweeted by {{retweet.user.name}}</span></h3> <div class="modal-body"> <img [src]="tweet.entities?.media[0].media_url_https" /> </div> <div class="modal-footer" [innerHTML]="tweet | tweet"></div> </clr-modal> I’ll just point out a few key aspects of this template. First, the two buttons in the .card-header-actions element show the number of favorites and retweets. They also have an event binding (click)="toggleAction('favorite')" which calls a method on click to handle the actions. This method will emit an event up to TweetsComponent, which is using the (action) event binding to capture. Also, you can see a lot of interpolation bindings, which are the {{tweet.favorite_count}}. There’s a lot of content to display, so this is the easiest way to print text or content into the page. Next, the main text of the tweet is bound directly to the innerHTML property of the .card-text element, as you see here. This is because we want to display HTML content instead of just text, because it allows us to inject content with links. <p class="card-text" [innerHTML]="tweet | tweet"></p> This binding to innerHTML is done because we have a custom pipe (which we’ll review in a moment) that parses the tweet and replaces some of the content with links. So for example, if a tweet has a URL in it, this will replace the plain text value with an actual anchor link. Similarly, if the tweet mentions another user, it does the same thing. We’ve also included the amTimeAgo pipes, which are a set of Angular pipes for time management. Finally, there’s a clr-modal element at the bottom, which is a Clarity modal. If the tweet contains an image, and the user clicks on the image (found above in the .card-img element), it will open the modal with a larger version. To wrap up this component, it’s useful to review the component controller in src/app/tweet/tweet.component.ts, which defines a few important attributes: import { Component, EventEmitter, Output, Input } from '@angular/core'; import { Tweet } from '../tweet'; @Component({ selector: 'app-tweet', templateUrl: './tweet.component.html', styleUrls: ['./tweet.component.scss'] }) export class TweetComponent { @Input() tweet: Tweet; @Input() retweet: Tweet; @Output() action = new EventEmitter<{property: string, tweet: Tweet}>(); hasPhoto(tweet: Tweet) { if (tweet.entities.media && tweet.entities.media.length && tweet.entities.media[0].type === 'photo') { return true; } return false; } toggleAction(property: 'favorite'|'retweet') { this.action.emit({property, tweet: this.tweet}); } } The component declares two inputs, @Input() tweet and @Input() retweet, and one output, @Output() action. The two inputs allow us to bind in the tweet to display, and if it’s a retweet we also bind in that tweet information. You saw these values being passed from the TweetsComponent template. The output alerts the parent component when something occurs, and in this case we want to alert about an action to favorite or retweet the tweet when those buttons are clicked. This information is simply passed along, like a normal JavaScript event, and the TweetsComponent component will handle what to do with it through the action method. Before we wrap up the way we display our tweets, let’s take a quick look at this TweetPipe, which we used to format and parse the tweet. Using TweetPipe to format data The last major feature to review is the TweetPipe, found at src/app/tweet.pipe.ts and displayed below. This handles the parsing of the tweet text and metadata to provide formatting: import { Pipe, PipeTransform } from '@angular/core'; import { Tweet } from './tweet'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({ name: 'tweet' }) export class TweetPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(tweet: Tweet, args?: any): any { let text = this.sanitizer.sanitize(tweet.full_text); if (tweet.entities.user_mentions) { tweet.entities.user_mentions.forEach(mention => { text = text.replace(new RegExp(`@${mention.screen_name}`, 'gi'), `<a href="{mention.screen_name}" target="_blank">@${mention.screen_name}</a>`); }); } if (tweet.entities.urls) { tweet.entities.urls.forEach(url => { text = text.replace(url.url, `<a href="${url.url}" target="_blank">${url.display_url}</a>`); }); } if (tweet.entities.media) { tweet.entities.media.forEach(url => { text = text.replace(url.url, ''); }); } text = text.replace(/\n/gm, '<br />'); return this.sanitizer.bypassSecurityTrustHtml(text); } } When you create a custom pipe, you have to implement the transform method and return the value you wish to display. In this case, we receive the entire tweet object (not just the text, because we need the metadata), and process it in several ways. Twitter returns data in a consistent structure, so we just inspect each property to figure out if any URLs, media, or mentions are present. If they are, we replace those values with a link, or in the case of media it’s removed because images are already displayed. However, Angular normally prevents you from passing HTML and binding it into a template for security reasons. Angular allows you to bypass this and handle sanitizing input directly. The way we’ve solved it here is to sanitize the tweet text first, which will remove any potentially dangerous content (such as links with javascript: or script tags). Then we modify the text string to replace mentions and urls with link tags. Finally, we use the DomSanitizer.bypassSecurityTrustHtml method to bypass the security restrictions for the text to display. However, since we sanitized the text at the beginning, the content can be trusted. When you have a pipe like this, be very careful of security and I recommend reviewing the Angular security guide. Summary That wraps up our rapid tour of an Angular Twitter client, and we saw a lot of Angular’s key features on display, and learned how to build a basic NodeJS server that connects to the Twitter API. This is intended to be a basic example, but many additional capabilities could be added fairly easily, such as composing tweets, viewing user profiles, and other interactions. I encourage you to look into the Twitter API documentation to see what options you have and see what else you can build! Get practical advice to start your career in programming! Master complex transitions, transformations and animations in CSS!
https://www.sitepoint.com/building-twitter-app-using-angular/
CC-MAIN-2021-04
refinedweb
3,683
57.06
On Tue, Jun 1, 2010 at 10:32 PM, Neil Brown <neilb@suse.de> wrote:> On Tue, 1 Jun 2010 12:50:01 +0200 (CEST)> Thomas Gleixner <tglx@linutronix.de> wrote:>>>>> OK.> Here is my suggestion.>> While I think this patch would actually work, and hope the ugly aspects are> reasonably balanced by the simplicity, I present it primarily as a base for> improvement.> The important part is to present how drivers and user-space can co-operate> to avoid losing wake-events. The details of what happens in the kernel are> certainly up for discussion (as is everything else really of course).>> The user-space suspend daemon avoids losing wake-events by using> fcntl(F_OWNER) to ensure it gets a signal whenever any important wake-event> is ready to be read by user-space. This may involve:> - the one daemon processing all wake eventsWake up events are not all processed by one daemon.> - Both the suspend daemon and the main event handling daemon opening any> given device that delivers wake events (this should work with input> events ... unless grabbing is needed)Not all wakeup events are broadcast like input events so they cannotbe read by both daemons. Not that this really matters, since readingthe event from the suspend daemon does not mean that it has beendelivered to and processed by the other daemon.> - The event handling daemon giving the suspend-daemon's pid as F_OWNER, and> using poll/select to get the events itself.I don't like the idea of using signals for this. Without the hack AlanStern suggested, you will temporarily block suspend if the wakeupevent happened before the suspend daemon thread made it to the kernel,but abort suspend if it happened right after.>> When 'mem' is written to /sys/power/state, suspend_prepare waits in an> interruptible wait until any wake-event that might have been initiated before> the suspend was request, has had a chance to be queued for user-space and> trigger kill_fasync.And what happens if you are not waiting when this happens?> Currently this wait is a configurable time after the last wake-event was> initiated. This is hackish, but simple and probably adequate.Waiting after a wake event is the same as suspend_block_timeout. Thisis useful when passing events through layers of code that does noblock suspend, but we should strive to avoid it. Other people had muchstronger objections to this, which is why it is not included in thelast suspend blocker patchset.It also does not work for drivers that need to block suspend for morethan a few seconds. For instance the gpio keypad matrix driver needsto block suspend while keys are pressed so it can scan the keypad.> If more precise timing is needed and achievable, that can be added later. It> would be an entirely internal change and would not affect the API further.> Some of the code developed for suspend-blockers might be a starting point for> this.>> Drivers should call pm_suspend_delay() whenever a wake-event occurs. This> simply records the time so that the suspend process knows if there is in fact> any need to wait at all.>> The delay to wait after the last pm_suspend_delay() is limited to 10 seconds> and can be set by kernel parameter suspend_block_delay=number-of-milliseconds> It defaults to 2 jiffies (which is possibly too short).>> - Would this fix the "bug"??> - and address the issues that suspend-blockers was created to address?> - or are the requirements on user-space too onerous?>>> Thanks,> NeilBrown>> Signed-off-by: NeilBrown <neilb@suse.de>>> diff --git a/include/linux/suspend.h b/include/linux/suspend.h> index 5e781d8..ccbadd0 100644> --- a/include/linux/suspend.h> +++ b/include/linux/suspend.h> @@ -142,11 +142,13 @@ extern void arch_suspend_disable_irqs(void);> extern void arch_suspend_enable_irqs(void);>> extern int pm_suspend(suspend_state_t state);> +extern void pm_suspend_delay(void);> #else /* !CONFIG_SUSPEND */> #define suspend_valid_only_mem NULL>> static inline void suspend_set_ops(struct platform_suspend_ops *ops) {}> static inline int pm_suspend(suspend_state_t state) { return -ENOSYS; }> +static inlint void pm_suspend_delay(void) {}> #endif /* !CONFIG_SUSPEND */>> /* struct pbe is used for creating lists of pages that should be restored> diff --git a/kernel/power/suspend.c b/kernel/power/suspend.c> index 56e7dbb..07897b9 100644> --- a/kernel/power/suspend.c> +++ b/kernel/power/suspend.c> @@ -46,6 +46,69 @@ bool valid_state(suspend_state_t state)> return suspend_ops && suspend_ops->valid && suspend_ops->valid(state);> }>> +/*> + * Devices that process potential wake-up events report each> + * wake-up events by pm_suspend_delay();> + * This ensures that suspend won't happen for a "little while"> + * so the event has a chance to get to user-space.> + * pm_suspend calls wait_for_blockers to wait the required> + * "little while" and to check for signals.> + * A process that requests a suspend should arrange (via> + * fcntl(F_GETOWN)) to get signalled whenever a wake-up event> + * is queued for user-space. This will ensure that if a suspend> + * is requested at much the same time as a wakeup event arrives, either> + * the suspend will be interrupted, or it will complete quickly.> + *> + * The "little while" is a heuristic to avoid having to explicitly> + * track every event through the kernel with associated locking and unlocking.> + * It should be more than the longest time it can take between an interrupt> + * occurring and the corresponding event being queued to userspace> + * (and the accompanying kill_fasync call).> + * This duration is configurable at boot time, has a lower limit of 2> + * jiffies and an upper limit of 10 seconds. It defaults to the minimum.> + */> +static unsigned long little_while_jiffies = 2;> +static int __init setup_suspend_block_delay(char *str)> +{> + unsigned long msec;> + if (sscanf(str, "%lu", &msec) != 1)> + return 1;> + if (msec > 10000)> + msec = 10000;> + little_while_jiffies = msecs_to_jiffies(msec);> + if (little_while_jiffies < 2)> + little_while_jiffies = 2;> + return 1;> +}> +__setup("suspend_block_delay=", setup_suspend_block_delay);> +> +static unsigned long next_little_while;> +void pm_suspend_delay()> +{> + unsigned long then = jiffies + little_while_jiffies;> +> + if (then != next_little_while)> + next_little_while = then;> +}> +EXPORT_SYMBOL_GPL(pm_suspend_delay);> +> +static int wait_for_blockers(void)> +{> + unsigned long timeout;> +> + if (time_after(jiffies, next_little_while))> + return 0;> + timeout = next_little_while - jiffies;> + if (timeout > msecs_to_jiffies(10000))> + /* jiffy wrap */> + return 0;> +> + while (timeout && !signal_pending(current))> + timeout = schedule_timeout_interruptible(timeout);> + if (signal_pending(current))> + return -EINTR;> + return 0;> +}> /**> * suspend_valid_only_mem - generic memory-only valid callback> *> @@ -89,6 +152,10 @@ static int suspend_prepare(void)> if (error)> goto Finish;>> + error = wait_for_blockers();> + if (error)> + goto Finish;> +> error = usermodehelper_disable();> if (error)> goto Finish;>>-- Arve Hjønnevåg--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2010/6/2/57
CC-MAIN-2017-17
refinedweb
1,053
54.22
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives A new compiled, protoype-based programming language called Lisaac is making some small waves on reddit due to its strong showing on microbenchmarks. Lisaac is inspired by Self, Smalltalk, and Eiffel. Sample code does look a bit verbose. Here's the grammar. Stated goal of Lisaac is to build an operating system. I think their use of "+" and "-" is the reverse of what I would have done. And the whole ALLUPPERCASE thing is so uncouth. :-} Edit: Clueless question - is Has-A (vs. Is-A) easily supported w/out lots of finger typing? Answer: Ah, you have have as many parents as you want. I guess that is more like MI or Mix-ins than delegation, though, since you get everything from the parent. To answer you about the meaning of the + and - "operators": "+" means that the slot or local variable it refers to is not shared. That means if an object is cloned, + slots can be different for all objects. For local variables, it means that the variable is not shared betwen invocations of the slot. "-" is like the "static" keyword in C or java. For a slot in a prototype, it means that the slot will be shared for all objects created from that prototype. This is often the case for code slots (ie methods) because you don't need a different implementation for every objects ... code is often shared. For a local variable, it means that this variable is the same for all invocations of the slot (like static variables in a function in C). For the ALL_IN_UPPERCASE for prototypes, you'll have to argue with our the creator: Benoit Sonntag ... and personally I don't care. You just have to be remidnded to use the CAPS LOCK key on your keyboard if you don't want your fingers to get hurt. But one advantage is that the case in Lisaac can differenciate words in different namespaces. Title case for keyword, UPPERCASE for types and lowercase for identifiers. I think I understood the definitions of "+" and "-" when I read the docs, it is just that I don't think they are good mappings from a usability perspective - based only on my own knee-jerk connotations for those. I.e. to me, "+" feels more open and therefore sharable. On every keyboard I use, I've gotten rid of CAPS LOCK. First, to avoid having it down accidentally, and second because I generally would rather have it act as another Ctrl key since I'm an Emacs user :-) I agree with you, I think that the use of "+" and "-" signs makes it hard to read. Neruda Last month on LtU "...seems everyone on the web is talking about the language Io at the moment..." so to what extent can those "dynamic" Io examples be written in Lisaac? What do we give up to get 4500x better performance? ..I think that "code as data" is lost somewhere in Lisaac's two-stage to-C compiler. Also, it's interesting to note, that Lisaac's "simplicity graph" is almost a direct clone of Io's, yet excludes Io from it. Multiple inheritance and shared vs local slots both seem like strange ideas for a prototype based language. Less simple/uniform syntax. No macros/meta-whizbang. That's my initial opinion, at least. That Io keyword count chart doesn't seem to have a link on the Io website. Is it also interesting to note that Lisaac's keyword count chart includes a count of 0 for Prolog, and yet Io's keyword count chart excludes Prolog? :-) I had a longer reply, but by the end it seemed excessively off topic. My only point was that the authors seem at least aware of Io, but chose not to include it in their comparison, despite it's linguistic similarities (along with Eiffel and Self). Prolog isn't close at all in terms of language design to Io. Either way, I'd looked at the Lisaac language reference to get a feel for the language and noted a few of things that stuck out to me, in response to your question posed earlier. Like I said earlier, the language seems to have a few things which make it more complicated than necessary (ie. four kinds of inheritance, shared vs local slots, syntax). Io is known by Liaac authors, it appears in the Links section: If it is not included I think it's because the simplicity graph is kind of old. It only refers to the first version of the language. And with the second version, the syntax changed a bit and i'm not sure the graph is still relevant. Because what is a keyword ? Actually some words can be seen as keywords like those which start with uppercase and end with lowercase, but they do not conflict with types (all in uppercase) not identifiers (all in lowercase). And they can only be found in some contexts. For example "Section Private" begins a section where slots are marked as private. The keyword "Expanded" can be added in front of types and it means that the value defined that way will hold directly the object and not a reference to it. In pre/postconditions (yet, there is contract programming built-in) you can use Result to refer to the return value of the slot and Old before a variable to ask for the value it contained at the beginning of the block). But even if there is all these words, I think the language remains simple. if you want to do all that Lisaac does, you can't avoir keywords forever. But what I like about it, is that there is never ambiguity betwen those keywords and the identifier that you choose (the case and context makes the difference) PS: it seems that my comment didn't get posted, so if there is a duplicate, excuse me. And, also, don't hesitate to join the mailing list if you are interrested ... ask questions ... I agree that having keywords or even large amounts of keywords makes a language any less simple. What does, to me, is the addition of lots and lots of features. I can understand their usefulness, things like static typing, contracts, various kinds of inheritance and slot exposure, but I don't think having these things makes a language simple. A simple prototype based language would have the minimum required to make a useable and flexible language. This would reduce the language to something like, objects are essentially collections of slots, everything is a value (higher order functions / closures), dynamic late-bound typing, one type of inheritance (copy on clone) and exception handling. I'm sure though, that simplicity isn't their primary goal, as Io's is, and that being able to use the language to construct a reasonably reliable OS is. And that is the source of most/all differences between the two languages. Well, Lisaac have a little more keywords than it once had ... but nonetheless, it is still very simple. The first time you look at it, it may not seem that simple but it is. Basicly we have just objects with prototypes that are a collection of slots. Each slot may be associated with an advanced access list. Slots can be shared from objects of the same family or not (+/-). Slots can have contracts. And that's all. Everything else is in the library. It may seem a bit too much for you, but there are many others languages far more complicated. Including the most used languages. and frankly, I think there is not much to remember. But I agree that there are languages that are simpler ... Like Io probably. But they do not produce fast executables like Lisaac does. And do not provides facilities like string type system and contracts. This simplicity graph has no value in comparing languages. A language with few keywords might force the programmer to encode everything. Just try programming in the pure lambda calculus. A language might also put everything in libraries, which may or may not be counted as keywords. Hi, I suppose you are talking about the way it is possible to create const objects in Io ..? But excuse me but I don't see its usefullness. I think you could say that in Lisaac, this job is dome automatically by the compiler. If you try to change the parser at run-time or the code representation at run-time ... well, it's impossible (it is already compiled). But I don't see where it would be useful. And i think pretty much anything else is possible. I have a simple question: How to uninstall Lisaac? I mean, the language is great, but I may want to uninstall it to intall a new version. I also notice that the documentation in general is lacking a good tutorial. Where can I find a good tutorial? you will find documentations and tutorials here: If you have installed the 0.12 version, you just have to remove the lisaac directory in your HOME and the last line of you bashrc. If you use the 0.13 a make clean should do the job. Hi, Xoswald. Since you seem to know a lot about lisaac, could you inform the team in charge of writing the lisaac compiler that it may have a bug? I mean, I can write programs that make the compiler crash, when running on Windows XP. I mean, the compiler should report an error, if the program is not correct; it should not crash. Below, you will find a silly buggy code, whose only purpose is to crash the compiler. // File zeca.li Section Header + name := ZECA; Section Inherit - parent_object:OBJECT := OBJECT; Section Public + value : INTEGER := 3; -set_value n:INTEGER ( value := n;); -get_value ( value;) Section Header + name := MICO; // File mico.li Section Public -main ( +slo : ZECA; +v:INTEGER; slo := ZECA.clone; v := slo.get_value; ) Issues like this are probably better raised directly with the Lisaac developers in the appropriate forum... I have tried to reply but it seems that pasting here delete some characters :/ Feel free to send us a mail on our list isaac-devel. or open a bugreport.
http://lambda-the-ultimate.org/node/2668
CC-MAIN-2021-25
refinedweb
1,720
73.07
A. We’ve previously discussed the best indie games , so make sure you check those out for some inspiration as to what can be achieved with tools such as Unity. These indie game development teams have demonstrated an agility and risk-tolerance that, in many cases, allows them to push gameplay innovation faster than their big budget counterparts. A number of shockingly successful indie titles have premiered in recent years, including Minecraft, Limbo, and Super Meat Boy, and even if you don’t have to skills to make games like this, you can make a game using Buildbox . In the rapidly evolving landscape of indie game development, Unity has emerged as something of a de-facto standard: its low cost, ease of use, and broad feature set make it ideal for rapid game development. Unity is so flexible, that you can even make your own custom game controllers How to Make a Custom Game Controller With Arduino and Unity How to Make a Custom Game Controller With Arduino and Unity Have you ever wanted to design your own game controller? It's easier than you think! Read More with a bit of DIY know how! Even large studios such as CCP (Developers of Eve Online) use it for rapidly prototyping game concepts. Unity provides a “game engine in a box” — a physics and rendering engine with hooks for several scripting languages, adaptable to virtually any genre of videogame. While Unity does provide a visual editor for manipulating the game environment, Unity is not a ‘zero programming’ game creator tool. It requires you to program to produce results, but also gives you a much more flexible and powerful tool than any ‘game maker’ program possibly could. Unity won’t do the work for you, but it does lower the barrier to entry substantially. Starting completely from scratch with C++ and OpenGL, it can take days to get to the point where there’s actually something rendered onscreen. Using Unity, it takes about ten seconds. Unity puts the basic elements of game creation into the hands of novice programmers in a fast, intuitive way. Today I’ll be guiding you through everything you need to know to make a game in Unity, which is broken down into ten main chapters: §3–A Brief Introduction to the Object-Oriented Paradigm §5–Example: Basic Elements of a Game §7–Example: Scripting Pong §8–Exploring the Documentation / Learning More §9–Building Your Game / Compiling to a Standalone Application 1. Versions of Unity Unity comes in two basic flavors: the pro version and the free version. There are a number of differences, but, broadly speaking, the pro version supports a number of visual improvements (like real-time soft shadows and post-processing), and a large number of relatively minor features that are extremely helpful for more complex games. That said, for most relatively simple games you might want to build, the free version of Unity is perfectly adequate. We’ll break down the key differences below in more detail for those interested. 1.1 Pricing The free version of Unity is, of course, free. However, there are a few limitations: the free version of Unity cannot be licensed to any company with an annual income of more than $100,000. While such organizations are beyond the scope of this guide, if you suspect you might become such an organization, it’s probably wise to spring for the Pro version. The Pro version of Unity is $75 a month, or $1500 for a permanent license, and has no limits on what you can do with the games created with it. There is also a 30-day free trial available, which we’ll be using for this guide, in order to give you as complete an overview of the available features as possible. A one-year student license is also available through Studica for $129. 1.2 Features There are many features absent in the free version of Unity. However, the most important differences are as follows: the free version of Unity lacks a number of rendering options that allow for better-looking, faster-running games (LOD support, screen-space post-processing, advanced shaders, real-time soft shadows, and deferred rendering). It also lacks the full mechanim animation system, and some AI tools. In general, for complex, large-scale projects, or projects where graphical performance is important, the pro version is worthwhile. I use the pro version, because I develop virtual reality games for the Oculus Rift Oculus Rift Review Oculus Rift Review Virtual Reality is not new, but it's finally affordable and within our grasp. After four year and two development prototypes, the final consumer edition of the Oculus Rift has arrived. Read More , and the screen-space post-processing support is necessary to correctly interact with the headset. 2. Installing Unity Unity is straightforward to install. You can download the executable from unity3d.com/get-unity/download. Once downloaded, run it, and then follow the installer instructions. When the installation is finished, a window titled ‘activate your Unity license’ will appear. Check the box marked ‘activate a free 30-day trial of Unity Pro’ and then ‘OK’. Congratulations! You now have a 30-day trial of Unity Pro. When the trial expires, if you don’t want to buy the pro version, you can switch to the free version and keep your existing content. 3. A Brief Introduction to the Object-Oriented Paradigm Before getting started started with Unity, it’s important that we go over the basics a little. Unity supports both C# and JavaScript for game programming; we’ll be working with C# for this tutorial. First off, if you’ve never programmed before, put this tutorial aside and spend a few days working through Microsoft’s C# Language Primer until you feel comfortable using the language for simple tasks. If you’d like something a bit different to C# (but not necessarily a language you can use in Unity), then take a look at our guide to the six easiest programming languages for beginners 6 Easiest Programming Languages to Learn for Beginners 6 Easiest Programming Languages to Learn for Beginners Learning to program is about finding the right language just as much as it's about the edification process. Here are the top six easiest programming languages for beginners. Read More . If you have programmed before in an imperative or object oriented language like C or Java, skim the primer and familiarize yourself with how C# differs from other languages you’ve used in the past. Either way, don’t proceed with the tutorial until you feel comfortable solving simple problems with C# (for example, if I were to ask you to write a program that prints the first hundred prime numbers, you should be able to write that program without consulting Google). The most important concept to understand here is the object-oriented paradigm (abbreviated as OOP). In object oriented languages, programs are divided into functional units called Objects. Each object has its own private variables and functions. Object-specific functions are called methods. The idea here is modularity: by having each object isolated, and forcing other objects to interact with it through its methods, you can reduce the number of possible unintentional interactions — and, by extension, bugs. You can also create objects you can reuse later with no modification. In Unity, you’ll be building these objects and attaching them to game entities (whose behavior they’ll govern). Objects are instantiated from classes: a class is just a file that lays out the definition of your object. So, if you want a Mook object that handles AI for an enemy in your game, you’d write a ‘Mook’ class, and then attach that file to every enemy entity. When you run your game, each enemy will be equipped with a copy of the ‘Mook’ object. Attaching a new script to an object looks like this: First, select the object and go to the Inspector. Click on the Add Component button. Go to new script, enter the name you want, and click create and add. Now you have a new script that you can edit by double-clicking on it! A class file looks something like this: using UnityEngine; public class Mook : MonoBehaviour { private float health; void Start () { health = 100; } void Update(){ if (health > 0) { /* Search for player if you encounter the player on the road, kill him if you get shot, remove a random amount of health */ } } } Let’s break this down: - Using UnityEngine: This line tells C# that we want to use Unity’s libraries, which allow us to connect to the Unity game engine. - Public class Mook : MonoBehaviour:This line declares the class and its name — Mook. - Private float health: This declares a private class variable (which can only be changed from inside the class). The variable is given a value in Start. - Void Start(): This declares a method called Start. Start is a special method that runs only once, when the game initially launches. - Void Update(): Update is another special method, which runs on every frame. Most of your game logic will go here. - //if you encounter the player on the road, kill him: This line is a comment (any line starting with a double slash is ignored by C#). Comments are used to remind yourself of what particular bits of code do. In this case, this comment is being used to stand in for a more complicated block of code that actually does what the comment describes. Along with Start and Update, you can instantiate your own methods with almost any name. However, methods that you create won’t run unless they’re called. Let’s declare a method for a hypothetical class called addTwoNumbers that adds two numbers together: public float addTwoNumbers(float a, float b) { return a+b; } This declares a public (accessible to other objects) method that returns a float, called addTwoNumbers, which takes two floats as input (called a and b). It then returns the sum of the two values as its output. Calling this method from within the same class (say, from inside Update) looks like this: float result = addTwoNumbers(1, 2); Calling the method from another class is similar: addTwoNumbers instance; float result = instance.addTwoNumbers(1, 2); Again, this just creates an instance of our class, accesses the appropriate method and feeds it the numbers we want to add, then stores the result in result. Simple. If your script is attached to an object that has special properties (like a particle emitter) that can’t be accessed under the normal set of GameObject parameters, you can choose to treat it as a different kind of game entity by using the GetComponent method. The syntax for that looks like this: GetComponent<ParticleSystem>().Play(); If any of this is unfamiliar to you, go back and go through the C# primer. It’ll save you a lot of frustration as we proceed. 4. Unity Basics In this section, we’re going to work our way through the basic mechanics of the Unity engine. The workflow in Unity goes something like this: - Create an entity to serve a role in the game (blank GameObjects can be used for abstract logical tasks). - Write or find a class file, and add it to the entity as a script (using the Add Component button in the inspector view. - Run > test > debug > repeat until it works and move on to the next element of the game. Unity comes with a number of basic view tabs that can be laid out in various ways to the taste of the user. The big five are: - Game: displays a running instance of the game that you can interact with and test. - Scene: provides a static, editable version of the game world. - Inspector: allows you to modify individual entities in the game world by selecting them in the editor tab. - Project: allows you to browse through the project’s files and drag models, materials, and other resources into the editor tab to place them in the game world. - Hierarchy: this tab shows all objects in the world, allowing you to find distant objects in the scene, and parent entities to one another by clicking and dragging. See the diagram below for the locations of all these things: 4.1 Unity Entities 4.1.1 Meshes Meshes are the way 3D geometry is represented in Unity. You can either use Unity’s built-in primitive objects (cubes, spheres, cylinders, etc), or import your own 3D models from a modelling package like Blender Getting Started with Blender: 7 Fantastic Tutorials for Newbies Getting Started with Blender: 7 Fantastic Tutorials for Newbies 3D modeling is an excellent way to exercise creativity while keeping in touch with your technical side. Here are some awesome free tutorials. Read More or Maya Learning Maya 2016: Where To Get Started Learning Maya 2016: Where To Get Started Maya is a tool used for 3D animation, but it comes with an incredibly steep learning curve. What good teaching material is there? Read More . Unity supports a variety of 3D formats, including .fbx, and .3ds.. 4.1.2 GUI Elements Traditional GUI sprites and text can be displayed using the GUI Text and the GUI Texture GameObjects in the editor.. 4.1.3 Materials Materials are combinations of textures and shaders , and can be dragged directly onto game objects from the project tab. A large number of shaders come with Unity Pro, and you can adjust the texture attached to them using the inspector tab for an object that they’re applied to. To import a texture, convert it to a .jpg, .png, or .bmp, and drag it into the assets folder under the Unity project directory (which appears in My Documents by default). After a few seconds, a loading bar will appear in the editor. When it finishes, you’ll be able to find the image as a texture under the project tab. 4.1.5 Lights. 4.1.6 Particle Systems. There are a lot of parameters that you can tweak to achieve these effects, and you can access them by spawning a particle system under the component editor > selecting the particle system > opening the inspector tab. You can change the size, speed, direction, rotation, color, and texture of each particle, and set most of those parameters to change over time as well. Under the collision attribute, if you enable it and set the simulation space to world you’ll get particles that will collide with objects in the world, which can be used for a number of realistic particle effects, including rain, moving water, and sparks. 5. Example: Basic Elements of a Game For this tutorial, we’re going to make a simple game of Pong — something that we’ve covered several times in DIY before: - Arduino Classic Pong -... - Arduino OLED Pong Arduino Retro Gaming With an OLED Display Arduino Retro Gaming With an OLED Display Ever wondered just how much work it takes to write your own retro games? How easy is Pong to code for the Arduino? In this section, we’ll go over arranging the core elements — the scripting tutorial will come later. First, let’s break down the game of Pong into its basic components. First, we need two paddles, and a ball. The ball flies offscreen, so we’ll want a mechanism to reset it. We also want text to display the current score, and, for the sake of showing you all the core elements of Unity, we’ll want a fancy particle effect when you hit the ball. The whole game will need to be dramatically lit. That breaks down into a ball object (a sphere), a spawner, two paddle props with particle emitters attached, a 3D-text entity, and a spot light. For this tutorial, we’ll be using the default physic material bounce, with bounce combine set to multiply. Here’s what the setup looks like, in ten screenshots: First, create a cube prop for the paddle.. Next, you’ll want to position and rotate the camera so that it frames the scene correctly. While the camera is selected, you can see a small preview of the camera’s view in the lower right hand corner. Before we finish, we need to create two additional cubes to be bumpers, to prevent the ball from bouncing out of the game area. We can make them invisible by unchecking the mesh renderer in the inspector tab. If you hit play, you can now see the basic elements of our game laid out. They won’t do anything yet, but we’ll get to that! Now that we’ve got that setup, we’re going to talk about what’s involved in scripting these elements to make a game. 6. Scripting in Unity. If you’ve used Eclipse or other IDE’s, MonoDevelop is very similar. You can build your scripts from inside the editor, to check for syntax errors, like so: In general, to get your script to interact with Unity, you’ll need to reference elements that the object holding the script possesses (you can see a list of these elements under the inspector tab when the relevant object is selected). You can then call methods or set variables for each of these elements to enact the changes you want.): - Transform - Cube (Mesh Filter) - Box Collider - Mesh Renderer Each of these aspects of the object can be influenced from within a script. Next, we’ll look at exactly how. 6.1 Transform The transform functions for a GameObject in Unity control the physical parameters of that object: its scale, its position, and its orientation. You can access them from within a script like this: transform.position = newPositionVector3; transform.rotation = newRotationQuaternion; transform.localScale = newScaleVector3; In the above examples, the named variables are of the types specified in the names. There are a few key details here: position and scale are, as you’d expect, stored as Vector3s. You can access the X, Y, and Z components of each (for example, transform.position.y gives you the distance of an object above the zero plane). However, to avoid gimbal lock, rotations are handled as Quaternions (four-component vectors). Because hand-manipulating quaternions is unintuitive, you can manipulate rotations using Eulerian angles by using the Quaternion.Euler method like so: transform.rotation = Quaternion.Euler(pitch, yaw, roll); If you wish to move objects smoothly from one place to another, you’ll find the Slerp method for quaternions and vector3s helpful. Slerp takes in three arguments – the current state, the final state, and the speed of change, and smoothly interpolates between them at the given speed. The syntax looks like this: transform.position = Vector3.Slerp(startPositionVector3, newDestinationVector3, 1); 6.2 Renderer The renderer functions in Unity allow you to control the way the surfaces of props are rendered on-screen. You can reassign the texture, change the color, and change the shader and visibility of the object. The syntax looks like this: renderer.enabled = false; renderer.material.color = new Color(0, 255, 0); renderer.material.mainTexture = myTexture; renderer.material.shader = newShader; Most of these have pretty clear functions. The first example makes the object in question invisible: a useful trick in a number of situations. The second example assigns a new RGB color (namely, green) to the object in question. The third assigns the main diffuse texture to a new Texture variable. The last example changes the shader of the object’s material to a newly defined shader variable. 6.3 Physics Unity comes with an integrated physics engine — something that physics sandbox games Smash, Drive & Build: 3 Awesome Physics Sandboxes Simulators Smash, Drive & Build: 3 Awesome Physics Sandboxes Simulators Read More all use. This allows you to assign the physical properties of objects and let the details of their simulation be handled for you. In general, rather than trying to implement your own physics using a textbook and the transform system, it is simpler and more robust to use Unity’s physics engine to the greatest extent possible. All physics props require colliders. However, the actual simulation itself is handled by a rigidbody, which can be added in the inspector view. Rigidbodies can be kinematic or nonkinematic. Kinematic physics props collide with (and effect) nonkinematic physics props around them, but are unaffected by collision themselves. Static kinematic props are the proverbial immoveable objects, and moving kinematic objects are the proverbial unstoppable force (for the record, when they collide, they simply pass through each other). Beyond that, you can adjust the angular drag of the object (how much energy it takes to spin it), change its mass, dictate whether or not it’s affected by gravity, and apply forces to it. Examples: rigidbody.angularDrag = 0.1f; rigidbody.mass = 100; rigidbody.isKinematic = false; rigidbody.useGravity = true; rigidbody.AddForce(transform.forward * 100); These are all pretty self-explanatory. The only thing to note here is the use of transform.forward. Vector3’s all have three components (.forward, .up, and .right) associated with them, which can be accessed and rotates with them (forward is the direction of the blue arrow in the editor). The transform.forward keyword is simply the forward vector for the current object with magnitude 1. It can be multiplied by a float to create more force on the object. You can also reference transform.up and transform.right, and negate them to get their reverses. 6.4 Collision Often, when building a game, you’d like a collision to result in some change-of-state in your code, beyond just physics simulation. For this, you’ll need a collision detection method. There’s a certain amount of prep work needed to detect collisions in Unity. First, at least one of the objects in the collision needs a non-kinematic rigidbody attached to it. Both objects must have correct colliders, set to be non-triggers. The total speed of both objects must be low enough that they actually collide, instead of simply skipping through one another. If you’ve got all that taken care of, you can check for collision by placing a special collision detection method in a script attached to the object you’d like to check collision with. The method will look like this: void OnCollisionEnter(Collision other) { //do things here } This method will automatically run during the first frame that another object touches your object. The collision entity other is a reference to the object that you hit. You can, for example, reference its gameobject, rigidbody, and transform characteristics to manipulate it in various ways. While OnCollisionEnter is probably the most common function you’ll be using, you can also use OnCollisionExit and OnCollisionStay (with otherwise identical syntax and usage), which activate during the first frame that you stop colliding with an object and during every frame that you’re colliding with an object, respectively. Sometimes, it can also be useful to do what’s called raycasting. In raycasting, an infinitely thin line (a ray) is cast through the world from some origin, along some vector, and, when it hits something, the position and other details of the first collision are returned. The code for a raycast looks like this: RaycastHit hit; if (Physics.Raycast(transform.position, -Vector3.up, out hit)) { float distanceToGround = hit.distance; } This casts a ray from the position of the current object along -Vector3.up (straight down), and links the variable hit to the first object it collides with. Once your ray has hit something, you can access hit.distance to determine how far away it is, or hit.GameObject to manipulate the object you hit. Raycasts like this can be used for shooters to determine what the gun’s pointed at, or to select objects when the camera looks at them, or for certain styles of movement mechanic. 6.5 Time Correction One important factor to keep in mind when you’re manipulating objects in this way has to do with framerate. No matter how carefully you optimize, framerates will always vary, and you don’t want your game speed to vary accordingly. If someone else runs your game on a faster computer than you developed it on, you don’t want the game to run at double speed. The way you correct for this is by multiplying the values you’re using by the time it took to render the last frame. This is done by using Time.deltaTime. This effectively changes the speed of any variable you’re incrementing every frame from change per frame to change per second, and you should probably make this change to any value you’re incrementing or decrementing every frame. 6.6 Audio Sources and Listeners Now that we’ve covered how to create, render, and control objects, let’s talk about the other sense that computer games can serve: namely, sound. Unity supports two kinds of sounds: 2D and 3D sounds. 3D sounds vary their volume based on distance, and distort as they move relative to the camera; 2D sounds do not. 2D sounds are appropriate for voice-overs and background music, and 3D sounds apply to sounds generated by events in the world. In order to change whether or not a sound is 3D, select it in the project view, switch to the inspector view and select the appropriate option from the dropdown menu, then press the reimport button. In order to actually play the sound, you’ll need to attach an audiosource to a prop (the prop you want the sound to originate from, in the case of a 3D sound). Then you’ll need to open the audioclip field and select your sound file. You can use myAudioSource.Pause() and myAudioSource.Play() to control those sound files. You can adjust the falloff behaviors, volume, and doppler shifting of the sounds under the inspector tab for the audiosource. 6.7 Input A game that doesn’t take any input from the user isn’t much of a game. There are a lot of different kinds of input you can read in, and almost all of them are accessible through the Input and KeyCode objects. Some sample input statements (which have a values evaluated every frame) are below. Vector3 mousePos = Input.mousePosition; bool isLeftClicking = Input.GetMouseButton(0); bool isPressingSpace = Input.GetKey(KeyCode.Space); The functions of these lines is mostly self explanatory. Using these three kinds of input reference, you can reconstruct the control schemes of most modern 3D computer games. 6.8 Debugging a Script Let’s say a script doesn’t work. As the good doctor says, bangups and hangups can happen to you. If there are outright syntax errors with your C#, the game will generally refuse to run when you hit play, and some fairly useful error messages are provided if you build the scripts from within the editor. See below: These bugs are typically not the most difficult to fix. What can be more problematic are subtle semantic errors, in which you have successfully written a file full of valid C# – just not one that does what you thought it would. If you have one of these errors, and you’re having trouble tracking it down, there are a few things you can try to improve the situation. The first is to pause the execution of the game, and check the console. You can pause the game by clicking on the pause icon in the upper middle portion of the editor, and then selecting console from the bottom of the window menu (or pressing Ctrl > Shift > C). Even if there are no errors, warnings can still help to give some clues as to what might be going wrong. If this doesn’t work, you can also try to get some idea about the state of your script by printing the state of internal variables to validate that the program is doing what you think it’s doing. You can use Debug.Log(String) to print the contents of a string to the console when the program execution hits that line. In general, if you work backwards from what you think should be happening through the things that should be making it happen, eventually you will reach a point where your debug prints don’t do what you expect them to do. That’s where your error is. 7. Example: Scripting Pong To build Pong, let’s. A good first step would be to add a non-kinematic rigidbody to the ball, two kinematic rigidbodies to the paddles, disable gravity for all of them, and assign an appropriate physic material from the standard assets (bounce with bounce combine set to multiply). Below, you can view the script for the ball with explanatory comments. The ball needs to accomplish some basic goals: it should bounce in a complicated pattern, always maintaining movement on both axes, and it should accelerate at a challenging but not impossible pace in the horizontal direction. Next, we need to script our paddle, which you can view below. The paddle needs to move up and down in response to key presses (but not outside certain bounds). It also needs to trigger the particle system when it collides with something. Next, we need enemy AI: something that will cause the enemy’s paddle to track towards the ball at a fixed rate. For that, we’ll be using Vector3.Slerp for maximum simplicity. We’d also like the same particle behavior that we see on our own paddle. Finally, we need a script to update the scoreboard and reset the ball when it goes out of bounds. With those scripts attached and the references filled in, when we run our game of Pong, we experience gameplay! You can download my Pong demo, if you’d like to see everything I’ve outlined in action. It runs on Windows, Mac and Linux systems. 8. Exploring the Documentation / Learning More Unity is a complex engine with many more features than could feasibly be covered in a guide of this style, and that’s before you include the wide swathe of (free and commercial) Unity extensions available on the internet. This guide will give you a strong starting place for developing a game, but self-education is an important skill in any endeavor, and doubly so here. A crucial resource here is the Unity ScriptReference. The ScriptReference is a searchable database, available for both C# and Javascript, which has a list of every Unity command and feature, with descriptions of their functions and brief examples of syntax. If you’re having trouble with the editor and interface of Unity, or just like video tutorials as a matter of preference, there is a long list of high-quality Unity video tutorials available. More extensive (but less broad) text tutorials for Unity are also available from CatLikeCoding. Finally, if you have questions beyond the scope of documentation or tutorials, you can ask specific questions at answers.Unity3d.com. Remember that answers are provided by volunteers, so respect their time and search the database first to make sure your question hasn’t already been answered. 9. Building Your Game / Compiling to a Standalone Application When you’ve built something you’re proud of (or you’ve finished cloning our slightly dodgy Pong example for practice), it’s time to move your game from the editor and turn it into something that you can post on the internet and force your friends and family to play. In order to do that, you’ll need to build a standalone application. The good news is that in Unity, this is very, very easy. There are, however, a few potential hiccoughs that you’ll want to be careful of. For starters, know that you can only build an error-free project. To that end, make sure you have the console open as you build: there are some error conditions that the game will ignore in the editor, but will still abort an attempted build. This only dumps error messages to the console, with no visible results onscreen, which can be frustrating if you forget to check. Once you’ve got your game compiling error-free, though, you can select Build Settings under the File menu, or press Ctrl > Shift > B. This will bring up a simple dialog that allows you to build your game for several platforms. The process from there is self explanatory: select your options, and hit build; the game will prompt you for a directory to install to, and will place both the executable and data directory there. These two files can be zipped together and distributed (just make sure you aren’t charging for a game built in the Unity demo, as this violates the terms of service). 10. Closing Notes As with any game development tool, the key to success with Unity is iterative development. You have to build in manageable increments — be ambitious, by all means, but be ambitious in small chunks, and arrange those chunks such that, even if you fall short of your ultimate ambition, you’ll at least wind up with a coherent product. Get the most crucial elements in first: have an idea in mind of your minimum viable product, the simplest, most bare-bones thing you could possibly create and still feel as though you achieved something worthwhile. Get to that minimum viable project before moving on to larger ambitions. This tutorial gives you a strong starting place, but the best way to learn Unity is by building a game. Start building a game, fill gaps in your knowledge as they come up, and the gradual flow of knowledge will erode away the things you don’t know surprisingly quickly. If you’ve read all this and are a bit overwhelmed by the coding required with Unity, make sure you read our guide on how to make video games without any programming How to Make Video Games Without Any Programming How to Make Video Games Without Any Programming Want to make a video game but can't code? Then use a video game construction kit that lets you build games without any coding required! Read More . Unity is a powerful tool, and with a bit of exploration, you can be building impressive projects with it quicker than you might expect. Let us know what you built in the comments below — we’d love to see! this does not make any sense you start with a scene, without even saying how to get there "select an object" my scene is empty Please tell the writer name of C# Primer. There are confusion over the google with many books name. Great guide! if you are looking for more tips about creating a game I highly recommend blog.theknightsofunity.com great article Thank you, it helped a lot! :) Starting was interesting, but kinda confusing from the mid.... Its a little confusion filled tutorial, but I unfer stand it a little? There's no 3D text!! Where is it?? Don't mention the weakness only. Please admire this article as an introduction to Unity. soz wrong chat
http://www.makeuseof.com/tag/programming-game-unity-beginners-guide/
CC-MAIN-2017-47
refinedweb
5,864
60.75
Install the extension with one of the following commands: $ easy_install Flask-Cache or alternatively if you have pip installed: $ pip install Flask-Cache Cache is managed through a Cache instance: from flask import Flask from flask.ext.cache import Cache app = Flask(__name__) # Check Configuring Flask-Cache methods, since it will take into account the identity.. timeout to “del” to delete cached value: {% cache 'del' %}... If keys are provided, you may easily generate the template fragment key and delete it from outside of the template context: from flask.ext.cache import make_template_fragment_key key = make_template_fragment_key("key1", vary_on=["key2", "key3"]) cache.delete(key) Example: Considering we have render_form_field and render_submit macroses. {% cache 60*5 %} <div> <form> {% render_form_field form.username %} {% render_submit %} </form> </div> {% endcache %} Here’s an example script to empty your application’s cache: from flask.ext.cache. The following configuration values exist for Flask-Cache: In addition the standard Flask TESTING configuration option is used. If this is True then Flask-Cache will use NullCache only. Uses a local python dictionary for caching. This is not really thread safe. Relevant configuration values Uses the filesystem to store cached values Uses a memcached server as a backend. Supports either pylibmc or memcache or google app engine memcache library. Relevant configuration values Uses a memcached server as a backend. Intended to be used with a SASL enabled connection to the memcached server. pylibmc is required and SASL must be supported by libmemcached. Relevant configuration values New in version 0.10. Same as SASLMemcachedCache however, it has the ablity to spread value across multiple keys if it is bigger than the memcached treshold which by default is 1M. Uses pickle. New in version 0.11. This class is used to control the cache objects. This is used to initialize cache with your app object Proxy function for internal cache object. Proxy function for internal cache object. Proxy function for internal cache object. Proxy function for internal cache object. instead of the function name, Flask-Cache will be able to place the args/kwargs in the proper order, and delete the positional cache. However, if delete_memoized has is swapped, the old cached results would eventually be reclaimed by the caching backend..
https://pythonhosted.org/Flask-Cache/
CC-MAIN-2016-30
refinedweb
366
58.58
Closed Bug 345896 Opened 14 years ago Closed 14 years ago menus don't find menupopups in XBL Categories (Core :: XUL, defect) Tracking () People (Reporter: enndeakin, Assigned: enndeakin) Details Attachments (1 file, 2 obsolete files) I want to be able to provide a <menupopup> defined in XBL for a menu, however the menu frame code only looks for non-anonymous children. Example: <binding id="blah" display="xul:menu"> <content> <xul:menupopup> ... </xul:menupopup> </content> </binding> This patch looks for non-anonymous menupopup elements and if not found, looks for anonymous menupopups next. Attachment #230616 - Flags: superreview?(bzbarsky) Attachment #230616 - Flags: review?(bzbarsky) I don't really know this code... If you can find anyone who does (Neil Rashbrook and roc may be the best initial candidates), that would be great. Otherwise I'll try to understand it well enough to review, but that would be really slow (weeks at best). Attachment #230616 - Flags: superreview?(roc) Attachment #230616 - Flags: superreview?(bzbarsky) Attachment #230616 - Flags: review?(roc) Attachment #230616 - Flags: review?(bzbarsky) How about abstracting this out into a new method nsIContent* nsContentUtils::FindFirstChildWithResolvedTag(nsIContent*, nsIAtom*) with an XXX comment that really, we should be returning the first child, but we can't currently do that because XBL currently doesn't tell us the relative ordering of anonymous vs explicit children, and this should be fixed. Also, don't we need to check the namespace somehow? Attachment #230616 - Attachment is obsolete: true Attachment #232811 - Flags: superreview?(roc) Attachment #232811 - Flags: review?(roc) Attachment #230616 - Flags: superreview?(roc) Attachment #230616 - Flags: review?(roc) Comment on attachment 232811 [details] [diff] [review] Use a utility function for this + nsIContent* childContent; + nsCOMPtr<nsIDOMNode> childNode; + children->Item(i, getter_AddRefs(childNode)); + CallQueryInterface(childNode, &childContent); + xblService->ResolveTag(childContent, &namespaceID, getter_AddRefs(tag)); + if (tag == aTag && namespaceID == aNamespace) { + return childContent; + } This seems to be leaking childContent. Use an nsCOMPtr and do_QueryInterface instead. Mention in the comment that the returned pointer has not been addreffed. Attachment #232811 - Attachment is obsolete: true Attachment #233627 - Flags: superreview?(roc) Attachment #233627 - Flags: review?(roc) Attachment #232811 - Flags: superreview?(roc) Attachment #232811 - Flags: review?(roc) Attachment #233627 - Flags: superreview?(roc) Attachment #233627 - Flags: superreview+ Attachment #233627 - Flags: review?(roc) Attachment #233627 - Flags: review+ Status: NEW → RESOLVED Closed: 14 years ago Resolution: --- → FIXED Component: XP Toolkit/Widgets: Menus → XUL QA Contact: xptoolkit.menus → xptoolkit.widgets
https://bugzilla.mozilla.org/show_bug.cgi?id=345896
CC-MAIN-2020-34
refinedweb
388
50.43
10.7. Chapter 10 - Summary¶ Chapter 10 included the following concepts from computing. Loop Body - The statement or statements that are repeated in a loop. In Python indention is used to show the statements that are part of the body of a loop. Total Turtle Trip Theorem - The total turtle trip theorem states that the turtle will draw a closed figure with n sides when the sum of the angles turned is a multiple of 360. Turtle Geometry - Turtle Geometry is a book by Hal Abelson and Andrea diSessa that explores math using turtles. 10.7.1. Summary of Python Keywords and Functions¶ def - The defkeyword is used to define a procedure or function in Python. The line must also end with a :and the body of the procedure or function must be indented 4 spaces. for - A forloop is a programming statement that tells the computer to repeat a statement or a set of statements. It is one type of loop. print - The range - The rangefunction in Python returns a list of consecutive values. If the range function is passed one value it returns a list with the numbers from 0 up to and not including the passed number. For example, range(5)returns a list of [0,1,2,3,4]. If the range function is passed two numbers separated by a comma it returns a list including the first number and then up to but not including the second number. For example, range(1,4)returns the list [1, 2, 3]. If it is passed three values range(start,end,step)it returns all the numbers from start to one less than end changing by step. For example, range(0,10,2)returns [0,2,4,6,8]. while - A whileloop is a programming statement that tells the computer to repeat a statement or a set of statements. It repeats the body of the loop while a logical expression is true. 10.7.2. Summary of Turtle Functions and Procedures¶ The table below shows the turtle functions and procedures that we have covered so far. Note This is the end of chapter 10. We would love it if you could give us some feedback on this chapter at. You might want to open this link in a new tab to make it easier for you to return to your place in this ebook.
https://runestone.academy/runestone/books/published/StudentCSP/CSPRepeatTurtles/summary.html
CC-MAIN-2021-10
refinedweb
396
71.34
On Wed, 2004-07-21 at 19:00, Hashemian, Mehdi wrote: > Hello, > > I apologize if I am sending my question to the wrong email list. It's the right list. > I am trying to copy a node and its children from one XML document to > another one. I clone the node from document A and then append it to > the > root node in document B. If I have elements of copied node in document > A > correctly indented with '\n', in the new document, for each new line I > have three new lines. When I remove the new Lines from document A, > every > thing looks fine in document B. > > I use toprettyxml function to print document to a file. > I use xml.dom.minidom module in python 2.2.2 on Red Hat 9.0. So is your problem with the actual composition of cloned text nodes, or with the way they're handled by prettyprint? You may want to show some code in order to clarify the problem for anyone who can help you. -- Uche Ogbuji Fourthought, Inc. Perspective on XML: Steady steps spell success with Google - Use XML namespaces with care - Managing XML libraries - Commentary on "Objects. Encapsulation. XML?" - A survey of XML standards -
https://mail.python.org/pipermail/xml-sig/2004-July/010365.html
CC-MAIN-2017-22
refinedweb
205
75.2
The Ins and outs of what you can do with BizTalk RFID... We have recently heard one of our customers run into the following issue during BizTalk RFID installation: ------- Error 1957. Failed to set permissions for user domain\account on the RFIDSTORE database on SQL Server FOO. One reason for this could be that we couldn't establish a connection to the SQL database. Please make sure you are using a domain account for the RFID Service account if you specified a remote SQL Server. See logs for more details. In this particular scenario, what was happening was that the account with which Setup was running was the same as the one specified for the RFID Service account credentials. While this may not be a very common scenario (as typically Setup is done by an account in the local administrators group and the default for the RFID Service account is .\RfidSvcAcc), I do see the possibility of somebody requiring this kind of a configuration. However, BizTalk RFID Setup doesn't currently support such a configuration, so I would strongly recommend ensuring during Setup that these two accounts are different. The BizTalk RFID MSDN forums has moved to the following new location: This supports improved filtering/tagging, improved posting experience (dynamic posting, thread preview, real time updates), Live alerts and RSS support. Do check out the new forums, and fire away your questions/feedback! I am very excited about the launch of BizTalk RFID Mobile and BizTalk RFID Standards Pack this month! BizTalk RFID Mobile is the RFID platform for Windows CE/Mobile: our goal is to make it as easy as possible to build a rich RFID/barcode enabled mobile application. In addition to enabling the human workflow scenarios on the mobile device, it also provides store-and-forward capabilities to publish data to a BizTalk RFID Server. You can find the comprehensive details about the platform here. Of course, you will need the corresponding device providers for the mobile device, and you can find those links here. If you have any feedback, please do post on the BizTalk RFID MSDN forums. BizTalk RFID Standards Pack includes a SDK for Tag Data Translation, a standards based discovery library, and a standards-based LLRP device provider which makes it easy to connect to any device that supports LLRP. The Standards Pack also enables the connectivity between BizTalk RFID Server and BizTalk RFID Mobile (for store-and-forward as well as for remote management of the mobile device from server). Here are some links to the documentation/evaluation editions of BizTalk RFID Mobile and BizTalk RFID Standards Pack: Installation Guides and Readme Downloadable Documentation MSDN Documentation Trial Software Code Samples Code Samples: I participated, as a co-speaker, in the TechEd IT Pro conference at Orlando during June this year. Our team had a few sessions here: 1) Deep Dive Into BizTalk RFID: This was a one hour interactive theater style presentation. Here, we started with a general overview of the BizTalk RFID, and then explained the concepts in BizTalk RFID using a shipping/receiving scenario. We used a fixed RFID reader and did a complete end to end demo on how a RFID business process could be set up that can get events from this device and store them into a SQL Server database. The attendees were really excited by the fact that events could go all the way to SQL database without writing even a single line of code. During the demo, we also added the Contoso provider (the simulated provider that ships with BizTalk RFID) and simulated five Contoso devices and showed them how they can use this to do their application development even if they don’t have a physical device. We also did some chalk talk on the general concepts. 2) Building rich RFID enabled applications for Windows CE/Mobile devices using "BizTalk RFID Mobile": This was a 75 minute breakout session. Here we spoke about the evolving mobile scenarios and form factors and the need for a mobile platform. We also went into the features and architecture of the platform. We had tagged some real products and demonstrated a picklist scenario on a mobile RFID reader running BizTalk RFID Mobile Beta and the corresponding device provider. We also did a RFID application development demo using the Windows Mobile emulators and attendees were able to appreciate how they can use this to do application development and testing without requiring to have a physical mobile reader. There was lot of excitement about how simple it was to connect to a radio module, get notified about events, and post events to a server. 3) Tech Talk on BizTalk RFID: This was a 20 minute interview style video recording. Here, Sudhir and I talked about three main topics: a) Application development with BizTalk RFID: b) Manageability: how RFID Manager, Client Console can be used to manage BizTalk RFID, and how System Center Operations Manager (SCOM) can also help in managing RFID devices. c) How can a RFID application developer get started using emulators, Contoso provider / Contoso device simulator / MyFirstCEProvider etc. This video will soon be posted to. Our booth: We had a booth for BizTalk RFID in the SOA theme. Cathexis Innovations had an event management solution that they ran in the booth: for every attendee to the booth, we registered them and printed out a RFID tag for them using BizTalk RFID. This was affixed on their badges, and attendees could come back and get this scanned (in order to increase their chances of winning a Zune) using BizTalk RFID Mobile. I had briefly touched upon Device Security in one of my earlier posts: in particular, the privileges needed for using the DeviceConnection methods. In this post, I will elaborate more on the same: 1) If you are performing a DeviceConnection operation that can potentially change the device (such as DeviceConnection.SetProperty()), the caller should have administrative privileges on the device. Having administrative privilege on a device means that at least one of the following should be true: a) The caller is a member of the builtin administrators group on the server (OR)b) The caller's account is a member of the device's custom administrator list (To view/modify this using RFID Manager, right click on a device -> Security). Note that in addition to being in the custom administrators list of the device, this account also should be added to the RFID_USER group on the server machine. 2) If you are performing a DeviceConnection operation that cannot change the state of the device (such as DeviceConnection.GetProperty()) or DeviceConnection.PrintTag()), the caller does not require administrative privileges. Any account in the RFID_USER group on the server machine should be able to perform such operations. Here's the full list of DeviceConnection methods and the information on whether it requires administrative privileges: Note: If you are using DeviceManagreProxy.ExecuteCommandForConnection(), the same security model described above applies exactly to it as well. However, I would strongly recommend using DeviceConnection for such operations instead of DeviceManagerProxy. (DeviceConnection internally goes through DeviceManagerProxy). One recent question I got on BizTalk RFID was: "Is it possible to try it out with multiple simulated devices?" The good news is "Yes, it is amazingly easy to do this" using the Contoso Provider / Device Simulator. Let's say you have added the Contoso Provider in BizTalk RFID using RFID Manager. 1. Go to %RFIDINSTALLDIR%\Samples\Device Service Provider\Contoso\ContosoEndToEnd\ContosoDeviceSimulator 2. Open ContosoSimulatorConfig.xml 3. Add additional sections here: add one section for each additional device that you want to simulate. Note that each section should have a unique name, unique device name, and unique port number. You need to change only the port information and can use the same IP address. For e.g. section <entry name="DeviceName">ContosoTestDevice2</entry> <entry name="ConnectionType">TCPIP</entry> <entry name="IpAddress">0.0.0.0</entry> <entry name="PortNumber">6667</entry> <entry name="ProviderId">Contoso</entry> <entry name="NotificationDataFile">ContosoNotificationConfig.xml</entry> <entry name="DeviceTranslatorAssemblyPath">Microsoft.Rfid.Test.ContosoDeviceTranslator.dll</entry> <entry name="DeviceTranslatorConfigFile"></entry> </section> 4) Run “runContosoSimulator.cmd”. Now, you can use the Add Device Wizard to add these simulated devices and connect to them. One client connection vs. multiple client connections: We saw an overview of the DeviceConnection class (Microsoft.Rfid.Client) in an earlier post and how it can be used for configuration and operations on a device. Now, consider the scenario where there is a client application which has opened a connection to a particular device and is doing some configuration on it (say for e.g. SetProperty). If another client application wants to open a connection to the same device to configure/operate it, DeviceConnection.Open() doesn't allow it because having more than one application configuring/operating on the device at the same time could affect the state of the device and could potentially take the device to an undefined state. Hence, when the second client application tries to do a deviceConnection.Open(), it would get an exception such as: "Cannot open a connection to device <devicename> because another client has already connected to the device. Retry the operation later" That said, there is an override if your application is really sure of what it is doing and has the required administrative privileges: DeviceConnection.OpenAdministrationConnection(). You can use this if you are sure that you are not stepping on some other client that is connected to the device. Device Security: What privileges are needed for using the DeviceConnection methods? Any operation that can potentially affect/change the state of the device requires the caller to have administrative privileges on the device. Having administrative privilege on a device means that atleast one of the following should be true: 1) The caller is a member of the builtin administrators group (OR)2) The caller is a member of the device's custom administrator list (To view/modify this using RFID Manager, right click on a device -> Security) So, using DeviceConnection.OpenAdministrationConnection() or DeviceConnection.SetProperty() or DeviceConnection.ApplyPropertyProfile() are considered "state changing operations" and hence would require one of the above two privileges. Using DeviceConnection.Open() or DeviceConnection.GetProperty() or DeviceConnection.PrintTag() are not considered to change state and hence don't require the above privileges - just being a member of the RFID_USER group (a Windows group created by BizTalk RFID during its installation) is enough to do such operations. Note that tag related operations (GetTags(), PrintTag() etc.) fall into the latter category. By default, devices in BizTalk RFID inherit security options from the parent device group. Using DeviceConnection from an event handler: If you have an event handler running as part of a RFID process, you may want to use DeviceConnection to do operations such as getting/setting the I/O port value on a device. This scenario is considered to be very similar to any other standalone client application using DeviceConnection. Let's say you want to do a state changing device operation from an event handler such as DeviceConnection.SetProperty(). If you see an exception such as the one below, it means the context in which the event handler is running doesn't have the required privileges to do the operation: System.IO.SensorServices.Rfid.Client.DeviceManagerException: Insufficient permissions to perform the requested operation on device entity <device name>. at System.IO.SensorServices.Rfid.Client.DeviceConnection.ExecuteCommand[TCommand](String deviceSourceName, TCommand cmd, VendorDefinedParameters parameters) at System.IO.SensorServices.Rfid.Client.DeviceConnection.SetProperty(String sourceName, String groupName, String propertyName, Object value, VendorDefinedParameters parameters) An event handler runs in the context of the "RFID Service Account (RSA)" on Windows XP / Windows Vista; it runs in the context of a "Worker Process Account (PSA") on a Windows Server 2003 computer. If this account is not part of the device's custom administrator list, it means that it does not have the privileges to do the operation. You can resolve this easily by adding PSA (on a Windows Server 2003 computer) or the RSA (on a Windows XP or Windows Vista computer) to the device's administrator list, using RFID Manager -> Right click on the device or device group -> Security -> Add. To summarize, any client application or an event handler using the DeviceConnection.Open() or DeviceConnection.OpenAdministrationConnection() is considered to be a "synchronous client". There could be any number of running "RFID Processes" bound to a device and be receiving notifications from the device. Internally, BizTalk RFID maintains only a single connection to the device and closes this connection only when the final interested process or the client goes away. I will post more on the device connection management in a later post. I briefly touched upon device properties (in my earlier post on device configuration and management) in the example of how to get the current device property profile. The "current property profile" of a device or source includes all the properties applicable to the device or source, including the standard properties (those that are defined by BizTalk RFID DSPI) as well as any additional custom properties of a specific device. Now, it may not be feasible for the provider or the device to persist the values of all of these properties, say for e.g. across a reboot of a device. To address such a scenario, BizTalk RFID provides support for a provider to specify the persistence status for a property (using the IsPersistent field in the device property metadata). Based on this information, BizTalk RFID automatically applies such properties every time after it establishes connection to a device. For e.g., you may notice something similar in your RfidServices.log file: 6| Info|091407 11:56:52|Going to auto-apply property profile for device ContosoTestDevice|[Device] 6| Info|091407 11:56:52|Property [CUSTOM:CUSTOMINTEDITABLEPROPERTY] was not persisted, adding to auto-apply list|[Device] 6| Info|091407 11:56:52|Property [CUSTOM:CUSTOMSTRINGEDITABLEPROPERTY] was not persisted, adding to auto-apply list|[Device] 6| Info|091407 11:56:52|Property [REBOOT GROUP:REBOOT] was not persisted, adding to auto-apply list|[Device] 6| Info|091407 11:56:52|Successfully auto applied 3 non-persisted properties|[Device] ..... ..... 6| Info|091407 11:56:52|Going to auto-apply property profile for source Antenna1 of device ContosoTestDevice|[Device] Here's some background on how BizTalk RFID accomplishes this: every time there is a change in the value of one or more properties (for e.g. when you set a property or when you apply an entire property profile) BizTalk RFID creates a new version for the device in its version store to track the changes. After every successful connection to a device, it checks with the provider (using its device property metadata) if there are any properties that the provider is not persisting. If it finds such properties, it applies the values for these properties based on the latest values from its version store. Note that the same thing applies for the source/antenna properties as well... By default, this behavior is enabled and shouldn't be modified. If you really need to turn this behavior off, you can do that by setting RFID Manager -> Devices -> Connection Parameters -> "Auto-apply Non-Persistent Properties" to false. In this post, I will talk about the various states of a device added in BizTalk RFID. Before I jump into that, want to quickly mention that you can use the "Contoso Provider" and the "Contoso Device Simulator" that come with BizTalk RFID (as part of the SDK component) to simulate a device. You can run the device simulator by changing directory to %RFIDINSTALLDIR%\Samples\Device Service Provider\Contoso\ContosoEndToEnd\ContosoDeviceSimulator and then launching runContosoSimulator.cmd. This will launch a device at 127.0.0.1 at port 6666 and you can add this device to BizTalk RFID. Now, back to device states - the following is the overview of the various states (you can observe these using RFID Manager): 1) Open: BizTalk RFID Service (hereafter referred to as "the service") is connected to this device. This can happen in the following scenarios: a) You have one or more running "RFID processes" that are "bound" to this device. (and/or) b) You have a client application running that has opened a connection to this device. 2) Closed: The service is not currently connected to this device. Obviously, this means that there are no running processes or applications that are interested in this device. 3) Retrying: The service will retry connection to this device periodically as it couldn't connect successfully in an earlier attempt. This can happen in the following scenario: a) There are one or more running "RFID processes" that are "bound" to this device, (AND) b) The service couldn't connect to this device successfully in an earlier attempt. How frequently does the service re-attempt a connection to such a device? In RFID Manager, if you right click on the Devices node on the left, and select "Connection Parameters", you can see a "Connection Retry Interval" parameter. This defaults to one minute, and can be tweaked appropriately to suit your needs. How many times does the service re-attempt a connection to such a device before giving up? In the same "Connection Parameters" dialog, you can see a "Maximum retry attempts" parameter. This defaults to 10 attempts. Again, you can configure this parameter based on your environment. You would also notice a parameter called "Connection Check Time" in the same dialog. For connected devices that are associated with a RFID process, the service has a mechanism to automatically verify periodically if the connection is still alive. The "Connection Check Time" parameter dictates how frequently the service should verify the validity of such connections. If the device is not found to be alive, the service automatically re-attempts a connection to this device. Note: I say "for a device associated with a RFID process" specifically because this automatic connection checking is not supported for a device connected through only a client application. 4) Disabled - Failed: We talked about the maximum number of retry attempts above. What happens when the service gives up? It takes the device to the "Failed" state. In this case, it might require the manual intervention of an administrator to fix the connectivity issue (for e.g. fix the IP address or fix a network problem). In most cases, the device has to be enabled manually before it can be used again. I say most cases because there is also a way in which BizTalk RFID can automatically bring back to life such a device: if it receives a discovery event for the same device from the provider, it will automatically enable the device. For e.g. there could be a mobile device which has gone out of scope and when it re-enters the system, the discovery event acts as a nice mechanism for automatically re-enabling such a device. There is another scenario (probably less common compared to the above) where a device can get into the "Failed" state and that's when the provider corresponding to a device is "stopped" while a connection to the device is open. In such a case, the device is taken to the "failed" state. When the provider is started again, the service will automatically re-attempt a connection to the device if there is atleast one RFID process that is bound to this device. If there is no RFID process interested in the device, the device will transition to the "Closed" state. Note that in this case the manual action to transition the device out of the failed state is to just start the provider. 5) Disabled - UnConfigured: This is the default state of a newly discovered device. Enabling such a device typically involves providing the authentication information required to connect to this device (if any). An administrator has to manually enable such a device before it can be used. 6) Disabled - Name Conflict: This indicates that the "physical name" of a device is different from its "logical name" (the name with which it was added to BizTalk RFID). This can happen in the following scenario: a) The physical device supports the NAME property and it is a writable property (AND) b) When starting a RFID Process, the service finds that the physical name is not the same as the logical name. An administrator has to manually enable such a device before it can be used. An easy way to fix this would be to rename the device and provide a new name so that the service can apply the same name to the physical name as well. 7) Disabled - Manually Disabled: You can also manually disable a device to temporarily put it out of use; this can be useful for any troubleshooting/maintenance activities on the device. An administrator has to manually enable such a device before it can be used To manually enable a device from any of the above four disabled states, you can right-click on a device in the Devices node of RFID Manager, and click "Enable". So, how do you track such state changes? For e.g. how can you detect quickly when you lose connection to a device and it goes to Retrying state? BizTalk RFID raises various management events, for e.g. DeviceConnectionAttemptFailedEvent when the service is not able to connect to a device. These are WMI based events and you can have your own WMI consumer client to listen to this events or use the "RFID Tray" application to view these events, or better still use MOM to manage such events. I will detail out the various device related management events in a future post... In my earlier post, I gave an overview of the various approaches in which you can add/register a device with BizTalk RFID. Now that you have the device added, I am sure you can't wait to configure it and start putting it to use. So, how do you use BizTalk RFID to configure it as well as do certain operations on it? I will explain both the RFID manager part of it as well using the Object Model to do this programmatically, in that order. A. Configuration (using RFID Manager): This can involve setting properties on the device, for e.g. the Regulatory Region or the event mode. In RFID Manager, right-click on a device, and then select Properties. RFID Manager will first attempt connect to the device; if the device is online, it will retrieve the latest values for the properties from the device ("current property profile") and display the properties in the Properties Dialog. If RFID Manager is not able to connect to the device, it will display the last known version of the property values: in this case, you will notice that you will only be able to view the properties and not edit them. The device needs to be online to be able to edit the properties as well. What about the properties of a device's sources/antennae? You can view the important properties of the antennae in the Sources tab of the Device Properties dialog; to view the rest, you can go the Custom tab of this dialog and select a particular source to view its other properties. B. Operations (using RFID Manager): RFID Manager provides support for certain common operations on a device: one example is to view tags from a device. You can right-click on a device, and then select View Tags. You will be able to configure the refresh interval as well. There are other such device operations as well that are supported from RFID Manager. C. Configuration/Operations (Programmatic): Now, on to the programmatic part: most of the device configuration and operations can be represented as "Commands" in the BizTalk RFID Device Service Provider Interface (DSPI). For e.g. you have a GetCurrentPropertyProfileCommand to get the latest property profile from a device, or a SetPropertyCommand to set the value for a particular device property. Similarly, you have a "GetTagsCommand" or "PrintTagCommand" for various device operations. From the Object Model perspective, the execution of these commands are synchronous in nature. You need to open a connection to the device before you can execute a command on it. I will give you two approaches by which you can achieve this: 1. Using DeviceConnection (recommended): The DeviceConnection class is the recommended approach when you want to do programmatic configuration/operations on a device. for e.g. to get the current property profile, here's a rough idea of how you can use the DeviceConnection class (Note: exception handling not included in the below samples): [You will have to add a reference to Microsoft.Rfid.Client.dll] Overall, there are lot of other such methods in the DeviceConnection class for various configurations/operations on a device. The typical pattern for each operation/configuration method is that you will find a simpler overload for the most common usage, and you will find a more advanced usage if you want to specify more options (for e.g. if you want to perform the operation/configuration on a particular source of a device, there is an overload where you can specify the source name). You can use this class from a standalone application or from your own BizTalk RFID event handler that is part of a RFID business process. 2. Using DeviceManagerProxy: The DeviceManagerProxy provides support for: In this, you will have to build a "Command" object and execute it - for e.g. to build a SetPropertyCommand to modify the location property, There is a convenient download link to download the Help file, Tutorials etc. for BizTalk RFID. The BizTalkRFID.chm file is the comprehensive help file that you can use for API reference as well as for other deployment operations. Check it out at:. -Kalyan In this post, I will attempt to give an overview of the various methods in which you can add/register a device with BizTalk RFID. You can use "RFID Manager" (the MMC based management console which ships with BizTalk RFID) to check out most of these concepts. The following are the main ways in which a device can be registered with BizTalk RFID: 1. Device Discovery: If your device provider supports discovery, it can post a discovery message to BizTalk RFID. If BizTalk RFID determines that the discovery information corresponds to that of a new device, it will add this device to its list of devices and will set it to "Unconfigured" state. The newly added device will instantly appear in the Devices view in RFID Manager. The main thing to note here is that you need to "enable" the device before you can start using this device. Enabling such a device typically involves providing the authentication information required to connect to this device (if any). To do this, you can right-click on a device in the Devices node of RFID Manager, and click "Enable". You can also use the "Trigger Discovery" functionality to manually trigger the above discovery process. To do this, you can right-click on a provider in the Providers node of RFID Manager, and click "Trigger Now". 2. Adding a device manually: You can use the Add Device Wizard in RFID Manager to add a device. You need to specify the following: Add Device Wizard will try to connect to the device based on the connection information you specified and will retrieve certain properties such as name, location and description. You can optionally change these values and complete the device addition. If RFID Manager is not able to connect based on the specified connection information, you still have the option of adding the device ("offline" mode). Unlike a device added through discovery, a device added in this way is by default in the "enabled" and usable state. 3. Bulk Addition of devices: Very similar to 2) above, but here you have the option of adding more than one device at the same time. In Add Device Wizard in RFID Manager, you can select the "Add Multiple Devices" option and you can specify a range of addresses. RFID Manager will attempt to connect to devices in this range and you also have the option to specify that devices found in this fashion be added automatically. 4. Your own client application: You can write your own client application which uses the BizTalk RFID Object Model to add a device. You can use DeviceManagerProxy.AddDevice() and specify the above details and choose whether you want to add the device in online mode or offline mode. You need to add references to "Microsoft.Rfid.Design.dll", "Microsoft.Rfid.SpiSdk.dll", "Microsoft.Rfid.ManagementWebServiceProxies.dll". The following is the SAMPLE code for how this can be done (you need to have Contoso simulator running if you want to really see this in action): using namespace Isn't this cool :)? You can explore the full power of the Object Model using Visual Studio Intellisense or by looking at the BizTalk RFID developer reference at. That's it for now. If you have any specific topics that you would like to see, please do give me feedback and I will attempt to address it in future posts. BizTalk Server 2006 R2 final RTM version has been launched! This includes BizTalk RFID and I will be blogging more about the various features of RFID, particularly related to device management and RFID Manager. has more details. You can download an evaluation version from:
http://blogs.msdn.com/kalyanaj/
crawl-002
refinedweb
4,910
51.07
Created on 2016-01-15 19:48 by SimonFr, last changed 2016-01-18 16:53 by serhiy.storchaka. This issue is now closed. grp.getgrgid is capable of accepting a string: from grp import getgrgid print(getgrgid('0')) However, pwd.getpwuid can't do the same: from pwd import getpwuid print(getpwuid('0')) Traceback (most recent call last): File "getpwuid_test.py", line 2, in <module> print(getpwuid('0')) TypeError: an integer is required This seems to be because inside Modules/pwdmodule.c, getpwuid uses PyNumber_ParseTuple with a converter that uses PyNumber_Index to get a Python integer, and that raises an exception on failure. However, in Modules/grpmodule.c, grp_getgrgid uses PyNumber_Long (Or PyNumber_Int for an old enough Python) as a conversion first, and as the documentation says at, this is the equivalent of running int(o), which can convert a string to an integer. Only then is it given to PyNumber_Index, by way of a helper function _Py_Gid_Converter Should these have different behaviours? Is there a reason for the difference? The behaviour of getgrgid seems more helpful, and it's odd that it doesn't apply to both functions. Is this undesirable behaviour in getgrgid or getpwuid? I'm adding Larry since it was his implementation of _Py_Uid_Converter in issue15301 that seems to lead to this behaviour. Nope. Argument Clinic was merged in 3.4, and in 3.3 pwd.getpwuid wouldn't accept strings. So this isn't a bug introduced in the Clinic conversion in 3.4, this is historical behavior, and we can't change it now. If anything, I'd prefer that grp.getgrid *didn't* accept strings, but it's too late to change that too. "Helpfully" automatically calling int() on an argument is un-pythonic. (To answer your specific questions: they probably shouldn't have different behaviors, and I assume there's no particular reason for the difference. It's probably that they had different implementors, and one did a sloppier job than the other.) This looks as unintentional consequences of ab0221811771. I think the current behavior of grp.getgrgid() is not correct, because it accepts str, float and other types. Python is strong-typed language and shouldn't make unwanted implicit type conversions. I guess the purpose was to support long arguments in Python 2. There is similar problem with grp.getgrnam() in 2.7. It accepts arguments of any types and convert them to str by calling str(). I guess the purpose was to support unicode arguments. In 3.x only str is accepted. Proposed patch deprecates accepting non-integer arguments in grp.getgrgid(). May be we can just remove this without starting deprecating process. I don't know. A single deprecation cycle should be enough since it obviously shouldn't work with floats and strings might make sense but updating code to not use them is easy enough. New changeset 65e0e06b70b6 by Serhiy Storchaka in branch 'default': Issue #26129: Deprecated accepting non-integers in grp.getgrgid(). Thank you for your review Brett.
https://bugs.python.org/issue26129
CC-MAIN-2017-13
refinedweb
502
59.8
For some reason without the else statement the code finds the indexes of the characters in the string. However, when I add the else statement to declare if a character is not found. All it does is give me the else statement even if the character is in the string. #Function takes a character and a string and returns the index of the character #found in the string. def whereIsItS(letter, word): #Start finding the index of characters in the string starting at 0. letInWord = 0 #For loop to find specific characters in a string. for l in word: #If the letter is found it returns the index of the letter. if l == letter: #Moves to the next character in the string. letInWord += 1 else: return "It is not there." #Returns the index of the character found the string. return word.index(letter) return will always exit from a function and not continue any loops you are performing. You either This is relatively simple to achieve with the following: def whereIsItS(letter, word): if letter in word: return word.index(letter) else: return "Letter {0} not in word {1}".format(letter, word) If the letter is in the word, return its index, if not, return the message specifying it wasn't found. Further trimmed with a conditional expression to: def whereIsItS(letter, word): return word.index(letter) if letter in word else "Letter {0} not in word {1}".format(letter, word)
https://codedump.io/share/ntT8LnPvTjM9/1/if-else-statement-for-finding-the-index-of-a-character-in-a-string
CC-MAIN-2017-26
refinedweb
241
73.98
There will be two ports, one with the Studio9 compiler, and another with gcc 3.4.1 . Currently, only the former has patches ready, which I will attach. I'm not sure if this will make NSS 3.9.3, which we will probably cut in less than 10 days . I'd like to target 3.9.4, but there is no such milestone in bugzilla. Created attachment 158665 [details] [diff] [review] patch to compile with the Sun Studio9 compiler You need to set USE_64 to 1 to compile 64-bit with this patch. There is currently a problem with the SHA384 and SHA512 tests failing in all.sh, but everything else passes. Created attachment 159142 [details] [diff] [review] also allow gcc to build 64-bit when setting NS_USE_GCC to 1 Comment on attachment 159142 [details] [diff] [review] also allow gcc to build 64-bit when setting NS_USE_GCC to 1 Here are my unsolicited review comments. Hope you don't mind. 1. coreconf/SunOS5.10_i86pc.mk >+ifeq ($(USE_64),1) >+AMD64 = 1 >+OS_DEFINES += -D__x86_64__ >+else >+OS_DEFINES += -Di386 >+endif I encourage you to avoid introducing the new make variable AMD64. It is not necessary. I think __x86_64__ is implicitly defined by compilers. > include $(CORE_DEPTH)/coreconf/SunOS5.mk > > CPU_ARCH = x86 >+ifndef AMD64 > ARCHFLAG = >-OS_DEFINES += -Di386 >+endif Perhaps CPU_ARCH needs to be "x86-64" or "x86_64" if USE_64 equals 1? "ARCHFLAG = " probably should not be inside an ifdef. 2. coreconf/SunOS5.mk > ifeq ($(USE_64), 1) > ifdef NS_USE_GCC >- ARCHFLAG= UNKNOWN >+ ARCHFLAG= Are you sure about this change? > ifdef NS_USE_GCC > DSO_LDOPTS += -shared -h $(notdir $@) >+ifeq ($(USE_64), 1) >+ DSO_LDOPTS += -m64 >+ OS_CFLAGS += -m64 >+endif > else > ifeq ($(USE_64), 1) >+ifdef AMD64 >+ DSO_LDOPTS += -xarch=amd64 >+else > DSO_LDOPTS += -xarch=v9 > endif >+endif > DSO_LDOPTS += -G -h $(notdir $@) > endif I think "OS_CFLAGS += -m64" should be deleted. Instead, replace the "ARCHFLAG= UNKNOWN" above by "ARCHFLAG = -m64". For NS_USE_GCC, you should add the new code before "DSO_LDOPTS += -shared -h $(notdir $@) to be analogous to the non-gcc case. 1. __x86_64__ is not implicitly defined by the Sun studio compiler, only by gcc. Changing CPUARCH may be an option, but I think there are other parts of coreconf that check for i86pc . 2. The "UNKNOWN" was showing up in the OBJDIR . That's why I reset it. Note that previously, ARCHFLAG was cleared in SunOS5.10_i86pc.mk . I just moved that to SunOS5.mk . I'll try your suggestion. Created attachment 159672 [details] [diff] [review] updated patch. applies to tip Comment on attachment 159672 [details] [diff] [review] updated patch. applies to tip Actually this still has a few problems. Some of the many solaris builds (12 total!) are failing. One more coming. Created attachment 159676 [details] [diff] [review] updated patch for NSS tip Implements many suggestions from Wan-Teh's and Saul's review. Allows building on x86 and AMD64, either 32-bit or 64-bit, with gcc or Sun's Studio 9. Applies to the tip. Comment on attachment 159676 [details] [diff] [review] updated patch for NSS tip I can't seem to attach the proper patch. Long day. Created attachment 159683 [details] [diff] [review] patch for NSS tip Created attachment 159685 [details] [diff] [review] patch for NSS_3_9_BRANCH FYI, the Sun Studio9 compiler defines __x86_64 and __amd64, but not __x86_64__ . Then I think our C code should test for __x86_64 instead of __x86_64__. Now I remember this same difference between gcc and Sun compiler for SPARC. In any case, I think defining -D__x86_64__ for the Sun Studio9 compiler is fine. Comment on attachment 159685 [details] [diff] [review] patch for NSS_3_9_BRANCH 1. coreconf/SunOS5.10_i86pc.mk >+ifeq ($(USE_64),1) >+CPU_ARCH = amd64 >+OS_DEFINES += -D__x86_64__ >+else > CPU_ARCH = x86 >-ARCHFLAG = > OS_DEFINES += -Di386 >+endif "x86-64" or "x86_64" might be a better value for CPU_ARCH than "amd64" because Intel has a compatible architecture called EM64T. You may want to indent the code inside ifeq and else. Do we need to have -Di386 for the USE_64 case? (See my question/comment about this in the NSPR Solaris/AMD64 bug.) 2. coreconf/SunOS5.mk >+# default to Sparc architecture >+ifeq ($(CPU_ARCH),) >+CPU_ARCH = sparc >+endif This change requires modifying all the older SunOS5.*_i86pc.mk to set CPU_ARCH to x86 before including SunOS5.mk. This can be avoided if in this file you use $(OS_TEST) instead of $(CPU_ARCH) to determine the CPU type. > ifeq ($(USE_64), 1) > ifdef NS_USE_GCC >- ARCHFLAG= UNKNOWN >+ ARCHFLAG= -m64 Does -m64 work for both AMD64 and 64-bit SPARC? > else >- ARCHFLAG=-xarch=v9 >+ ifeq ($(CPU_ARCH),amd64) >+ ARCHFLAG=-xarch=amd64 >+ else >+ ARCHFLAG=-xarch=v9 >+ endif > endif Instead of comparing $(CPU_ARCH) with amd64, it may be better to compare $(OS_TEST) with i86pc to be consistent with NSPR. Also may want to indent inside ifeq and else. > else >- ifdef NS_USE_GCC >- ifdef USE_HYBRID >- ARCHFLAG=-mcpu=v9 -Wa,-xarch=v8plus >+ ifeq ($(CPU_ARCH),sparc) >+ ifdef NS_USE_GCC >+ ifdef USE_HYBRID >+ ARCHFLAG=-mcpu=v9 -Wa,-xarch=v8plus >+ else >+ ARCHFLAG=-mcpu=v8 >+ endif > else >- ARCHFLAG=-mcpu=v8 >- endif >- else >- ifdef USE_HYBRID >- ARCHFLAG=-xarch=v8plus >- else >- ARCHFLAG=-xarch=v8 >+ ifdef USE_HYBRID >+ ARCHFLAG=-xarch=v8plus >+ else >+ ARCHFLAG=-xarch=v8 >+ endif > endif > endif > endif Does this change (adding ifeq ($(CPU_ARCH),sparc) around the whole block of code) mean we were compiling with -xarch=v8 on Solaris x86?! Thanks for the review, Wan-Teh. 1. I wanted to have a CPU_ARCH that was different. amd64 seems innocuous enough, IMO, even if Intel has a compatible instruction set. I don't think we need -Di386 for the USE_64, nor do we want to. This can actually tell some parts of the code to optimize structures for 32 bits integers, which is undesirable. Sun studio does not define this macro in 64-bit mode, but unfortunately gcc does. 2. If I use OS_TEST instead of OS_ARCH, then I also have to check USE_64 . But it's OK since it means not having to modify config files for each new version of solaris. gcc -m64 works for both AMD64 and 64-bit Sparc indeed . However, on Sparc, the gcc build fails for other reasons not related to the patch, even in 32 bit mode. Actually the NSPR build fails with gcc on Sparc as it seems to be using the Sun compiler syntax. The NSS build may be OK, but I didn't get that far. As far as the test on CPU_ARCH for sparc, yes, I have seen cases when we were compiling with -xarch=v8 on Solaris x86, although that only generated a warning, as the Sun compiler is not a cross-compiler. Those cases may only have occurred when I had the patch in progress, and not with what was checked in before; but regardless, I don't think this change hurts anything. Created attachment 161337 [details] [diff] [review] updated patch for tip 1. use CPU_ARCH = x86_64 instead of AMD64 2. Don't define __x86_64__ 3. Don't define i386 for 64 bit casse 4. Don't define CPU_ARCH to Sparc by default 5. Use OS_TEST = i86pc and USE_64 to test for x86 64 6. remove tabs Created attachment 161346 [details] [diff] [review] updated patch for NSS_3_9_BRANCH same changes as for the tip Comment on attachment 161337 [details] [diff] [review] updated patch for tip r=wtc. There are some white space problems in your changes. You should try to follow the indentation styles in those makefiles, including the use of tabs. coreconf uses tabs more than our C files do. We should avoid a mixture of indentation styles in coreconf. Comment on attachment 161346 [details] [diff] [review] updated patch for NSS_3_9_BRANCH r=wtc. Same comments about the use of white spaces. Please follow the prevalent indentation style and use of tabs in coreconf makefiles. I fixed the indenting. Checked in to NSS_3_9_BRANCH : Checking in coreconf/SunOS5.10_i86pc.mk; /cvsroot/mozilla/security/coreconf/SunOS5.10_i86pc.mk,v <-- SunOS5.10_i86pc.mk new revision: 1.1.82.1; previous revision: 1.1 done Checking in coreconf/SunOS5.mk; /cvsroot/mozilla/security/coreconf/SunOS5.mk,v <-- SunOS5.mk new revision: 1.13.16.1; previous revision: 1.13 done Checking in nss/lib/freebl/Makefile; /cvsroot/mozilla/security/nss/lib/freebl/Makefile,v <-- Makefile new revision: 1.53.14.4; previous revision: 1.53.14.3 done And to the tip : Checking in coreconf/SunOS5.10_i86pc.mk; /cvsroot/mozilla/security/coreconf/SunOS5.10_i86pc.mk,v <-- SunOS5.10_i86pc.mk new revision: 1.3; previous revision: 1.2 done Checking in coreconf/SunOS5.mk; /cvsroot/mozilla/security/coreconf/SunOS5.mk,v <-- SunOS5.mk new revision: 1.16; previous revision: 1.15 done Checking in nss/lib/freebl/Makefile; /cvsroot/mozilla/security/nss/lib/freebl/Makefile,v <-- Makefile new revision: 1.58; previous revision: 1.57 done
https://bugzilla.mozilla.org/show_bug.cgi?id=259003
CC-MAIN-2017-17
refinedweb
1,425
66.84
On Wed, May 9, 2012 at 4:48 PM, <martin at v.loewis.de> wrote: >>> I'm not sure why we *need* a list of portions, but if we do, simple >>> return values seem like the way to go. But the 2-element tuple wins >>> even in the single path portion case, and the tuple-return protoocol is >>> extensible if we need more data returned in future anyway. >> >> >> Nick laid out a use case in a previous email. It makes sense to me. For >> example, a zip file could contain multiple portions from the same >> namespace package. You'd need a new path hook or mods to zipimport, but >> it's conceivable. > > > I must have missed Nick's message where he explained it, so I still need > to ask again: how exactly would such a zip file be structured? > > I fail to see the need to ever report both a loader and a portion, > as well as the need to report multiple portions, for a single sys.path > item. That sounds like an unnecessary complication. My actual objection is the same as Antoine's: that needing to introspect the result of find_loader() to handle the PEP 420 use case is a code smell that suggests the API design is flawed. The problem I had with it was that find_loader() needs to report on 3 different scenarios: 1. I am providing a loader to fully load this module, stop scanning the path hooks 2. I am contributing to a potential namespace package, keep scanning the path hooks 3. I have nothing to provide for that name, keep scanning the path hooks. Using the type of the return value (or whether or not it has a "load_module" attribute) to decide between scenario 1 and 2 just feels wrong. My proposed alternative was to treat the "portion_found" event as a callback rather than as something to be handled via the return value. Then loaders would be free to report as many portions as they wished, with the final "continue scanning or not" decision handled via the existing "loader or None" semantics. The example I happened to use to illustrate the difference was one where a loader actually internally implements its *own* path scan of multiple locations. I wasn't specifically thinking of zipfiles, but you could certainly use it that way. The core concept was that a single entry on the main path would be handed off to a finder that actually knew about *multiple* code locations, and hence may want to report multiple path portions. The 3 scenarios above would then correspond to: 1. Loader was returned (doesn't matter if callback was invoked) 2. None was returned, callback was invoked one or more times 2. None was returned, callback was never invoked Eric's counter-proposal is to handle the 3 scenarios as: 1. (<loader>, <don't care>) 2. (None, [<path entries>]) 3. (None, []) Yet another option would be to pass a namespace_path list object directly into the find_loader() call, instead of passing namespace_path.append as a callback. Then the loader would append any portions it finds directly to the list, with the return value again left as the simple choice between a loader or None. One final option would be add an optional "extend_namespace" method to *loader* objects. Then the logic would become, instead of type introspection, more like the following: loader = find_loader(fullpath) try: extend_namespace = loader.extend_namespace except AttributeError: pass else: if extend_namespace(namespace_path): # The loader contributed to the namespace package rather than loading the full module continue if loader is not None: return loader It's definitely the switch-statement feel of the proposed type checks that rubs me the wrong way, though. Supporting multiple portions from a single loader was just the most straightforward example I could think of a limitation imposed by that mechanism. Regards, Nick. -- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
https://mail.python.org/pipermail/import-sig/2012-May/000594.html
CC-MAIN-2016-40
refinedweb
648
62.27
CodePlexProject Hosting for Open Source Software Hi, I want to build an universal message wrapper class and serialize it to Json. This class contains a collection of headers and the message body, which can be any type. I want to serialize it to plain Json, so I'm using TypeNameHandling = TypeNameHandling.Objects in serializer settings, so type names get serialized along with the data. Here's my class and json it produces: public class MessageWrapper2 { public MessageWrapper2() { Headers = new Hashtable(); } public Hashtable Headers { get; set; } public object Body { get; set; } } JSON: {"$type":"Tests.MessageWrapper2, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Headers":{"$type":"System.Collections.Hashtable, mscorlib, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089","DeliverAt":"yesterday!"}, "Body":{"$type":"Tests.TestMessage1, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Id":893239} } I'd like to have "$type" field only in the contents of Body property, there's no need to have $type for the MessageWrapper2 class and Headers property because it only makes the message bigger. Ideally, the json should look like { "Headers":{"DeliverAt":"yesterday!"}, "Body":{"$type":"Tests.TestMessage1, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Id":893239} } Can you please help me how to customize the serializer or my MessageWrapper2 class to serialize & deserialize json in such way? Many thanks RG I have added TypeNameHandling to the JsonProperty attribute. Thanks, that's great. I'll give it a try asap. 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.
https://json.codeplex.com/discussions/207905
CC-MAIN-2017-13
refinedweb
276
51.65
Solving problem is about exposing yourself to as many situations as possible like What does the Ellipsis object do? does the Ellipsis object do?, which can be followed any time. Take easy to follow this discuss. While idly surfing the namespace I noticed an odd looking object called Ellipsis, it does not seem to be or do anything special, but it’s a globally available builtin. After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy… but almost nothing else. Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all? D:workspacenumpy>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Ellipsis Ellipsis Answer #1: This came up in another question recently. I’ll elaborate on my answer from there: Ellipsis is an object that can appear in slice notation. For example: myList[1:2, ..., 0] Its interpretation is purely up to whatever implements the __getitem__ function and sees Ellipsis objects there, but its main (and intended) use is in the numpy third-party library, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4×4 array, the top left area would be defined by the slice [:2,:2]: 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]) a[:2,:2] # top left array([[1, 2], [5, 6]])a array([[ Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for all the dimensions in the gap it is placed, so for a 3d array, a[...,0] is the same as a[:,:,0] and for 4d, a[:,:,:,0], similarly, a[0,...,0] is a[0,:,:,0] (with however many colons in the middle make up the full number of dimensions in the array). Interestingly, in python3, the Ellipsis literal ( ...) is usable outside the slice syntax, so you can actually write: Ellipsis... Other than the various numeric types, no, I don’t think it’s used. As far as I’m aware, it was added purely for numpy use and has no core support other than providing the object and corresponding syntax. The object being there didn’t require this, but the literal “…” support for slices did. Answer #2: In Python 3, you can¹ use the Ellipsis literal ... as a “nop” placeholder for code that hasn’t been written yet: def will_do_something(): ... This is not magic; any expression can be used instead of ..., e.g.: def will_do_something(): 1 (Can’t use the word “sanctioned”, but I can say that this use was not outrightly rejected by Guido.) ¹ 'can' not in {'must', 'should'} Answer #3: As of Python 3.5 and PEP484, the literal ellipsis is used to denote certain types to a static type checker when using the typing module. Example 1: Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example Tuple[int, ...] Example 2: It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis (three dots) for the list of arguments: def partial(func: Callable[..., str], *args) -> Callable[..., str]: # Body Answer #4: You can also use the Ellipsis when specifying expected doctest output: class MyClass(object): """Example of a doctest Ellipsis >>> thing = MyClass() >>> # Match <class '__main__.MyClass'> and <class '%(module).MyClass'> >>> type(thing) # doctest:+ELLIPSIS <class '....MyClass'> """ pass Answer #5: Summing up what others have said, as of Python 3, Ellipsis is essentially another singleton constant similar to None, but without a particular intended use. Existing uses include: - In slice syntax to represent the full slice in remaining dimensions - In type hinting to indicate only part of a type( Callable[..., int]or Tuple[str, ...]) - In type stub files to indicate there is a default value without specifying it Possible uses could include: - As a default value for places where Noneis a valid option - As the content for a function you haven’t implemented yet Answer #6: From the Python documentation: This object is commonly used by slicing (see Slicings). It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)()produces the Ellipsis singleton. It is written as Ellipsisor .... Answer #7: __getitem__ minimal ... example in a custom class When the magic syntax ... gets passed to [] in a custom class, __getitem__() receives a Ellipsis class object. The class can then do whatever it wants with this Singleton object. Example: class C(object): def __getitem__(self, k): return k # Single argument is passed directly. assert C()[0] == 0 # Multiple indices generate a tuple. assert C()[0, 1] == (0, 1) # Slice notation generates a slice object. assert C()[1:2:3] == slice(1, 2, 3) # Ellipsis notation generates the Ellipsis class object. # Ellipsis is a singleton, so we can compare with `is`. assert C()[...] is Ellipsis # Everything mixed up. assert C()[1, 2:3:4, ..., 6] == (1, slice(2,3,4), Ellipsis, 6) The Python built-in list class chooses to give it the semantic of a range, and any sane usage of it should too of course. Personally, I’d just stay away from it in my APIs, and create a separate, more explicit method instead. Tested in Python 3.5.2 and 2.7.12. Answer #8: You can use Ellipsis yourself, in custom slicing situations like numpy has done, but it has no usage in any builtin class. I don’t know if it was added specifically for use in numpy, but I certainly haven’t seen it used elsewhere. See also: How do you use the ellipsis slicing syntax in Python?
https://discuss.dizzycoding.com/what-does-the-ellipsis-object-do/
CC-MAIN-2022-33
refinedweb
1,007
64.61
Hello, I'm getting an odd error on some very simple code. I have an swf that contain a movieclip with the Linkage name 'Box'. The movieclip has an animation of 30 frames, yet Flash Builder keeps erroring saying it's not a movieclip! public class Main extends Sprite { [Embed(source="../assets/box.swf", symbol="Box")] public static const A_Box:Class; public function Main() { var box:MovieClip = new A_Box(); } } #1034: Type Coercion failed: cannot convert box_swf$161b93e3bc30cfa0cb18e1d734943c6f-1063626660@53720a1 to flash.display.MovieClip. If I try to bring it in as a Sprite, it works just fine (var box:Sprite = new A_Box();), however then it does not animate, as it's being treated as a sprite. I've looked at around 20 online examples, the code is very simple and I can't seem to find anything wrong with my code. I've also double checked 300 times and the Movieclip is set up properly inside the Swf. (Linkage name, multiple frames, export for actionscript frame 1, etc) So... Why does only Sprite work and MovieClip doesn't? Am I doing something wrong or is this maybe a FlashBuilder/Air13.0 problem? Thanks! I opened my Project again today to find out that it suddenly works perfectly... Something must have been cached because I struggled with it for 6 hours yesterday, and now without changing anything it work right off the bat. I find there's so many caching issues like this in FB. Sometimes any changes I make are not reflected in the project at all (including deleting main classes) until I completely restart FB. Really wish Adobe would get their act together and release a patch to fix some of the any bugs.
https://forums.adobe.com/thread/1442309
CC-MAIN-2017-51
refinedweb
285
71.75
Doubt about Spec Section 5.2.4. Assignability of raw and parameterized types - On injection point without diamond operatorNuno Godinho de Matos Dec 17, 2016 9:18 AM Hi, I have doubt about the following spec section: I am trying to understand what paragraph in the spec explains the reason why a parameterized bean would not be injectable into a raw type delcared injection point. From what I understand in CDI 1.0 weld se core final, there was an implementation bug that has since been fixed, whereby the following type of injection would work: @ Inject Instance<Dao> allDaos; Now Dao, is a paremeterized interface. And in CDI 1.1 weld 2.3.2 final, the code to be made to work would need to fix the injection point to read as follows: Instance<Dao<?>> allDaos; So, one would jave to declare that he wants to inject a Dao where the type parameter is unbounded / wild carded. Of course, the Dao class could be for example a public interface Dao<T>{ } The problem of course, is that as I try to upgrade, I am encountering some runtime blowups where essentially instances that used to be made accessible from injection points that were not using the diamon wild card fail. This is fine, I will fix those ... I do need to spot them all... but life is like that. Mistakes have a price. But in any case, i would like to see in the spec document the phrase that states that a class. public class UserDao implements Dao<User>{ } Is not assignable to the injection point Instance<Dao>. I suspect the phrase is htis one: "A parameterized bean type is considered assignable to a raw required type if the raw types are identical and all type parameters of the bean type are either unbounded type variables or java.lang.Object." In this case: A A parameterized bean type UserDao is considered assignbale to a raw requred type @ Inject Instance<Dao> allDaos; if the raw types "Dao" and all type parameters of the bean type "User" either unbounded type (it is not the case right it is bounded to "User") or "java.lang.Object". But I am not sure 100% that my interepretaiton is corect. If it is, this means that to the old injection point only a class of the form: UnAssigninedDao <T> extends Dao<T>{ } Or a class ObjectDao extends Dao<Object>{ } would be legal candaidates to the injection point above? Thanks for the clarification, this is discovery is an unfortunate setback... that is blowing up in my face in runtime testing. 1. Re: Doubt about Spec Section 5.2.4. Assignability of raw and parameterized types - On injection point without diamond operatorMartin Kouba Dec 19, 2016 4:05 AM (in response to Nuno Godinho de Matos)1 of 1 people found this helpful Hi Nuno, you're right, this is covered in the first paragraph of 5.2.4. Assignability of raw and parameterized types. This sentence is there since CDI 1.0 and it follows the rules for Java generics. @Inject Instance<Dao> allDaosis de facto @Inject Instance<Dao<Object>> allDaosand you can't assign Dao<Integer>to Dao<Object>. Imagine that there is a Dao.save(T instance)method. If it was permitted to inject Dao<Integer>bean into Dao<Object>, the client code would be able to Dao.save("stringInsteadOfInteger")which is obviously wrong. 2. Re: Doubt about Spec Section 5.2.4. Assignability of raw and parameterized types - On injection point without diamond operatorNuno Godinho de Matos Dec 19, 2016 6:21 AM (in response to Martin Kouba) Hi Martin, thank you very much for the clarification. It helped.
https://developer.jboss.org/thread/273400
CC-MAIN-2018-17
refinedweb
614
61.87
How to use precompiled headers in CMake project in QtCreator? - Alexander Trots last edited by Alexander Trots Hello I trying to use a precompiled header in CMake project. Cotire module provides this functionality. But QtCreator code highlight not working. It seems that QtCreator code model doesn't parse a precompiled header. Here is a project example: CMakeLists.txt include(cotire) cmake_minimum_required(VERSION 2.8) project(temp_cmake_precompiled) add_executable(${PROJECT_NAME} "main.cpp") set_target_properties(${PROJECT_NAME} PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "Stable.h") cotire(${PROJECT_NAME}) main.cpp int main() { std::vector<int> vec; std::cout << vec.size() << std::endl; return 0; } Stable.h #include <iostream> #include <vector> Both Clang and built-in code model have this problem. But build performs with success. In dialog Tools -> C++ -> Inspect C++ Code Model... a Precompiled headers key is set to <None>. May be there is a different way to specify a precompiled header in CMake project that QtCreator can resolve? QtCreator 4.8.2 I ran into the same problem and this problem is very very annoying during daily work. I filed a bug report for that issue.
https://forum.qt.io/topic/100918/how-to-use-precompiled-headers-in-cmake-project-in-qtcreator/2
CC-MAIN-2019-39
refinedweb
178
54.59
Description of the files: ext-all.js, ext-debug.js, ext-all-debug.js, ext-dev, ... Description of the files: ext-all.js, ext-debug.js, ext-all-debug.js, ext-dev, ... Sorry! bump! I am wondering about the same thing myself. - Join Date - Jan 2009 - Location - Palo Alto, California - 1,939 - Vote Rating - 9 We're simplifying all of this in 4.1 as it's clearly somewhat confusing at the moment. Here's what they do in 4.0: ext-all: minified, no JSDoc, no console warnings ext-all-debug: non-minified, with JSDoc, no console warnings ext-all-dev: non-minified, with JSDoc, with console warnings ext-all and ext-all-debug are functionally equivalent, whereas ext-all-dev throws console warnings when you do things like use deprecated APIs or misconfigure components. I don't believe we have ported the debug console from 3.x across yetExt JS Senior Software Architect Personal Blog: Twitter: Github: I think there's a bug in ext-dev.js: When i switch from ext-debug.js to ext-dev.js, the path of 'Ext' namespace is lost. This is because extjs path is extracted by searching for included script with the following name: /ext(-debug)?\.js$/ And obviously this is not the case for ext-dev.js. A woirkaround is to specify manually ExtJS path, but i think that ext-debug and ext-dev should be seamlessly interchangeable.. @EdSpencer: should i post this in bug forume thread? You need to set path for Ext when you use ext-dev.js . I think you should always use ext-dev.js instead of ext-debug.js when you intend to use dynamic class loading feature during your development phase.Thanks and regards, Yiyu Jia ext-all-dev does not output deprecated usage to the console ext-all-dev does not output deprecated usage to the console Not completely true. As a test, I decided to use Ext.sum() and Ext.type() which is deprecated in 4.0.6. There are no messages in the console at all when using ext-all-dev.js.. ExtJS 4.1 GA has been released, but seems that it has become worse, now there are much more files than before.. the files are: ext-all-debug-w-comments.js ext-all-debug.js ext-all-dev.js ext-all.js ext-debug-w-comments.js ext-debug.js ext-dev.js ext-neptune-debug-w-comments.js ext-neptune-debug.js ext-neptune.js ext.js during development i use: ext-dev.js and during production i use (i include the whole extjs lib): ext-all.js Is this still correct in 4.1? What is the "proper" way in 4.1? I also had the same doubts, and i've come up with the following: Production: ext-all.js Development: ext-all-dev.js (It's really useful to use Ext.log function for debugging)
http://www.sencha.com/forum/showthread.php?142565-Description-of-the-files-ext-all.js-ext-debug.js-ext-all-debug.js-ext-dev-...&p=744017&viewfull=1
CC-MAIN-2014-52
refinedweb
489
60.61
GNU 2017-09-15 NAME strptime - convert a string representation of time to a time tm structure SYNOPSIS #define _XOPEN_SOURCE /* See feature_test_macros(7) */ #include <time.h> #include <time.h> char *strptime(const char *s, const char *format, struct tm *tm); DESCRIPTION The strptime() function is the converse of strftime(3); it converts the character string pointed to by s to values which are stored in the "broken-down time" structure pointed to by tm, using the format specified by format. The broken-down time structure tm format argument white space the name of a day of the week or a month name) is to be matched, the comparison is case insensitive. In case a number is to be matched, leading zeros are permitted but not required. RETURN VALUE The null byte at the end of the string. If strptime() fails to match all of the format string and therefore an error occurred, the function returns NULL. ATTRIBUTES For an explanation of the terms used in this section, see attributes(7). CONFORMING TO POSIX.1-2001, POSIX.1-2008, SUSv2. NOTES In principle, this function does not initialize tm but stores only. The \(aqy\(aq (year in century) specification is taken to specify a year in the range 1950-2049 by glibc 2.0. It is taken to be a year in 1969-2068 since glibc 2.1. Glibc notes For reasons of symmetry, glibc tries to support for strptime() the same format characters as for strftime(3). (In most cases, the corresponding fields are parsed, but no field in tm is changed.) This leads to); } strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm); strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm); puts(buf); exit(EXIT_SUCCESS); }
https://reposcope.com/man/en/3/strptime
CC-MAIN-2022-21
refinedweb
293
62.38
IE 9 support for Richfaces 3.x branchgonzalad Oct 20, 2010 12:51 PM Hello, Does Richfaces team plan to support IE 9 browser with Richfaces 3.x branch (releasing a 3.3.4 release if needed for IE 9 support) ? Or do you plan to support IE 9 only with Richfaces 4 ? We are running some applications in production and need to know if we need to migrate to RF 4 to provide IE 9 support. The better for us would be of course to have a smooth evolution : for instance use a RF 3.3.4 (or continue with RF 3.3.3 if it's fine with IE 9) once IE 9 is final - just drop the new jar and everything is fine - , and afterwards migrate our applications with Java EE 6, Seam 3, RF 4, etc... (which will be quite a bit more work ). Thanks for your answer ! 1. Re: IE 9 support for Richfaces 3.x branchKriya Studio Oct 20, 2010 1:38 PM (in response to gonzalad) First you have to ask the million dollar question.. will Richfaces ever work... 2. Re: IE 9 support for Richfaces 3.x branchIlya Shaikovsky Oct 25, 2010 5:36 AM (in response to gonzalad) Hi, unfortunatelly yes, we are completelly concentrated at JSF 2 RF 4 branch currently. And we have no releases planned at all for 3.3.x community branch(only for WFK product). But it's open for community patches to provide fixes needed by you in 3.3.4-snapshot. I do not think there will be much problems. And if somebody will report that for example some simple styling should be corrected or some simple js check's to be added and will submit patch to jira - it's likelly to appears in that branch. As about current problems - even if the 3.3.x branch was active now - we normally do not checking RF at not-stable environments. We have too wide set of stable browsers to check all the beta's available First you have to ask the million dollar question.. will Richfaces ever work... Hm.. want to hear more about specific problems. 3. Re: IE 9 support for Richfaces 3.x branchJay Balunas Oct 25, 2010 9:44 AM (in response to Kriya Studio) Not exactly a productive, or helpful answer. I would have hoped for more.... 4. Re: IE 9 support for Richfaces 3.x branchshiyou shao Oct 25, 2010 10:36 AM (in response to Ilya Shaikovsky) yes,JSF 2 RF 4 branch. 5. Re: IE 9 support for Richfaces 3.x branchgonzalad Oct 25, 2010 3:12 PM (in response to Ilya Shaikovsky) Thanks for the answer, we'll wait IE 9 final release and hope we'll not find too much issues then. Thanks once more Ilya ! 6. Re: IE 9 support for Richfaces 3.x branchBrett Williamson Jan 2, 2012 8:13 PM (in response to gonzalad). 7. Re: IE 9 support for Richfaces 3.x branchSilvia Peifer Apr 27, 2012 2:43 AM (in response to Brett Williamson) We have the same problems...any solution available? 8. Re: IE 9 support for Richfaces 3.x branchAdrien Adrien May 19, 2012 10:09 AM (in response to gonzalad) In same case, have you found a good workaround? It's critical, when i look in google analytics IE represent 38.18% of internet and 60% of ie use ie9!!! Millions people !! Impossible to say to users:" no no" not use ie, use chrome or firefox because actually we are in a course for a migration because our library has 1 year and is no more supported.... I think a good workaround (Servlet filter don't work it s impossible to add meta just after <head>) or anything else is welcome and urgent. Please show us Richfaces is the better choice in jsf library. Thanks Adrien 9. Re: IE 9 support for Richfaces 3.x branchgonzalad May 19, 2012 12:30 PM (in response to Adrien Adrien) Hi Adrien, We're using RF 3.3.3.Final, it works fine in IE9 when setting IE8 compatibility mode. You just have to set the necessary HTTP Headers (see). I'm not at work, but it should be something like X-UA-Compatible: IE=EmulateIE8. You can use a servlet filter for this or just modify your apache configuration (we use the first approach, but IMO the second is better since you don't have to modify your webapp). 10. Re: IE 9 support for Richfaces 3.x branchAdrien Adrien May 19, 2012 4:04 PM (in response to gonzalad) Hi Gonzalad, Thanks for the link, very interesting. If you use a Servlet filter how do you do to put the meta just after <head> and before the meta of Richfaces? ServletFilter: ---------------- ->For ServletFilter i've try to do it (with PhaseListener also) , but the meta X-UA-Compatible is always inserted after the meta of richfaces , so it have to be the first meta after <head> In the forum Niraj Adhikary has same problem : (etc...many other post) ->On internet i found many people who have this problem and the only workaround they found to put meta X-UA.. just after <head> is to use servlet filter and set loadScript/StyleStrategie at NONE and add explicitly the metas for richfaces in each page, I've try, it s 'functionnaly' ok but after the problem are skins and rich:page (semantic laouyt) .... APACHE ------------- ->I think it is only for who use mod_jk.....(snif) Thanks for response Adrien 11. Re: IE 9 support for Richfaces 3.x branchgonzalad May 19, 2012 7:41 PM (in response to Adrien Adrien) You just need to set HTTP header. Try something like this (don't know if this compiles), it should work : public class IECompatibilityFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { ((HttpServletResponse) response).setHeader("X-UA-Compatible", "IE=EmulateIE8"); chain.doFilter(request, response); } } Hope this helps 12. Re: IE 9 support for Richfaces 3.x branchAdrien Adrien May 20, 2012 1:14 AM (in response to gonzalad) Hi Gonzalad Thanks for your response. This is exactly the filter I used, but if you look in the console of IE9 n this warning is write :"HTML1115: X-UA-Compatible META tag ('IE=EmulateIE8') ignored because document mode is already finalized." So what is the trick to put the meta before richfaces metas? Adrien 13. Re: IE 9 support for Richfaces 3.x branchgonzalad May 22, 2012 4:04 AM (in response to Adrien Adrien) Hi Adrien, sorry for the late reply. Couldn't get my hands on a desktop with IE 9 ;( However, you shouldn't have to set <meta> in your JSF page (setting HTTP Header with the filter should be enough). The error : "HTML1115: X-UA-Compatible META tag ('IE=EmulateIE8') ignored because document mode is already finalized." is explained here : It appears because your X-UA-Compatible meta directive is not the first meta directive. Once more, don't use the meta directive - just set the HTTP Header. 14. Re: IE 9 support for Richfaces 3.x branch胜强 张 Jun 9, 2012 1:28 AM (in response to gonzalad) Thank you very much! You just described the point exactly and solved my problem.
https://community.jboss.org/message/568220
CC-MAIN-2015-40
refinedweb
1,218
73.98