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 |
|---|---|---|---|---|---|
In this tutorial, you will learn how to exit a For loop in C#. You can break a For loop using the
break; statement.
Breaking a For Loop
By now, you understand the syntax of a For loop in C#.
for (int i = 0; i < length; i++) { }
This loop will run as long as long as the conditions in the conditions section (
i < length) are true. Suppose, however, that you want your loop to run 10 times, unless some other conditions are met before the looping finishes.
If you want to break out of your loop early, you are in luck. The
break; statement in C# can be used to break out of a loop at any point.
using System; namespace ForLoop { class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Console.WriteLine(i); if (i == 7) { Console.WriteLine("We found a match!"); break; } } Console.ReadLine(); } } }
In this example, we have added an
[if](/csharp/beginners/csharp-if-else-if-conditional-statements/) statement inside our loop (Line 12) to check for a specific condition. If that condition is met, the program will execute the code inside the code block on Lines 13-16. Line 15 is part of that code block and contains the
break; statement. Once this statement is executed, the program will break out of the
for loop and jump to Line 18.
With the simple
break; statement, you can exit your loop before it is scheduled to end and continue with the next line of code after the loop code block.
The Bottom Line
In this tutorial, you learned how to break out of a
for loop. This is useful when using a loop for data manipulation or for finding matching items. If you have any questions, | https://wellsb.com/csharp/beginners/exit-for-loop-csharp/ | CC-MAIN-2022-21 | refinedweb | 295 | 72.56 |
Attachment.
Printable View
Attachment.
Please post the code and explain what is not working.Please post the code and explain what is not working.Quote:
why it isn't working
Be sure to wrap the code in code tags: [code=java]<YOUR CODE HERE>[/code] to get highlighting
Post the full text of any error messages you get
The program compiles fine, I have gotten this far. It's just the fact that the lines on my grid run past where they should.The program compiles fine, I have gotten this far. It's just the fact that the lines on my grid run past where they should.Code java:
package program2; import javax.swing.JFrame; import java.awt.*; import javax.swing.JOptionPane; public class Program2 extends JFrame { private static final int FRAME_SIZE = 500; private static final int MAX_NUM = 40; private static final int MIN_NUM = 10; private static int lineNumber; public static void main(String[] args) { Program2 guiWindow = new Program2 (); //Set Frame Size guiWindow.setSize(FRAME_SIZE, FRAME_SIZE); guiWindow.setDefaultCloseOperation(EXIT_ON_CLOSE); String valueString; //Create input error trap to ask for Number of lines in the Grid do{ valueString = JOptionPane.showInputDialog("Enter the Number of Lines in the Grid (10-40)"); guiWindow.lineNumber = Integer.parseInt(valueString); } while(lineNumber < MIN_NUM || lineNumber > MAX_NUM); //Sets window to Visible guiWindow.setVisible(true); } @Override public void paint(Graphics g) { super.paint(g); Graphics canvas = getContentPane().getGraphics(); //Gather width,height information int width = this.getContentPane().getWidth(); int height = this.getContentPane().getHeight(); //Declare my Variables double leftGrid = width * .1; int leftOfGrid = (int)leftGrid; double rightGrid = width * .9; int rightOfGrid = (int) rightGrid; double topGrid = height * .1; int topOfGrid = (int)topGrid; double bottomGrid = height * .9; int bottomOfGrid = (int) bottomGrid; int numberOfGaps = lineNumber - 1; double sVertical = (height * .8) / numberOfGaps; int spaceVertical = (int) sVertical; double sHorizontal = (width * .8) / numberOfGaps; int spaceHorizontal = (int) sHorizontal; //Draw the Horizontal Lines int topY = topOfGrid; for(int count = 1; count <= lineNumber; count++){ canvas.drawLine(leftOfGrid, topY, rightOfGrid, topY); topY = topY + spaceVertical; } //Draw the Vertical Lines int leftX = leftOfGrid; for(int count = 1; count <= lineNumber; count++){ canvas.drawLine(leftX, bottomOfGrid, leftX, topOfGrid); leftX = leftX + spaceHorizontal; } } }
Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting
Draw them shorter.Draw them shorter.Quote:
the lines on my grid run past where they should.
It has to be .1(10%) from each border. And the grid must scale when the window is enlarged. So I cant really just draw them shorter without messing one of these scenarios up.
Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting
done, sorry
It looks like you have a simple arithmetic problem.
Take a piece of grid paper and draw the grid and see how the number of grids should be used to compute the x,y values for the corners.
How do you determine the x,y values for the corners?
Dunno guess I just don't see it. Been looking at this program way to much over past 48 hours. I just don't understand why its fine on the left and not the right.
If i put 10 into the pane, it is fine. Is it a rounding error because i parsed those doubles as ints? It seems the lines get more out of whack the higher the amount of lines the user specifies.
Try computing the x,y values for the four corners of the gird.
Consider that their positions must be an exact multiple of the number of squares times the size of each square.
For example if there are 8 sqrs and each is 10 pixels wide then the length of the lines will be 80 | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/14225-need-help-figuring-out-its-driving-me-nutz-printingthethread.html | CC-MAIN-2015-11 | refinedweb | 613 | 67.55 |
My entire project is fucked if I can't do this;
Basically, I need to be able to add an element to a JList (doesn't need to be a JList, just needs to be a list component) then have a tag added to the element too, so when I get the selected list item I can cast it to the object I need... I can't really explain it in words, let me explain it in code.
public class MyObject { public int i; public MyObject(int i) { this.i = i; } } public class Main { public void addJListElement() { jList.addElement("My object", new MyObject(10)); } public void getSelectedListElement() { MyObject myObject = (MyObject)jList.getSelectedElement().getTag(); int i = myObject.i; //should be 10. } }
Please excuse the poor code, I was rushing to create an example.
Is there anyway I can make this possible, or do something similar? | https://www.daniweb.com/programming/software-development/threads/357177/jlist-element-tags | CC-MAIN-2017-47 | refinedweb | 144 | 56.55 |
do not like the idea of Storing packages on a drive, Package store / SSIS catalog is more centralized and i have also noticed faster to run plus you do not need to worry about setting permissions for the SSIS user on the stored drive.
as for the main issue, it seems to me the SQL server agent / what ever user you are trying to run the job with may not have access to one part of your package data flow, might be because of the missing AS400 component you mentioned.
easiest way to check is:
import the package into MSDB, once done right click and select RUN Package, if it runs manually this way with no error it is definitely a permission issue some where. if it returns error it will be in more details which would help us identify the issue.
either way please note the result here so we can try to diagnose the cause.
indeed, the SSDT runs in 32bit mode, the SQL agent does run in 64bit mode.
as indicated, you can configure the package to indeed run in 32 bit mode, a bit of work though:
1. in the Job properties select steps
2. select the step in which the package is setup to execute ( i Assumed you have already created this) and press edit
3. select the execution tab
5. press ok and save
HOWEVER:
I have had a similar issue with the exact same error and running the package in 32 bit did not resolve anything,
in my case the cause was with user permissions. (me being stupid it took me a few days to find the cause)
when you run a package in SSDT it uses your windows current session credentials to run the package, running it within SQL however you need to select a user with permissions on running SSIS packages.
Now you can either use Proxy account or the SQL Server Agent Service Account.
here is my setup:
1. I have already imported my SSIS package into the Integration Services Package store
2. in Job step properties the package is set to run as SQL Server Agent Service Account
3. Package source is set to SSIS Package store
4. Use windows credentials
5. and finally the package path within the Store under MSDB
again no matter which method you use in either case make sure the job runs with an account that has full permission on SSIS executions.
Note that if you would like to use windows credentials instead of SQL server agent you need to create a proxy account.
I should have mentioned that I already tried the 32 bit option and still the same issue.
The SQL agent account has administrator rights on the server. The SSIS service is owned by another account. Is this OK or should I make the service account as the owner of SSIS service also ?
One of the team members also mentioned about a component for connecting to AS400 not right in the SQL server. He is installing it tonight. I will test it tomorrow and update the status.
Also, what is the best practice to store packages if I plan lot of SQL agent jobs to be scheduled overnight ?
Should I store the packages in a drive on the server or in MSDB package store or in SSIS catalog ?,
Another thing I noticed is the project level connection managers give trouble when I schedule a job using SQL agent. Is this a real problem or I am missing something ?
We have SQL server 2012 standard edition and I am using VS2012/SSDT.
Thanks Again.
But, my immediate task was changed to something else and I will post a different question for that.
Kind Regards | https://www.experts-exchange.com/questions/28663724/SSIS-package-does-not-run-in-SQL-agent-job.html | CC-MAIN-2018-26 | refinedweb | 622 | 69.31 |
So before anyone gets suspicious this IS HOMEWORK. So please don't waste your time posting "Do your own homework" because I am NOT asking for answers. Now that I have that out of the way.
Below I have posted the assignment:
So I know that is a lot of info but I am kinda confused. I have already created the "Movie" class (below)So I know that is a lot of info but I am kinda confused. I have already created the "Movie" class (below)Your task is to come up with an object-oriented design for a streaming movie rental system
(like NetFlix). The names of your classes, private instance variables, methods etc. are totally
up to you.
Specication
Every user has the following information associated with them:
A name.
An account number.
An ordered playlist of movies. In particular, if movie A is before movie B in the playlist, then the user watches A before B.
The five most recent movies that the user has watched.
There are three different kinds of users:
Trial: A trial user can only have one movie in their playlist at a time.
Members: A member can have up to 5 movies in their playlist at a time.
VIP Members: A VIP member can have an unlimited number of movies in their playlist.
Every user must be able to do the following operations:
Check-out a movie. If a user checks out a movie, then it is put at the end of the user's playlist.
Watch a movie: If a user watches a movie, then the movie is removed from the user's playlist. You may assume that the user can only watch whatever movie is at the front of the playlist.
Recall the five most recent movies that they have watched: This operation should print the most recent movies that the user has watched to the screen.
Every movie contains the following information:
A title.
A date.
A genre.
A rental price.
Notice that different users have different movie rental rights, so it is possible that a user willattempt to do something that (s)he is not allowed to do. When this occurs, you must do thefollowing:
Make sure that the operation is not performed.
Print an informative error message that states why the operation could not be performed.
Your object-oriented design must include the following object-oriented features:
An abstract class. What should be the base class that other classes build o of?
Inheritance. In particular, you must inherit from a base abstract class.
Polymorphism (Dynamic Binding). In particular, your method for checking a movie out must be polymorphic.
import java.util.Date; public class Movie { private String title; private String genre; private int price = 1; private Date d1 = new Date(); public Movie(String title, int day, int month, int year, String genre, int price) { super(); this.title = title; this.genre = genre; this.price = price; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String toString() { return "Title is: " + title +"\n" + "Today's date is: " + d1 + "\n" + "Genre: " + genre + "\n" + "Rental price is: " + price; } }
QUESTIONS FOR THE FORUM
I am working on the "User" class. but I am stuck now because I do not know what I should put into this user class.
Should I create three separate classes for the three types of memberships or should I just add them ALL into the "User" class. and how would I go about doing this?
I have a hard time thinking without a skeleton code, could some one help me create a skeleton so I at least know where to BEGIN.
Thanks again for this wonderful community, I would be failing this course if it was not for this site. | http://www.javaprogrammingforums.com/object-oriented-programming/19409-netflix-based-java-project.html | CC-MAIN-2014-15 | refinedweb | 652 | 73.58 |
Assignment:
"In this assignment, you are to write a program that will compute a monthly payment. You are to have, at least, 1 function ( other than main() ) in your program."
Problem:
I keep getting "inf" when I run the program. I mean, it's obvious that the main function is okay since it does ask for the input and displays something, so there must be a problem with the calculation function, but I'm not sure what the problem is.
#include <iostream> #include <math.h> using namespace std; float calculation(float p, float yir, float y) { float mir, payment, a, b, c, d, e, f; mir = yir / 1200; a = 1 + mir; b = 1 / a; c = 12 * y; d = pow(b, c); e = 1 - d; f = p * mir; payment = f / e; return payment; } int main() { float p, yir, y, x; x = calculation(p, yir, y); cout << "Input principal amount" << endl; cin >> p; cout << "Input yearly interest rate" << endl; cin >> yir; cout << "Input term in years" << endl; cin >> y; cout << x << endl; }
Any help would be grateful. | http://www.dreamincode.net/forums/topic/265754-inf-error-when-computing-payment/page__pid__1546582__st__0&#entry1546582 | crawl-003 | refinedweb | 175 | 68.23 |
TL;DR; Haskell can process flat files as though they were hierarchal with the help of lazy evaluation and one ridiculously clever one-line function.
When working on Day 7 of the Advent of Code, I asked an innocuous question on r/haskell that led me down an extremely deep rabbit hole. The first part of the problem gives you a textual specification of a tree as an unordered series of nodes and asks you to compute the depth. It doesn’t take a genius to figure out that the second part will also involve computing some property of the graph.
I’d originally planned to solve the problem like this:
- parse the lines
- assemble the lines into a tree structure
- use recursion-schemes to evaluate the answer
recursion-schemes is a powerful but rather impenetrable library (rather like
lens) that provides generalisations of
foldr and
unfoldr that work for recursive structures other than
List. Those familiar with the library will see that my final solution looks pretty similar to a solution using
cata.
Unfortunately, my plan somewhat resembled the following plan:
- steal underpants
- ???
- profit!
in that, I had nice elegant ways of dealing with 1 and 3, but 2 was going to be just plain annoying to write. So I asked a question as to whether there was a better way to do it. There was, courtesy of a function called
loeb.
loeb is a way of using Haskell’s pervasive laziness to circumvent a lot of busy work by the neat trick of constructing the final object as if it already existed. This makes it a generalisation of those Stupid Dwarf Tricks like the Fibonacci ZipList implementation we trot out when showing how powerful laziness is.
This gave me a fairly neat way of doing processing the tree structure by creating a map of node names to parsed assembled nodes, but something still bothered me: I had to write one function that created the map in the first place, and one function that looked up values in the map. This offended my sense of symmetry but I finally came up with what I believe to be a very nice way of solving it that uses the generalisation
moeb, which is described in more detail in the above linked David Luposchainsky article.
Preamble
I’ve written this up as literate Haskell, so next we have the inevitable headers:
{-# LANGUAGE ScopedTypeVariables #-}
Although not used in the final code, the ability to constrain types of identifiers in
where clauses is vital for me when I try to figure out why my code isn’t typechecking.
Some of the following declarations are used in part two.
module Day7blog2 where import qualified Text.Megaparsec as MP import qualified Text.Megaparsec.String as S import qualified Text.Megaparsec.Char as C import qualified Text.Megaparsec.Lexer as L
Megaparsec is a fork of the Parsec library with a very similar API that aims to be faster and produce better error messages.
import qualified Data.Map.Lazy as M import qualified Control.Monad as CM import qualified Control.Monad.Trans.Either as E import qualified Control.Monad.State.Lazy as St import Data.Function (on) import Data.List (maximumBy) import Data.Monoid (<$>)
Parsing the input file
We start by defining a type that corresponds to a line in the file.
data Node = Node { name :: String, weight :: Integer, children :: [String] } deriving (Show)
This is the first surprise of the code: if I were using recursion-schemes, I’d have created
Node a where
children :: [a] and derived
Functor. If I had actually wanted to construct the tree as I had originally planned I’d have still gone with that design, but as we’ll see, it’s possible to never actually construct the tree.
Next, we need a parser to map the lines of the file to our
Node representation. We’ll recall that the format looks like this:
ktlj (57) fwft (72) -> ktlj, cntj, xhth
nodeParser :: S.Parser Node nodeParser = do n <- identifier _ <- C.char ' ' w <- C.char '(' *> L.integer <* C.char ')' c <- MP.try parseChildren MP. pure [] _ <- MP.try C.newline -- the final line of the file doesn't have a newline pure Node { name = n, weight = w, children = c } where comma = C.char ',' <* C.char ' ' parseChildren = C.string " -> " *> MP.sepBy identifier comma identifier = MP.many MP.letterChar
I’m growing very fond of parser combinators very fast. I had trouble getting Megaparsec to work when I used its whitespace functions, but the file is very regular so I just threw them away.
day7text :: IO String day7text = readFile "C:\\Users\\me\\advent\\day7.txt"
Yes, I’m using Windows. As long as you don’t try to use a C library it’s not that bad.
nodes :: IO (Either (MP.ParseError Char MP.Dec) [Node]) nodes = MP.parse (MP.many nodeParser) "" <$> day7text
This type is pretty ugly, but I don’t know what I could do to fix it.
Computing the depth of the tree
Now we’ve got a list of
Nodes, we need to figure out how to process them as or into tree. We currently have no idea which
Node relates to which
Node and the data isn’t organised in a way to make this easy. Indeed, if we had constructed a tree of
Nodes computing the depth would be pretty simple. The standard way I’d handle this in C# would involve multiple passes building up partial results until we’d finally take everything off the “todo” pile. It works, but it’s not an approach I much like.
Wouldn’t it be great if we could process the nodes without worrying about the order, and let Haskell’s laziness resolve everything as appropriate. It turns out we can, using
moeb.
moeb :: (((result -> intermediate) -> intermediate) -> input -> result) -> input -> result moeb f x = go where go = f ($ go) x
This type signature is, frankly, too complex for someone at my level to work out, but the article by David Luposchainsky mentions that
((r -> m) -> m) -> i -> r is satisfied by
fmap,
foldMap,
traverse. (As an aside
moeb foldr attempts to construct an infinite type, so maybe don’t use that.) I don’t know if there are any other interesting functions that satisfy it.
So, here’s what those applications give us:
moeb fmap :: Functor f => f (f b -> b) -> f b moeb foldMap :: (Monoid r, Foldable t) => t (r -> r) -> r moeb traverse :: (Applicative f, Traversable t) => t (f (t b) -> f b) -> f (t b)
As established in the article,
moeb fmap is
loeb. Using
f = Map String would give you
Map String (Map String b -> b) -> Map String b.
moeb traverse gives you a monadic version of
loeb, which doesn’t seem to buy us much over
loeb.
Originally I tried implementing this code using
loeb. It would have worked, but as mentioned earlier I still had some reservations. It was then that it occurred to me that, as well as a
Functor and
Applicative,
Map String b is a
Monoid.
So, a specialized version of
moeb foldMap would be
[(Map String b) -> (Map String b)] -> (Map String b) where the
Strings are the node names and the
bs are whatever values we want to compute. We need a list of
(Map String b) -> (Map String b) and obviously they need to be generated from the list of
Nodes or we haven’t got a result that depends in the inputs. (There’s probably some Yoneda-adjacent insight to be had here, but I’m not there yet.)
So that means what we actually need is a function like this:
Node -> (Map String b) -> (Map String b). The first parameter is the
Node, the second parameter the lazily evaluated final result. And the result will be the singleton map entry for the original node. This can use the “final result” map to look up the child nodes and compute the current node’s value.
Then
moeb foldMap constructs these singleton maps and smushes them together to get the final result. i.e. final result -> intermediate results -> final result. As I’ve said before, none of this would work without a serious amount of lazy evaluation.
For such a long explanation, the resultant code is extremely short.
getDepth1 :: Node -> M.Map String (Maybe Integer) -> M.Map String (Maybe Integer) getDepth1 n m = M.singleton (name n) (((1+) . foldr max 0) <$> z) where z = traverse CM.join $ (`M.lookup` m) <$> children n
We’re using
Maybe Integer rather than
Integer to capture the possibility that there’s a broken reference in the file. So this function:
- takes the node names of the children,
- looks up the depths in
m(adding another Maybe to the type in the process)
- takes
[Maybe (Maybe Integer)]and turns it into
Maybe [Integer]courtesy of
traverse CM.join
- finds the largest value (
0if it’s empty)
- adds one
- makes a singleton map for the node to that new value
That’s the hard work done, now we just follow the types to get this solution
day7a = do Right n <- nodes (pure . maximumBy (on compare snd) . M.assocs . moeb foldMap) $ getDepth1 <$> n
Print that out in GHCI and it gives us the depth and the name of the root node. This is good, but still a bit ugly and also not very general.
Taking it further
Let’s imagine that, instead, we wanted to sum the weights. At this point, we should come up with something more reusable. After all, all we really want to write is a catamorphism function that takes the current node, the results of its children and gives you the result for the current node. The type for this would be
Node -> [a] -> a and we want a function that would take that and give us something that looked like
getDepth1.
So cleaning up the code we’ve already written gives us this:
nodeReduce :: (Node -> [a] -> a) -> Node -> M.Map String (Maybe a) -> M.Map String (Maybe a) nodeReduce f n m = M.singleton (name n) (f n <$> z) where z = traverse CM.join $ (`M.lookup` m) <$> children n
This is pretty similar to the code in
getDepth1. Now we can write a general routine for processing
Nodes. It’s also obvious how to generalize this even further.
process :: (Node -> [a] -> a) -> [Node] -> M.Map String (Maybe a) process f l = moeb foldMap $ nodeReduce f <$> l getDepth2 :: Node -> [Integer] -> Integer getDepth2 _ = (1+) . foldr max 0 day7a2 = do Right n <- nodes (pure . maximumBy (on compare snd) . M.assocs . process getDepth2) n
So, now we have a cleaner way of getting the same result as last time, let’s now extend it to sum the weights.
data NodeWeight = NodeWeight { node :: Node, totalWeight :: Integer } deriving (Show)
We could just compute the
Integer and throw away the type, but when you’re debugging it’s rather useful to have all the relevant information around.
sumNodes :: Node -> [NodeWeight] -> NodeWeight sumNodes n l = NodeWeight { node = n, totalWeight = weight n + sum (totalWeight <$> l) }
So, by dropping
sumNodes in instead of
getDepth2 we can solve a different problem.
day7sumNodes = (fmap . fmap) (process sumNodes) nodes lookup x = (fmap . fmap) (M.! x) day7sumNodes
Of course, no-one was actually asking us for this answer, and the second part is significantly harder. However, this has hopefully shown the power of the technique, that allows you to process flat files in an order imposed by their logical structure. In the second part we’ll show how this can be used to solve the much harder part b of Day 7: finding the incorrect value in the file.
Many thanks must go to Kris Jenkins for reviewing this post providing some really valuable feedback, and those that helped me out and showed me interesting things on r/haskell. | https://colourcoding.net/2018/03/ | CC-MAIN-2018-34 | refinedweb | 1,967 | 71.44 |
The heap data structures can be used to represents a priority queue. In python it is available into the heapq module. Here it creates a min-heap. So when the priority is 1, it represents the highest priority. When new elements are inserted, the heap structure updates.
To use this module, we should import it using −
import heapq
There are some heap related operations. These are −
It is used to convert an iterable dataset to heap data structure.
This method is used to insert the element into the heap. After that re-heap the entire heap structure.
This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements.
This method is used to insert and pop element in one statement..
This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap.
This method is used to return n largest element from the heap.
This method is used to return n smallest element from the heap.
import heapq my_list = [58, 41, 12, 17, 89, 65, 23, 20, 10, 16, 17, 19] heapq.heapify(my_list) print(my_list) heapq.heappush(my_list, 7) print(my_list) print('Popped Element: ' + str(heapq.heappop(my_list))) print(my_list) new_iter = list() new_iter = heapq.nlargest(4, my_list) print(new_iter)
[10, 16, 12, 17, 17, 19, 23, 20, 41, 89, 58, 65] [7, 16, 10, 17, 17, 12, 23, 20, 41, 89, 58, 65, 19] Popped Element: 7 [10, 16, 12, 17, 17, 19, 23, 20, 41, 89, 58, 65] [89, 65, 58, 41] | https://www.tutorialspoint.com/python-heap-queue-algorithm | CC-MAIN-2021-43 | refinedweb | 273 | 75.3 |
?diff --git a/mm/mmap.c b/mm/mmap.cindex 9efdc021ad22..fd64ff662117 100644--- a/mm/mmap.c+++ b/mm/mmap.c@@ -1615,6 +1615,34 @@ static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags) return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE; } +/**+ * mmap_max_overlaps - Check the process has not exceeded its quota of mappings.+ * @mm: The memory map for the process creating the mapping.+ * @file: The file the mapping is coming from.+ * @pgoff: The start of the mapping in the file.+ * @count: The number of pages to map.+ *+ * Return: %true if this region of the file has too many overlapping mappings+ * by this process.+ */+bool mmap_max_overlaps(struct mm_struct *mm, struct file *file,+ pgoff_t pgoff, pgoff_t count)+{+ unsigned int overlaps = 0;+ struct vm_area_struct *vma;++ if (!file)+ return false;++ vma_interval_tree_foreach(vma, &file->f_mapping->i_mmap,+ pgoff, pgoff + count) {+ if (vma->vm_mm == mm)+ overlaps++;+ }++ return overlaps > 9;+}+ unsigned long mmap_region(struct file *file, unsigned long addr, unsigned long len, vm_flags_t vm_flags, unsigned long pgoff, struct list_head *uf)@@ -1640,6 +1668,9 @@ unsigned long mmap_region(struct file *file, unsigned long addr, return -ENOMEM; } + if (mmap_max_overlaps(mm, file, pgoff, len >> PAGE_SHIFT))+ return -ENOMEM;+ /* Clear old maps */ while (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent)) {diff --git a/mm/mremap.c b/mm/mremap.cindex 049470aa1e3e..27cf5cf9fc0f 100644--- a/mm/mremap.c+++ b/mm/mremap.c@@ -430,6 +430,10 @@ static struct vm_area_struct *vma_to_resize(unsigned long addr, (new_len - old_len) >> PAGE_SHIFT)) return ERR_PTR(-ENOMEM); + if (mmap_max_overlaps(mm, vma->vm_file, pgoff,+ (new_len - old_len) >> PAGE_SHIFT))+ return ERR_PTR(-ENOMEM);+ if (vma->vm_flags & VM_ACCOUNT) { unsigned long charged = (new_len - old_len) >> PAGE_SHIFT; if (security_vm_enough_memory_mm(mm, charged)) | https://lkml.org/lkml/2018/2/8/651 | CC-MAIN-2018-43 | refinedweb | 260 | 62.07 |
The QTextCodec class provides conversion between text encodings. More...
#include <qtextcodec.h>
Inherited by *c = QTextCodec::codecForName( "Shift-JIS" ); QTextDecoder *decoder = c-.
By making objects of subclasses of QTextCodec, support for new text encodings can be added to Qt.Dec.
s contains the string being tested for encode-ability.().
Warning: Do not call this function.
QApplication calls this can be helpful to chase down memory leaks, as QTextCodec objects will not show up..
Subclasses of QTextCodec in memory shared by all applications simultaneously using Qt.GbkCodec, QJisCodec, QHebrewCodec and QSjisCodec.
Subclasses of QTextCodec must reimplement this function. It returns the name of the encoding supported by the subclass. When choosing a name for an encoding, consider these points:
Example: qwerty/qwerty.cpp.
See also codecForLocale().-2002 Trolltech. All Rights Reserved. | http://doc.trolltech.com/3.0/qtextcodec.html | crawl-002 | refinedweb | 130 | 53.58 |
on run {input, parameters}
tell application "iTunes"
launch
set this_track to add input to playlist "Library" of source "Library"
duplicate this_track to playlist "film"
end tell
return input
end run
Does unchecking the preference in iTunes "Copy files to iTunes Music folder when adding to Library" not work for Films???
It does. That's what I do. This is much less of a hassle. Set this up, and then it
done. Otherwise, each time I want to import a movie, I either copy it, or uncheck;
import; check. But then, the movie is not 'organized' either. This is the way to go!
---
"The best way to accelerate a PC is 9.8 m/s2"
My reply doesn't have much to do with your process, and it's farily obvious, but I
thought I'd share anyway.
Since I don't like having my ipod movies stored in my iTunes Music Library, I just
drag the movie file onto the iPod in iTunes. The movie gets copied to my iPod
without getting copied to my music library.
I then delete the file from my hard drive to save room (I can always remake it
with Handbrake, so no need to use up storage space on both the ipod and the hard
drive).
Another option would be to have an Import folder _inside_ your library, with a
placeholder file so that iTunes doesn't delete the folder. Have Handbrake
export to your Import folder, and create a folder action that fires off your
import applescript. Since the file is, technically, already IN the iTunes music
folder, iTuned will just update the location on disk without a requirement for a
file copy operation.
Incidentally, I was snarfing up some of the scripting goodness at
Doug's Applescripts for iTunes website, and I found an app called
"DVD2Pod".
Can you guess what it does?
It says it's based on Handbrake. It does most of what your hint
describes, including offering an option to put the converted movie into
the iTunes library. I've tried it twice so far, and just dragged the video
file onto the iPod, into a list I made.
I'm not sure [since I've only had an iPod a week] but it seems to me I
can't watch any videos unless I've put the video into a playlist. Just
dropping a video file onto the iPod in iTunes didn't seem to put it
anywhere that I could find it [but it sure took its time copying it, so it
must have gone somewhere].
---
--
osxpounder
Don't have an account yet? Sign up as a New User
Visit other IDG sites: | http://hints.macworld.com/article.php?story=20060524085833709 | CC-MAIN-2014-15 | refinedweb | 446 | 78.69 |
Section 6.4
Timers, KeyEvents, and State Machines
Not every event is generated by an action on the part of the user. Events can also be generated by objects as part of their regular programming, and these events can be monitored by other objects so that they can take appropriate actions when the events occur. One example of this is the class javax.swing.Timer. A Timer generates events at regular intervals. These events can be used to drive an animation or to perform some other task at regular intervals. We will begin this section with a look at timer events and animation. We will then look at another type of basic user-generated event: the KeyEvents that are generated when the user types on the keyboard. The example at the end of the section uses both a timer and keyboard events to implement a simple game and introduces the important idea of state machines.
6.4.1 Timers and Animation
An object belonging to the class javax.swing.Timer exists only to generate events. A Timer, by default, generates a sequence of events with a fixed delay between each event and the next. (It is also possible to set a Timer to emit a single event after a specified time delay; in that case, the timer is being used as an "alarm.") Each event belongs to the class ActionEvent. An object that is to listen for the events must implement the interface ActionListener, which defines just one method:
public void actionPerformed(ActionEvent evt)
To use a Timer, you must create an object that implements the ActionListener interface. That is, the object must belong to a class that is declared to "implement ActionListener", and that class must define the actionPerformed method. Then, if the object is set to listen for events from the timer, the code in the listener's actionPerformed method will be executed every time the timer generates an event.
Since there is no point to having a timer without having a listener to respond to its events, the action listener for a timer is specified as a parameter in the timer's constructor. The time delay between timer events is also specified in the constructor. If timer is a variable of type Timer, then the statement
timer = new Timer( millisDelay, listener );
creates a timer with a delay of millisDelay milliseconds between events (where 1000 milliseconds equal one second). Events from the timer are sent to the listener. (millisDelay must be of type int, and listener must be of type ActionListener.) The listener's actionPerfomed() will be executed every time the timer emits an event. Note that a timer is not guaranteed to deliver events at precisely regular intervals. If the computer is busy with some other task, an event might be delayed or even dropped altogether.
A timer does not automatically start generating events when the timer object is created. The start() method in the timer must be called to tell the timer to start running. The timer's stop() method can be used to turn the stream of events off. It can be restarted later by calling start() again.
One application of timers is computer animation. A computer animation is just a sequence of still images, presented to the user one after the other. If the time between images is short, and if the change from one image to another is not too great, then the user perceives continuous motion. The easiest way to do animation in Java is to use a Timer to drive the animation. Each time the timer generates an event, the next frame of the animation is computed and drawn on the screen -- the code that implements this goes in the actionPerformed method of an object that listens for events from the timer.
Our first example of using a timer is not exactly an animation, but it does display a new image for each timer event. The program shows randomly generated images that vaguely resemble works of abstract art. In fact, the program draws a new random image every time its paintComponent() method is called, and the response to a timer event is simply to call repaint(), which in turn triggers a call to paintComponent. The work of the program is done in a subclass of JPanel, which starts like this:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RandomArtPanel extends JPanel { /** * A RepaintAction object calls the repaint method of this panel each * time its actionPerformed() method is called. An object of this * type is used as an action listener for a Timer that generates an * ActionEvent every four seconds. The result is that the panel is * redrawn every four seconds. */ private class RepaintAction implements ActionListener { public void actionPerformed(ActionEvent evt) { repaint(); // Call the repaint() method in the panel class. } } /** * The constructor creates a timer with a delay time of four seconds * (4000 milliseconds), and with a RepaintAction object as its * ActionListener. It also starts the timer running. */ public RandomArtPanel() { RepaintAction action = new RepaintAction(); Timer timer = new Timer(4000, action); timer.start(); } /** * The paintComponent() method fills the panel with a random shade of * gray and then draws one of three types of random "art". The type * of art to be drawn is chosen at random. */ public void paintComponent(Graphics g) { . . // The rest of the class is omitted .
You can find the full source code for this class in the file RandomArt.java. I will only note that the very short RepaintAction class is a natural candidate to be replaced by an anonymous inner class. That can be done where the timer is created:
Timer timer = new timer(4000, new ActionListener() { public void actionPerformed(ActionEvent evt) { repaint(); } });
Later in this section, we will use a timer to drive the animation in a simple computer game.
6.4.2 Keyboard Events
In Java, user actions become events in a program. These.
It's a good idea to give the user some visual feedback about which component has the input focus. For example, if the component is the typing area of a word-processor, the feedback is usually in the form of a blinking text cursor. Another possible visual clue is to draw a brightly colored border around the edge of a component when it has the input focus, as I do in the examples given later in this section.
If comp is any component, and you would like it to have the input focus, you can call requestFocusInWindow(), which should work as long as the window that contains the component is active and there is only one component that is requesting focus. In some cases, when there is only one component involved, it is enough to call this method once, just after opening the window, and the component will retain the focus for the rest of the program. (Note that there is also a requestFocus() method that might work even when the window is not active, but the newer method requestFocusInWindow() is preferred in most cases.)
In a typical user interface, the user can choose to give the focus to a component by clicking on that component with the mouse. And pressing the tab key will often move the focus from one component to another. This is handled automatically by the components involved, without any programming on your part. However, some components do not automatically request the input focus when the user clicks on them. To solve this problem, a program can register a mouse listener with the component to detect user clicks. In response to a user click, the mousePressed() method should call requestFocusInWindow() for the component. This is true, in particular, for JPanels that are used as drawing surfaces, since JPanel objects do not receive the input focus automatically.
As our first example of processing key events, we look at a simple program in which the user moves a square up, down, left, and right by pressing arrow keys. When the user hits the 'R', 'G', 'B', or 'K' key, the color of the square is set to red, green, blue, or black, respectively. Of course, none of these key events are delivered to the panel unless it has the input focus. The panel in the program changes its appearance when it has the input focus: When it does, a cyan-colored border is drawn around the panel; when it does not, a gray-colored border is drawn. The complete source code for this example can be found in the file KeyboardAndFocusDemo.java. I will discuss some aspects of it below. After reading this section, you should be able to understand the source code in its entirety. I suggest running the program to see how it works.
In Java, keyboard event objects belong to a class called KeyEvent. An object that needs to listen for KeyEvents must implement the interface named KeyListener. Furthermore, the object must be registered with a component by calling the component's addKeyListener() method. The registration is done with the command "component.addKeyListener(listener);" where listener is the object that is to listen for key events, and component is the object that will generate the key events (when it has the input focus). It is possible for component and listener to be the same object., and so on. In some cases, such as the shift key, OS computer, I can type an accented (whether that's done with one key press or several). Note that one user action, such as pressing the E key, can be responsible for two events, a keyPressed event and a keyTyped event. Typing an upper case 'A' can generate two keyPressed events, two keyReleased events, and one keyPressed events. I used to have a computer solitaire game that highlighted every card that could be moved, when I held down the Shift key. You can do something like that in Java by highlighting the cards when the Shift key is pressed and removing the highlight when the Shift key is released.
There is one more complication. Usually, when you hold down a key on the keyboard, that key will auto-repeat. This means that it will generate multiple keyPressed events with just one keyReleased at the end of the sequence. program, I use the keyPressed routine to respond when the user presses one of the arrow keys. The program includes instance variables, squareLeft and squareTop, that give the position of the upper left corner of the movable square. When the user presses one of the arrow keys, the keyPressed routine modifies the appropriate instance variable and calls repaint() to redraw the panel with the square in its new position. Note that the values of squareLeft and squareTop are restricted so that the square never moves outside the white area of the panel:
/** * This is called each time the user presses a key while the panel has * the input focus. If the key pressed was one of the arrow keys, * the square is moved (except that it is not allowed to move off the * edge of the panel, allowing for a 3-pixel border). */ public void keyPressed(KeyEvent evt) { int key = evt.getKeyCode(); // keyboard code for the pressed key if (key == KeyEvent.VK_LEFT) { // left-arrow key; move the square left squareLeft -= 8; if (squareLeft < 3) squareLeft = 3; repaint(); } else if (key == KeyEvent.VK_RIGHT) { // right-arrow key; move the square right squareLeft += 8; if (squareLeft > getWidth() - 3 - SQUARE_SIZE) squareLeft = getWidth() - 3 - SQUARE_SIZE; repaint(); } else if (key == KeyEvent.VK_UP) { // up-arrow key; move the square up squareTop -= 8; if (squareTop < 3) squareTop = 3; repaint(); } else if (key == KeyEvent.VK_DOWN) { // down-arrow key; move the square down squareTop += 8; if (squareTop > getHeight() - 3 - SQUARE_SIZE) squareTop = getHeight() - program, the body of this method is empty since the program does nothing in response to keyReleased events.
6.4.3 registered with FocusListener. When it loses the focus, it calls the listener's focusLost() method.
In the sample KeyboardAndFocusDemo program, the response to a focus event is simply to redraw the panel. The paintComponent() method checks whether the panel has the input focus by calling the boolean-valued function hasFocus(), which is defined in the Component class, and it draws a different picture depending on whether or not the panel has the input focus. The net result is that the appearance of the panel changes when the panel gains or loses focus. The methods from the FocusListener interface are defined simply as:
public void focusGained(FocusEvent evt) { // The panel now has the input focus. repaint(); // will redraw with a new message and a cyan border } public void focusLost(FocusEvent evt) { // The panel has now lost the input focus. repaint(); // will redraw with a new message and a gray border }
The other aspect of handling focus is to make sure that the panel actually gets the focus. In this case, I called requestFocusInWindow() for the panel in the program's main() routine, just after opening the window. This approach works because there is only one component in the window, and it should have focus as long as the window is active. If the user clicks over to another window while using the program, the window becomes inactive and the panel loses focus temporarily, but gets is back when the user clicks back to the program window.
There are still decisions to be made about the overall structure of the program. In this case, I decided to use a nested class named Listener to define an object that listens for both focus and key events. In the constructor for the panel, I create an object of type Listener and register it to listen for both key events and focus events from the panel. See the source code for full details.
6.4.4 depends on what state it's in when the event occurs. An object is a kind of state machine. Sometimes, this point of view can be very useful in designing classes.
The state machine point of view can be especially useful in the type of event-oriented programming that is required by graphical user interfaces. When designing a GUI program, you can ask yourself: What information about state do I need to keep track of? What events can change the state of the program? How will my response to a given event depend on the current state? Should the appearance of the GUI be changed to reflect a change in state? How should the paintComponent() method take the state into account? All this is an alternative to the top-down, step-wise-refinement style of program design, which does not apply to the overall design of an event-oriented program.
In the KeyboardAndFocusDemo program, shown above, the state of the program is recorded in the instance variables squareColor, squareLeft, and squareTop. These state variables are used in the paintComponent() method to decide how to draw the panel. Their values are changed in the two key-event-handling methods.
In the rest of this section, we'll look at another example, where the state plays an even bigger role. In this example, the user plays a simple arcade-style game by pressing the arrow keys. The program is defined in the source code file SubKiller.java. As usual, it would be a good idea to compile and run the program as well as read the full source code. Here is a picture:
The program shows a black "submarine" near the bottom of the panel. While the panel has the input focus, this submarine moves back and forth erratically near the bottom. Near the top, there is a blue "boat." You can move this boat back and forth by pressing the left and right arrow keys. Attached to the boat is a red "bomb" (or "depth charge"). You can drop the bomb by hitting the down arrow key. The objective is to blow up the submarine by hitting it with the bomb. If the bomb falls off the bottom of the screen, you get a new one. If the submarine explodes, a new sub is created and you get a new bomb. Try it! Make sure to hit the sub at least once, so you can see the explosion.
Let's think about how this game can be programmed. First of all, since we are doing object-oriented programming, I decided to represent the boat, the depth charge, and the submarine as objects. Each of these objects is defined by a separate nested class inside the main panel class, and each object has its own state which is represented by the instance variables in the corresponding class. I use variables boat, bomb, and sub in the panel class to refer to the boat, bomb, and submarine objects.
Now, what constitutes the "state" of the program? That is, what things change from time to time and affect the appearance or behavior of the program? Of course, the state includes the positions of the boat, submarine, and bomb, so those objects have instance variables to store the positions. Anything else, possibly less obvious? Well, sometimes the bomb is falling, and sometimes it's not. That is a difference in state. Since there are two possibilities, I represent this aspect of the state with a boolean variable in the bomb object, bomb.isFalling. Sometimes the submarine is moving left and sometimes it is moving right. The difference is represented by another boolean variable, sub.isMovingLeft. Sometimes, the sub is exploding. This is also part of the state, and it is represented by a boolean variable, sub.isExploding. However, the explosions require a little more thought. An explosion is something that takes place over a series of frames. While an explosion is in progress, the sub looks different in each frame, as the size of the explosion increases. Also, I need to know when the explosion is over so that I can go back to moving and drawing the sub as usual. So, I use an integer variable, sub.explosionFrameNumber to record how many frames have been drawn since the explosion started; the value of this variable is used only when an explosion is in progress.
How and when do the values of these state variables change? Some of them seem to change on their own: For example, as the sub moves left and right, the state variables that specify its position change. Of course, these variables are changing because of an animation, and that animation is driven by a timer. Each time an event is generated by the timer, some of the state variables have to change to get ready for the next frame of the animation. The changes are made by the action listener that listens for events from the timer. The boat, bomb, and sub objects each contain an updateForNextFrame() method that updates the state variables of the object to get ready for the next frame of the animation. The action listener for the timer calls these methods with the statements
boat.updateForNewFrame(); bomb.updateForNewFrame(); sub.updateForNewFrame();
The action listener also calls repaint(), so that the panel will be redrawn to reflect its new state. There are several state variables that change in these update methods, in addition to the position of the sub: If the bomb is falling, then its y-coordinate increases from one frame to the next. If the bomb hits the sub, then the isExploding variable of the sub changes to true, and the isFalling variable of the bomb becomes false. The isFalling variable also becomes false when the bomb falls off the bottom of the screen. If the sub is exploding, then its explosionFrameNumber increases from one frame to the next, and when it reaches a certain value, the explosion ends and isExploding is reset to false. At random times, the sub switches between moving to the left and moving to the right. Its direction of motion is recorded in the sub's isMovingLeft variable. The sub's updateForNewFrame() method includes these lines to change the value of isMovingLeft at random times:
if ( Math.random() < 0.04 ) isMovingLeft = ! isMovingLeft;
There is a 1 in 25 chance that Math.random() will be less than 0.04, so the statement "isMovingLeft = ! isMovingLeft" is executed in one in every twenty-five frames, on average. The effect of this statement is to reverse the value of isMovingLeft, from false to true or from true to false. That is, the direction of motion of the sub is reversed.
In addition to changes in state that take place from one frame to the next, a few state variables change when the user presses certain keys. In the program, this is checked in a method that responds to user keystrokes. If the user presses the left or right arrow key, the position of the boat is changed. If the user presses the down arrow key, the bomb changes from not-falling to falling. This is coded in the keyPressed()method of a KeyListener that is registered to listen for key events on the panel; that method reads as follows:
public void keyPressed(KeyEvent evt) { int code = evt.getKeyCode(); // which key was pressed. if (code == KeyEvent.VK_LEFT) { // Move the boat left. (If this moves the boat out of the frame, its // position will be adjusted in the boat.updateForNewFrame() method.) boat.centerX -= 15; } else if (code == KeyEvent.VK_RIGHT) { // Move the boat right. (If this moves boat out of the frame, its // position will be adjusted in the boat.updateForNewFrame() method.) boat.centerX += 15; } else if (code == KeyEvent.VK_DOWN) { // Start the bomb falling, if it is not already falling. if ( bomb.isFalling == false ) bomb.isFalling = true; } }
Note that it's not necessary to call repaint() in this method, since this panel shows an animation that is constantly being redrawn anyway. Any changes in the state will become visible to the user as soon as the next frame is drawn. At some point in the program, I have to make sure that the user does not move the boat off the screen. I could have done this in keyPressed(), but I choose to check for this in another routine, in the boat object.
The program uses four listeners, to respond to action events from the timer, key events from the user, focus events, and mouse events. In this program, the user must click the panel to start the game. The game is programmed to run as long as the panel has the input focus. In this example, the program does not automatically request the focus; the user has to do it. When the user clicks the panel, the mouse listener requests the input focus and the game begins. The timer runs only when the panel has the input focus; this is programmed by having the focus listener start the timer when the panel gains the input focus and stop the timer when the panel loses the input focus. All four listeners are created in the constructor of the SubKillerPanel class using anonymous inner classes. (See Subsection 6.3.5.)
I encourage you to read the source code in SubKiller.java. Although a few points are tricky, you should with some effort be able to read and understand the entire program. Try to understand the program in terms of state machines. Note how the state of each of the three objects in the program changes in response to events from the timer and from the user.
While it's not at all sophisticated as arcade games go, the SubKiller game does use some interesting programming. And it nicely illustrates how to apply state-machine thinking in event-oriented programming. | http://math.hws.edu/javanotes/c6/s4.html | CC-MAIN-2017-17 | refinedweb | 3,924 | 70.43 |
2009-06-04 09:17:52 8 Comments
#include <stdio.h> int main(void) { int i = 0; i = i++ + ++i; printf("%d\n", i); // 3 i = 1; i = (i++); printf("%d\n", i); // 2 Should be 1, no ? volatile int u = 0; u = u++ + ++u; printf("%d\n", u); // 1 u = 1; u = (u++); printf("%d\n", u); // 2 Should also be one, no ? register int v = 0; v = v++ + ++v; printf("%d\n", v); // 3 (Should be the same as u ?) int w = 0; printf("%d %d\n", ++w, w); // shouldn't this print 1 1 int x[2] = { 5, 8 }, y = 0; x[y] = y ++; printf("%d %d\n", x[0], x[1]); // shouldn't this print 0 8? or 5 0? }
Related Questions
Sponsored Content
9 Answered Questions
[SOLVED] Undefined, unspecified and implementation-defined behavior
- 2010-03-07 21:10:30
- Zolomon
- 49511 View
- 504 Score
- 9 Answer
- Tags: c++ c undefined-behavior unspecified-behavior implementation-defined-behavior
5 Answered Questions
[SOLVED] Undefined behavior and sequence points
- 2010-11-14 05:37:46
- Prasoon Saurav
- 100195 View
- 970 Score
- 5 Answer
- Tags: c++ undefined-behavior c++-faq sequence-points
23 Answered Questions
[SOLVED] Which is faster: while(1) or while(2)?
- 2014-07-20 07:32:49
- Nikole
- 86646 View
- 581 Score
- 23 Answer
- Tags: c performance while-loop
1 Answered Questions
[SOLVED] Is the behavior of i = post_increment_i() specified, unspecified, or undefined?
- 2012-06-25 20:36:19
- user1480833
- 279 View
- 6 Score
- 1 Answer
- Tags: c language-lawyer undefined-behavior operator-precedence sequence-points
9 Answered Questions
[SOLVED] Why does sizeof(x++) not increment x?
11 Answered Questions
[SOLVED] Why is f(i = -1, i = -1) undefined behavior?
- 2014-02-10 06:31:32
- Nicu Stiurca
- 23682 View
- 266 Score
- 11 Answer
- Tags: c++ language-lawyer undefined-behavior
2 Answered Questions
[SOLVED] What is the rationale for this undefined behavior?
- 2015-07-07 12:51:40
- dhein
- 779 View
- 5 Score
- 2 Answer
- Tags: c++ undefined-behavior
5 Answered Questions
[SOLVED] Undefined behavior and sequence points reloaded
- 2011-01-09 08:40:54
- Nawaz
- 11317 View
- 84 Score
- 5 Answer
- Tags: c++ undefined-behavior c++-faq sequence-points
@Steve Summit 2015-06-18 11:55:45
Another way of answering this, rather than getting bogged down in arcane details of sequence points and undefined behavior, is simply to ask, what are they supposed to mean? What was the programmer trying to do?
The first fragment asked about,
i = i++ + ++i, is pretty clearly insane in my book. No one would ever write it in a real program, it's not obvious what it does, there's no conceivable algorithm someone could have been trying to code that would have resulted in this particular contrived sequence of operations. And since it's not obvious to you and me what it's supposed to do, it's fine in my book if the compiler can't figure out what it's supposed to do, either.
The second fragment,
i = i++, is a little easier to understand. Someone is clearly trying to increment i, and assign the result back to i. But there are a couple ways of doing this in C. The most basic way to add 1 to i, and assign the result back to i, is the same in almost any programming language:
C, of course, has a handy shortcut:
This means, "add 1 to i, and assign the result back to i". So if we construct a hodgepodge of the two, by writing
what we're really saying is "add 1 to i, and assign the result back to i, and assign the result back to i". We're confused, so it doesn't bother me too much if the compiler gets confused, too.
Realistically, the only time these crazy expressions get written is when people are using them as artificial examples of how ++ is supposed to work. And of course it is important to understand how ++ works. But one practical rule for using ++ is, "If it's not obvious what an expression using ++ means, don't write it."
We used to spend countless hours on comp.lang.c discussing expressions like these and why they're undefined. Two of my longer answers, that try to really explain why, are archived on the web:
See also question 3.8 and the rest of the questions in section 3 of the C FAQ list.
@supercat 2015-06-30 16:14:39
A rather nasty gotcha with regard to Undefined Behavior is that while it used to be safe on 99.9% of compilers to use
*p=(*q)++;to mean
if (p!=q) *p=(*q)++; else *p= __ARBITRARY_VALUE;that is no longer the case. Hyper-modern C would require writing something like the latter formulation (though there's no standard way of indicating code doesn't care what's in
*p) to achieve the level of efficiency compilers used to provide with the former (the
elseclause is necessary in order to let the compiler optimize out the
ifwhich some newer compilers would require).
@artm 2016-02-08 07:49:15
I've seen at least 5 similar questions about these ++ and -- madness last week or so. These seem to be some professors' favorite topic to puzzle their students..
@Steve Summit 2019-09-23 18:26:18
@supercat I now believe that any compiler that's "smart" enough to perform that sort of optimization must also be smart enough to peek at
assertstatements, so that the programmer can precede the line in question with a simple
assert(p != q). (Of course, taking that course would also require rewriting
<assert.h>to not delete assertions outright in non-debug versions, but rather, turn them into something like
__builtin_assert_disabled()that the compiler proper can see, and then not emit code for.)
@P.P. 2015-12-30 20:26:30
Often this question is linked as a duplicate of questions related to code like
or
or similar variants.
While this is also undefined behaviour as stated already, there are subtle differences when
printf()is involved when comparing to a statement such as:
In the following statement:
the order of evaluation of arguments in
printf()is unspecified. That means, expressions
i++and
++icould be evaluated in any order. C11 standard has some relevant descriptions on this:
Annex J, unspecified behaviours
3.4.4, unspecified behavior
The unspecified behaviour itself is NOT an issue. Consider this example:
This too has unspecified behaviour because the order of evaluation of
++xand
y++is unspecified. But it's perfectly legal and valid statement. There's no undefined behaviour in this statement. Because the modifications (
++xand
y++) are done to distinct objects.
What renders the following statement
as undefined behaviour is the fact that these two expressions modify the same object
iwithout an intervening sequence point.
Another detail is that the comma involved in the printf() call is a separator, not the comma operator.
This is an important distinction because the comma operator does introduce a sequence point between the evaluation of their operands, which makes the following legal:
The comma operator evaluates its operands left-to-right and yields only the value of the last operand. So in
j = (++i, i++);,
++iincrements
ito
6and
i++yields old value of
i(
6) which is assigned to
j. Then
ibecomes
7due to post-increment.
So if the comma in the function call were to be a comma operator then
will not be a problem. But it invokes undefined behaviour because the comma here is a separator.
For those who are new to undefined behaviour would benefit from reading What Every C Programmer Should Know About Undefined Behavior to understand the concept and many other variants of undefined behaviour in C.
This post: Undefined, unspecified and implementation-defined behavior is also relevant.
@kavadias 2018-10-17 20:20:57
This sequence
int a = 10, b = 20, c = 30; printf("a=%d b=%d c=%d\n", (a = a + b + c), (b = b + b), (c = c + c));appears to give stable behavior (right-to-left argument evaluation in gcc v7.3.0; result "a=110 b=40 c=60"). Is it because the assignments are considered as 'full-statements' and thus introduce a sequence point? Shouldn't that result in left-to-right argument/statement evaluation? Or, is it just manifestation of undefined behavior?
@P.P. 2018-10-18 08:40:02
@kavadias That printf statement involves undefined behaviour, for the same reason explained above. You are writing
band
cin 3rd & 4th arguments respectively and reading in 2nd argument. But there's no sequence between these expressions (2nd, 3rd, & 4th args). gcc/clang has an option
-Wsequence-pointwhich can help find these, too.
@Antti Haapala 2017-03-26 14:58:07
While the syntax of the expressions like
a = a++or
a++ + a++is legal, the behaviour of these constructs is undefined because a shall in C standard is not obeyed. C99 6.5p2:
With footnote 73 further clarifying that
The various sequence points are listed in Annex C of C11 (and C99):
The wording of the same paragraph in C11 is:
You can detect such errors in a program by for example using a recent version of GCC with
-Walland
-Werror, and then GCC will outright refuse to compile your program. The following is the output of gcc (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005:
The important part is to know what a sequence point is -- and what is a sequence point and what isn't. For example the comma operator is a sequence point, so
is well-defined, and will increment
iby one, yielding the old value, discard that value; then at comma operator, settle the side effects; and then increment
iby one, and the resulting value becomes the value of the expression - i.e. this is just a contrived way to write
j = (i += 2)which is yet again a "clever" way to write
However, the
,in function argument lists is not a comma operator, and there is no sequence point between evaluations of distinct arguments; instead their evaluations are unsequenced with regard to each other; so the function call
has undefined behaviour because there is no sequence point between the evaluations of
i++and
++iin function arguments, and the value of
iis therefore modified twice, by both
i++and
++i, between the previous and the next sequence point.
@Steve Summit 2018-08-16 11:54:35
Your question was probably not, "Why are these constructs undefined behavior in C?". Your question was probably, "Why did this code (using
++) not give me the value I expected?", and someone marked your question as a duplicate, and sent you here.
This answer tries to answer that question: why did your code not give you the answer you expected, and how can you learn to recognize (and avoid) expressions that will not work as expected.
I assume you've heard the basic definition of C's
++and
--operators by now, and how the prefix form
++xdiffers from the postfix form
x++. But these operators are hard to think about, so to make sure you understood, perhaps you wrote a tiny little test program involving something like
But, to your surprise, this program did not help you understand -- it printed some strange, unexpected, inexplicable output, suggesting that maybe
++does something completely different, not at all what you thought it did.
Or, perhaps you're looking at a hard-to-understand expression like
Perhaps someone gave you that code as a puzzle. This code also makes no sense, especially if you run it -- and if you compile and run it under two different compilers, you're likely to get two different answers! What's up with that? Which answer is correct? (And the answer is that both of them are, or neither of them are.)
As you've heard by now, all of these expressions are undefined, which means that the C language makes no guarantee about what they'll do. This is a strange and surprising result, because you probably thought that any program you could write, as long as it compiled and ran, would generate a unique, well-defined output. But in the case of undefined behavior, that's not so.
What makes an expression undefined? Are expressions involving
++and
--always undefined? Of course not: these are useful operators, and if you use them properly, they're perfectly well-defined.
For the expressions we're talking about what makes them undefined is when there's too much going on at once, when we're not sure what order things will happen in, but when the order matters to the result we get.
Let's go back to the two examples I've used in this answer. When I wrote
the question is, before calling
printf, does the compiler compute the value of
xfirst, or
x++, or maybe
++x? But it turns out we don't know. There's no rule in C which says that the arguments to a function get evaluated left-to-right, or right-to-left, or in some other order. So we can't say whether the compiler will do
xfirst, then
++x, then
x++, or
x++then
++xthen
x, or some other order. But the order clearly matters, because depending on which order the compiler uses, we'll clearly get different results printed by
printf.
What about this crazy expression?
The problem with this expression is that it contains three different attempts to modify the value of x: (1) the
x++part tries to add 1 to x, store the new value in
x, and return the old value of
x; (2) the
++xpart tries to add 1 to x, store the new value in
x, and return the new value of
x; and (3) the
x =part tries to assign the sum of the other two back to x. Which of those three attempted assignments will "win"? Which of the three values will actually get assigned to
x? Again, and perhaps surprisingly, there's no rule in C to tell us.
You might imagine that precedence or associativity or left-to-right evaluation tells you what order things happen in, but they do not. You may not believe me, but please take my word for it, and I'll say it again: precedence and associativity do not determine every aspect of the evaluation order of an expression in C. In particular, if within one expression there are multiple different spots where we try to assign a new value to something like
x, precedence and associativity do not tell us which of those attempts happens first, or last, or anything.
So with all that background and introduction out of the way, if you want to make sure that all your programs are well-defined, which expressions can you write, and which ones can you not write?
These expressions are all fine:
These expressions are all undefined:
And the last question is, how can you tell which expressions are well-defined, and which expressions are undefined?
As I said earlier, the undefined expressions are the ones where there's too much going at once, where you can't be sure what order things happen in, and where the order matters:
As an example of #1, in the expression
there are three attempts to modify `x.
As an example of #2, in the expression
we both use the value of
x, and modify it.
So that's the answer: make sure that in any expression you write, each variable is modified at most once, and if a variable is modified, you don't also attempt to use the value of that variable somewhere else.
@alinsoar 2017-10-13 13:58:04
A good explanation about what happens in this kind of computation is provided in the document n1188 from the ISO W14 site.
I explain the ideas.
The main rule from the standard ISO 9899 that applies in this situation is 6.5p2.
The sequence points in an expression like
i=i++are before
i=and after
i++.
In the paper that I quoted above it is explained that you can figure out the program as being formed by small boxes, each box containing the instructions between 2 consecutive sequence points. The sequence points are defined in annex C of the standard, in the case of
i=i++there are 2 sequence points that delimit a full-expression. Such an expression is syntactically equivalent with an entry of
expression-statementin the Backus-Naur form of the grammar (a grammar is provided in annex A of the Standard).
So the order of instructions inside a box has no clear order.
can be interpreted as
or as
because both all these forms to interpret the code
i=i++are valid and because both generate different answers, the behavior is undefined.
So a sequence point can be seen by the beginning and the end of each box that composes the program [the boxes are atomic units in C] and inside a box the order of instructions is not defined in all cases. Changing that order one can change the result sometimes.
EDIT:
Other good source for explaining such ambiguities are the entries from c-faq site (also published as a book) , namely here and here and here .
@haccks 2017-11-24 07:00:15
How this answer added new to the existing answers? Also the explanations for
i=i++is very similar to this answer.
@alinsoar 2017-11-24 12:14:44
@haccks I did not read the other answers. I wanted to explain in my own language what I learned from the mentioned document from the official site of ISO 9899 open-std.org/jtc1/sc22/wg14/www/docs/n1188.pdf
@supercat 2012-12-05 18:30:27
While it is unlikely that any compilers and processors would actually do so, it would be legal, under the C standard, for the compiler to implement "i++" with the sequence:
While I don't think any processors support the hardware to allow such a thing to be done efficiently, one can easily imagine situations where such behavior would make multi-threaded code easier (e.g. it would guarantee that if two threads try to perform the above sequence simultaneously,
iwould get incremented by two) and it's not totally inconceivable that some future processor might provide a feature something like that.
If the compiler were to write
i++as indicated above (legal under the standard) and were to intersperse the above instructions throughout the evaluation of the overall expression (also legal), and if it didn't happen to notice that one of the other instructions happened to access
i, it would be possible (and legal) for the compiler to generate a sequence of instructions that would deadlock. To be sure, a compiler would almost certainly detect the problem in the case where the same variable
iis used in both places, but if a routine accepts references to two pointers
pand
q, and uses
(*p)and
(*q)in the above expression (rather than using
itwice) the compiler would not be required to recognize or avoid the deadlock that would occur if the same object's address were passed for both
pand
q.
@Muhammad Annaqeeb 2017-06-10 22:56:26
The reason is that the program is running undefined behavior. The problem lies in the evaluation order, because there is no sequence points required according to C++98 standard ( no operations is sequenced before or after another according to C++11 terminology).
However if you stick to one compiler, you will find the behavior persistent, as long as you don't add function calls or pointers, which would make the behavior more messy.
So first the GCC: Using Nuwen MinGW 15 GCC 7.1 you will get:
}
How does GCC work? it evaluates sub expressions at a left to right order for the right hand side (RHS) , then assigns the value to the left hand side (LHS) . This is exactly how Java and C# behave and define their standards. (Yes, the equivalent software in Java and C# has defined behaviors). It evaluate each sub expression one by one in the RHS Statement in a left to right order; for each sub expression: the ++c (pre-increment) is evaluated first then the value c is used for the operation, then the post increment c++).
according to GCC C++: Operators
the equivalent code in defined behavior C++ as GCC understands:
Then we go to Visual Studio. Visual Studio 2015, you get:
How does visual studio work, it takes another approach, it evaluates all pre-increments expressions in first pass, then uses variables values in the operations in second pass, assign from RHS to LHS in third pass, then at last pass it evaluates all the post-increment expressions in one pass.
So the equivalent in defined behavior C++ as Visual C++ understands:
as Visual Studio documentation states at Precedence and Order of Evaluation:
@Antti Haapala 2017-10-21 10:46:50
I've edited the question to add the UB in evaluation of function arguments, as this question is often used as a duplicate for that. (The last example)
@Antti Haapala 2017-10-21 10:47:24
Also the question is about c now, not C++
@haccks 2015-06-27 00:27:48
Most of the answers here quoted from C standard emphasizing that the behavior of these constructs are undefined. To understand why the behavior of these constructs are undefined, let's understand these terms first in the light of C11 standard:
Sequenced: (5.1.2.3)
Unsequenced:
Evaluations can be one of two things:
Sequence Point:
Now coming to the question, for the expressions like
standard says that:
6.5 Expressions:
Therefore, the above expression invokes UB because two side effects on the same object
iis unsequenced relative to each other. That means it is not sequenced whether the side effect by assignment to
iwill be done before or after the side effect by
++.
Depending on whether assignment occurs before or after the increment, different results will be produced and that's the one of the case of undefined behavior.
Lets rename the
iat left of assignment be
iland at the right of assignment (in the expression
i++) be
ir, then the expression be like
An important point regarding Postfix
++operator is that:
It means the expression
il = ir++could be evaluated either as
or
resulting in two different results
1and
2which depends on the sequence of side effects by assignment and
++and hence invokes UB.
@unwind 2009-06-04 09:20:59
C has the concept of undefined behavior, i.e. some language constructs are syntactically valid but you can't predict the behavior when the code is run.
As far as I know, the standard doesn't explicitly say why the concept of undefined behavior exists. In my mind, it's simply because the language designers wanted there to be some leeway in the semantics, instead of i.e. requiring that all implementations handle integer overflow in the exact same way, which would very likely impose serious performance costs, they just left the behavior undefined so that if you write code that causes integer overflow, anything can happen.
So, with that in mind, why are these "issues"? The language clearly says that certain things lead to undefined behavior. There is no problem, there is no "should" involved. If the undefined behavior changes when one of the involved variables is declared
volatile, that doesn't prove or change anything. It is undefined; you cannot reason about the behavior.
Your most interesting-looking example, the one with
is a text-book example of undefined behavior (see Wikipedia's entry on sequence points).
@PiX 2009-06-04 09:42:37
I knew it was undefined, (The idea of seing this code in production frighten me :)) but I tried to understand what was the reason for these results. Especially why u = u++ incremented u. In java for example: u = u++ returns 0 as (my brain) expected :) Thanks for the sequence points links BTW.
@ChrisBD 2009-06-04 10:21:25
Obviously because of the brackets around the u++ the compiler has decided to incerement u and then return it. As it is undefined behaviuor in C this is ligitimate. A different compiler or even a different machine and the same one may give a different answer. I do not know java, but perhaps the behaviour is clearly defined.
@Richard 2009-06-04 10:57:18
@PiX: Things are undefined for a number of possible reasons. These include: there is no clear "right result", different machine architectures would strongly favour different results, existing practice is not consistent, or beyond the scope of the standard (e.g. what filenames are valid).
@Laurence Gonsalves 2012-07-30 16:19:24
@PiX Java goes out of its way to have defined behaviors for many things that are undefined in C.
@Pascal Cuoq 2012-11-17 19:01:37
@PaulManta, If you see this, editing answers is not intended for the addition of irrelevant information to already-accepted answers. This is a C question and the answer was fine as it was to describe the situation in C standards from C90 to C11. Editing is for fixing syntax and style.
@user3124504 2014-03-22 11:13:37
unwind you called it undefined behaviour, but is there any explanation for why it is so?
@unwind 2014-03-22 20:01:45
@rusty Not sure what you mean. The term "undefined behavior" is used in the C standard. It means that even though some constructs are syntactically valid and will typically compile, they lead to undefine behavior i.e. they do not make sense and should be avoided since your program is broken if it has undefined behavior.
@M.M 2014-07-10 05:51:00
Just to confuse everyone, some such examples are now well-defined in C11, e.g.
i = ++i + 1;.
@Shafik Yaghmour 2014-07-14 01:18:59
@MattMcNabb that is only well defined in C++11 not in C11.
@Antti Haapala 2017-10-21 10:46:00
I've edited the question to add the UB in evaluation of function arguments, as this question is often used as a duplicate for that. (The last example)
@supercat 2017-12-17 23:12:29
Reading the Standard and the published rationale, It's clear why the concept of UB exists. The Standard was never intended to fully describe everything a C implementation must do to be suitable for any particular purpose (see the discussion of the "One Program" rule), but instead relies upon implementors' judgment and desire to produce useful quality implementations. A quality implementation suitable for low-level systems programming will need to define the behavior of actions that wouldn't be needed in high-end number crunching.applications. Rather than try to complicate the Standard...
@supercat 2017-12-17 23:15:59
...by getting into extreme detail about which corner cases are or are not defined, the authors of the Standard recognized that implementors should be better paced to judge which kinds of behaviors will be needed by the kinds of programs they're expected to support. Hyper-modernist compilers pretend that making certain actions UB was intended to imply that no quality program should need them, but the Standard and rationale are inconsistent with such a supposed intent.
@jrh 2018-01-03 17:56:24
@supercat Well put, I'd recommend adding that to your answer.
@supercat 2018-01-03 18:08:20
@jrh: I wrote that answer before I'd realized how out of hand the hyper-modernist philosophy had gotten. What irks me is the progression from "We don't need to officially recognize this behavior because the platforms where it's needed can support it anyway" to "We can remove this behavior without providing a usable replacement because it was never recognized and thus any code needing it was broken". Many behaviors should have been deprecated long ago in favor of replacements that were in every way better, but that would have required acknowledging their legitimacy.
@pqnet 2018-07-04 13:55:19
Undefined behavior basically allows the compiler to make more assumption about conditions which can only be verified at runtime, e.g. assume that in the expression
*ptrthe pointer is valid, because if it is null the program is allowed to do anything and so it is not necessary to add code to the program to check for that condition and ensure a defined behavior.
@David R Tribble 2018-07-31 20:39:04
A the time that C was standardized (1989), many C compilers existed, and each one played by slightly different rules. The primary goal of the ANSI (and later ISO) committee was to codify existing practice. Thus in many cases where multiple compilers disagreed on the "correct" semantic behavior for obviously ambiguous cases (mostly having to do with the evaluation order of expression operators), the committee (wisely) chose to deem such cases as "undefined behavior" or "implementation defined behavior".
@iBug 2018-10-08 01:33:20
If I write
b = (++a)+(++a)+(++a), is the value of
awell-defined?
@stillanoob 2018-10-13 12:16:01
@unwind For
u=1; u=u++;, is it true that what's undefined is the value of
uafter the second statement is executed? I mean, by the rules of sequencing of value evaluation (as opposed to the side-effect evaluation), the expression
u=u++must be guaranteed to evaluate to
1, right?
@Ilmari Karonen 2019-01-31 15:55:02
@stillanoob: No, because the behavior of any code containing that expression is undefined, meaning that it can do literally anything. It might always evaluate to 42, except on Sundays when the moon is waxing gibbous. It might get stuck in an infinite loop instead of evaluating to anything at all. It might jump to a random location in your code. It might crash the process. It might even make your computer catch fire and make demons fly out of your nose, and the C standard still wouldn't care.
@Rajesh 2019-04-01 00:54:25
I understand variable cannot get updated more than once within a sequence point and hence i=i++ is undefined. But why b= i++ + i is also undefined? Here i is not getting updated more than once and I get compiler warning for this too.
@unwind 2019-04-01 08:42:19
@Rajesh Because the operator
+is not a sequence point. Please read the Wikipedia page.
@TomOnTime 2015-04-08 03:20:31
In someone asked about a statement like:
which prints 7... the OP expected it to print 6.
The
++iincrements aren't guaranteed to all complete before the rest of the calculations. In fact, different compilers will get different results here. In the example you provided, the first 2
++iexecuted, then the values of
k[]were read, then the last
++ithen
k[].
Modern compilers will optimize this very well. In fact, possibly better than the code you originally wrote (assuming it had worked the way you had hoped).
@Nikhil Vidhani 2014-09-11 12:36:41
The C standard says that a variable should only be assigned at most once between two sequence points. A semi-colon for instance is a sequence point.
So every statement of the form:
and so on violate that rule. The standard also says that behavior is undefined and not unspecified. Some compilers do detect these and produce some result but this is not per standard.
However, two different variables can be incremented between two sequence points.
The above is a common coding practice while copying/analysing strings.
@underscore_d 2016-07-19 18:55:58
Of course it doesn't apply to different variables within one expression. It would be a total design failure if it did! All you need in the 2nd example is for both to be incremented between the statement ending and the next one beginning, and that's guaranteed, precisely because of the concept of sequence points at the centre of all this.
@badp 2010-05-24 13:26:05
Just compile and disassemble your line of code, if you are so inclined to know how exactly it is you get what you are getting.
This is what I get on my machine, together with what I think is going on:
(I... suppose that the 0x00000014 instruction was some kind of compiler optimization?)
@bad_keypoints 2012-09-24 14:11:42
how do i get the machine code? I use Dev C++, and i played around with 'Code Generation' option in compiler settings, but go no extra file output or any console output
@badp 2012-09-24 18:20:05
@ronnieaka
gcc evil.c -c -o evil.binand
gdb evil.bin→
disassemble evil, or whatever the Windows equivalents of those are :)
@kchoi 2013-09-20 16:07:50
is -0x4(%ebp) = 4 at the end?
@Shafik Yaghmour 2014-07-01 14:00:21
This answer does not really address the question of
Why are these constructs undefined behavior?.
@badp 2014-07-01 16:27:17
@ShafikYaghmour I'm addressing the questions in the question body ("why am I not getting the results I am getting?"), see the comments in the code. Given that this is undefined behaviour, I can only show how to get the actual assembly he's compiled.
@Shafik Yaghmour 2014-07-01 18:12:59
Perhaps the answer is in there but I think most would not be able to figure it out without some elaboration. Just add some explanatory text and it becomes an answer.
@badp 2014-07-01 23:21:25
@ShafikYaghmour I must admit that the assembly is kinda baffling me; especially the instruction at +20. But why am I trying to make sense of it?
@Kat 2015-07-27 20:32:11
As an aside, it'll be easier to compile to assembly (with
gcc -S evil.c), which is all that's needed here. Assembling then disassembling it is just a roundabout way of doing it.
@Steve Summit 2016-02-16 21:26:07
For the record, if for whatever reason you're wondering what a given construct does -- and especially if there's any suspicion that it might be undefined behavior -- the age-old advice of "just try it with your compiler and see" is potentially quite perilous. You will learn, at best, what it does under this version of your compiler, under these circumstances, today. You will not learn much if anything about what it's guaranteed to do. In general, "just try it with your compiler" leads to nonportable programs that work only with your compiler.
@Shafik Yaghmour 2013-08-15 19:25:21
The behavior can't really be explained because it invokes both unspecified behavior and undefined behavior, so we can not make any general predictions about this code, although if you read Olve Maudal's work such as Deep C and Unspecified and Undefined sometimes you can make good guesses in very specific cases with a specific compiler and environment but please don't do that anywhere near production.
So moving on to unspecified behavior, in draft c99 standard section
6.5paragraph 3 says(emphasis mine):
So when we have a line like this:
we do not know whether
i++or
++iwill be evaluated first. This is mainly to give the compiler better options for optimization.
We also have undefined behavior here as well since the program is modifying variables(
i,
u, etc..) more than once between sequence points. From draft standard section
6.5paragraph 2(emphasis mine):
it cites the following code examples as being undefined:
In all these examples the code is attempting to modify an object more than once in the same sequence point, which will end with the
;in each one of these cases:
Unspecified behavior is defined in the draft c99 standard in section
3.4.4as:
and undefined behavior is defined in section
3.4.3as:
and notes that:
@Christoph 2009-06-04 09:35:47
I think the relevant parts of the C99 standard are 6.5 Expressions, §2
and 6.5.16 Assignment operators, §4:
@supercat 2011-11-20 21:41:25
Would the above imply that 'i=i=5;" would be Undefined Behavior?
@dhein 2013-09-23 15:39:50
@supercat as far as I know
i=i=5is also undefined behavior
@supercat 2013-09-23 16:18:26
@Zaibis: The rationale I like to use for most places rule applies that in theory a mutli-processor platform could implement something like
A=B=5;as "Write-lock A; Write-Lock B; Store 5 to A; store 5 to B; Unlock B; Unock A;", and a statement like
C=A+B;as "Read-lock A; Read-lock B; Compute A+B; Unlock A and B; Write-lock C; Store result; Unlock C;". That would ensure that if one thread did
A=B=5;while another did
C=A+B;the latter thread would either see both writes as having taken place or neither. Potentially a useful guarantee. If one thread did
I=I=5;, however, ...
@supercat 2013-09-23 16:19:57
... and the compiler didn't notice that both writes were to the same location (if one or both lvalues involve pointers, that may be hard to determine), the generated code could deadlock. I don't think any real-world implementations implement such locking as part of their normal behavior, but it would be permissible under the standard, and if hardware could implement such behaviors cheaply it might be useful. On today's hardware such behavior would be way too expensive to implement as a default, but that doesn't mean it would always be thus.
@dhein 2013-09-23 16:40:45
@supercat but wouldn't the sequence point access rule of c99 alone be enough to declare it as undefined behavior? So it doesn't matter what technically the hardware could implement?
@supercat 2013-09-23 16:48:53
@Zaibis: Rules which characterize actions as Undefined Behavior aren't supposed to exist merely to allow implementations to behave in hostile fashion. They're supposed to exist to allow implementers to either do something more efficiently or more usefully than would be possible in their absence. To understand why the specs characterize something as UB, it's helpful to identify something useful the rule would allow implementations to do which they otherwise could not.
@dhein 2013-09-23 16:56:34
@supercat I absolutly agree to that what you say about the behavior of undefined behavior(^^). But this doesn't change the point that if something is in the standard listed as UB you can expect, it is well defined just because it would be easy to implement as well defined construct. If the standard says it is UB, then the answer to the question is it UB? is "Yes!", and not "It could... [...]".
@supercat 2013-09-23 17:49:17
@Zaibis: The answer to almost any question of the form "Why is X in language/framework Y Undefined Behavior" is "Because that's what the standard for Y says", but that's hardly enlightening. In most cases, however, what someone asking such a question really wants to know is "Why did the makers of the standard specify that". In most cases, things are specified as UB (rather than partially-specified behaviors) to allow for the possibility of an implementation which might do something unexpected. For example, the spec could have said that
p1=malloc(4); p2=malloc(5); r=p1>p2;...
@supercat 2013-09-23 17:55:26
...may result in
rarbitrarily holding 1 or 0, with no guarantee that the value will relate in any way to future comparisons among the same or different operands. Such a spec (returning an arbitrary 0 or 1) would have allowed an efficient
memmoveto be written in portable fashion [if
dest > src, apply a top-down copy, else bottom-up; if the regions don't overlap, either will work so the comparison result wouldn't matter]. I believe the standard says such comparison is UB, however; if every machine could easily--at worst--arbitrarily yield a 0 or 1, there'd be no reason not to say so. | https://tutel.me/c/programming/questions/949433/why+are+these+constructs+using+pre+and+postincrement+undefined+behavior | CC-MAIN-2019-43 | refinedweb | 6,728 | 58.42 |
Iterating over lines in multiple Linux log files using Python
I needed to parse through my Nginx log files to debug a problem. However, the logs are separated into many files, most of them are gzipped, and I wanted the ordering within the files reversed. So I abstracted the logic to handle this into a function. Now I can pass a glob pattern such as /var/log/nginx/cache.log* to my function, and iterate over each line in all the files as if they were one file. Here is my function. Let me know if there is a better way to do this.
Update 2010-02-24:To handle multiple log files on a remote host, see my script on github.
import glob import gzip import re def get_lines(log_glob): """Return an iterator of each line in all files matching log_glob. Lines are sorted most recent first. Files are sorted by the integer in the suffix of the log filename. Suffix may be one of the following: .X (where X is an integer) .X.gz (where X is an integer) If the filename does not end in either suffix, it is treated as if X=0 """ def sort_by_suffix(a, b): def get_suffix(fname): m = re.search(r'.(?:\.(\d+))?(?:\.gz)?$', fname) if m.lastindex: suf = int(m.group(1)) else: suf = 0 return suf return get_suffix(a) - get_suffix(b) filelist = glob.glob(log_glob) for filename in sorted(filelist, sort_by_suffix): if filename.endswith('.gz'): fh = gzip.open(filename) else: fh = open(filename) for line in reversed(fh.readlines()): yield line fh.close()
Here is an example run on my machine. It prints the first 15 characters of every 1000th line of all my syslog files.
for i, line in enumerate(get_lines('/var/log/syslog*')): if not i % 1000: print line[:15]
File listing:
$ ls -l /var/log/syslog* -rw-r----- 1 syslog adm 169965 2010 01/23 00:18 /var/log/syslog -rw-r----- 1 syslog adm 350334 2010 01/22 08:03 /var/log/syslog.1 -rw-r----- 1 syslog adm 18078 2010 01/21 07:49 /var/log/syslog.2.gz -rw-r----- 1 syslog adm 16700 2010 01/20 07:43 /var/log/syslog.3.gz -rw-r----- 1 syslog adm 18197 2010 01/19 07:52 /var/log/syslog.4.gz -rw-r----- 1 syslog adm 15737 2010 01/18 07:45 /var/log/syslog.5.gz -rw-r----- 1 syslog adm 16157 2010 01/17 07:54 /var/log/syslog.6.gz -rw-r----- 1 syslog adm 20285 2010 01/16 07:48 /var/log/syslog.7.gz
Results:
Jan 22 23:57:01 Jan 22 14:09:01 Jan 22 03:51:01 Jan 21 17:35:01 Jan 21 14:37:33 Jan 21 08:35:01 Jan 20 22:12:01 Jan 20 11:56:01 Jan 20 01:41:01 Jan 19 15:18:01 Jan 19 04:53:01 Jan 18 18:35:01 Jan 18 08:40:01 Jan 17 22:10:01 Jan 17 11:32:01 Jan 17 01:05:01 Jan 16 14:27:01 Jan 16 04:01:01 Jan 15 17:25:01 Jan 15 08:50:01
This is a very interesting function. I'm just curious why are you ordering your files by their numbers when default ordering obviously gives the same result and saves the regex.
Hi David, I should have used a better example. When the numbering gets up to 10, the ordering returned by glob() is no longer correct. I will update my example. I thought about using a shell command like "ls -t", but thought this way would be better if the file modification times got messed up.
Thanks for the precisions Eliot, I took the habit of padding numbers with 0 to avoid this trap when sorting by alphanumerical order. I still have to remember this when I cannot control the numbering schema though :-/
I do agree that relying on the modification date would be too brittle. | https://www.saltycrane.com/blog/2010/01/iterating-over-lines-multiple-linux-log-files-using-python/ | CC-MAIN-2019-30 | refinedweb | 669 | 74.08 |
I have a static library and it has a class like below in its header file:
namespace MyNameSpace { class MyClass { public: void Something(); }; }
I linked above static library with my another dynamic link library project, and now I can call above function like below:
int Main() { MyNameSpace::MyClass A; A.Something(); }
Although above works fine, I like to use my static library function like below, instead declaring classes:
int Main() { MyNameSpace::Something(); }
But I am wondering about the correct way to do this.
I tried it in static library like:
namespace MyNameSpace { void Something(); }
and after linking static library to the dynamic library, tried to use the function in it like:
MyNameSpace::Something();
But, IntelliSense doesn't see it and I already included my static library's header file and linked it properly.
What I want to do is declare a function in a static library outside classes and make it visible to another projects whose it linked into. In this case, to dynamic library.
Thanks in Advance. | http://www.developersite.org/1002-196-c2b2b | CC-MAIN-2018-22 | refinedweb | 168 | 52.53 |
Table of Contents
- Introduction
- Overview
- Historicals
- Kernel Architectures
- Micro vs Monolithic
- Single Server vs Multi Server
- Multi Server is superior, ...
- The Hurd even more so.
- Mach Inter Process Communication
- How to get a port?
- Example of hurd_file_name_lookup
- Pathname resolution example
- Mapping the POSIX Interface
- File System Servers
- Active vs Passive
- Authentication
- Operations on authentication ports
- Establishing trusted connections
- Password Server
- Process Server
- Filesystems
- Developing the Hurd
- Store Abstraction
- Debian GNU/Hurd
- Status of the Debian GNU/Hurd binary archive
- Status of the Debian infrastructure
- Status of the Debian Source archive
- Debian GNU/Hurd: Good idea, bad idea?
- End
Talk about the Hurd
This talk about the Hurd was written by Marcus Brinkmann for
- OSDEM, Brussels, 4. Feb 2001,
- Frühjahrsfachgespräche, Cologne, 2. Mar 2001 and
- Libre Software Meeting, Bordeaux, 4. Jul 2001.
Introduction removes these restrictions from the user. It provides an user extensible system framework without giving up POSIX compatibility and the unix security model. Throughout this talk, we will see that this brings further advantages beside freedom.
Overview
The Hurd is a POSIX compatible multi-server system operating on top of the GNU Mach Microkernel.
I will have to explain what GNU Mach is, so we start with that. Then I will talk about the Hurd's architecture. After that, I will give a short overview on the Hurd libraries. Finally, I will tell you how the Debian project is related to the Hurd.
Historicals
When Richard Stallman founded the GNU project in 1983, he wanted to write an operating system consisting only of free software. Very soon, a lot of the essential tools were implemented, and released under the GPL. However, one critical piece was missing: The kernel.
After considering several alternatives, it was decided not to write a new kernel from scratch, but to start with the Mach microkernel. This was in 1988, and it was not before 1991 that Mach was released under a license allowing the GNU project to distribute it as a part of the system.
In 1998, I started the Debian GNU/Hurd project, and in 2001 the number of available GNU/Hurd packages fills three CD images.
Kernel Architectures
Microkernels were very popular in the scientific world around that time. They don't implement a full operating system, but only the infrastructure needed to enable other tasks to implement most features. In contrast, monolithical kernels like Linux contain program code of device drivers, network protocols, process management, authentication, file systems, POSIX compatible interfaces and much more.
So what are the basic facilities a microkernel provides? In general, this is resource management and message passing. Resource management, because the kernel task needs to run in a special privileged mode of the processor, to be able to manipulate the memory management unit and perform context switches (also to manage interrupts). Message passing, because without a basic communication facility the other tasks could not interact to provide the system services. Some rudimentary hardware device support is often necessary to bootstrap the system. So the basic jobs of a microkernel are enforcing the paging policy (the actual paging can be done by an external pager task), scheduling, message passing and probably basic hardware device support.
Mach was the obvious choice back then, as it provides a rich set of interfaces to get the job done. Beside a rather brain-dead device interface, it provides tasks and threads, a messaging system allowing synchronous and asynchronous operation and a complex interface for external pagers. It's certainly not one of the sexiest microkernels that exist today, but more like a big old mama. The GNU project maintains its own version of Mach, called GNU Mach, which is based on Mach 4.0. In addition to the features contained in Mach 4.0, the GNU version contains many of the Linux 2.0 block device and network card drivers.
A complete treatment of the differences between a microkernel and monolithical kernel design can not be provided here. But a couple of advantages of a microkernel design are fairly obvious.
Micro vs Monolithic
Because the system is split up into several components, clean interfaces have to be developed, and the responsibilities of each part of the system must be clear.
Once a microkernel is written, it can be used as the base for several different operating systems. Those can even run in parallel which makes debugging easier. When porting, most of the hardware dependant code is in the kernel.
Much of the code that doesn't need to run in the special kernel mode of the processor is not part of the kernel, so stability increases because there is simply less code to break.
New features are not added to the kernel, so there is no need to hold the barrier high for new operating system features.
Compare this to a monolithical kernel, where you either suffer from creeping featuritis or you are intolerant of new features (we see both in the Linux kernel).
Because in a monolithical kernel, all parts of the kernel can access all data structures in other parts, it is more likely that short cuts are used to avoid the overhead of a clean interface. This leads to a simple speed up of the kernel, but also makes it less comprehensible and more error prone. A small change in one part of the kernel can break remote other parts.
Single Server vs Multi Server
There exist a couple of operating systems based on Mach, but they all have the same disadvantages as a monolithical kernel, because those operating systems are implemented in one single process running on top of the kernel. This process provides all the services a monolithical kernel would provide. This doesn't make a whole lot of sense (the only advantage is that you can probably run several of such isolated single servers on the same machine). Those systems are also called single-server systems. The Hurd is the only usable multi-server system on top of Mach. In the Hurd, there are many server programs, each one responsible for a unique service provided by the operating system. These servers run as Mach tasks, and communicate using the Mach message passing facilities. One of them does only provide a small part of the functionality of the system, but together they build up a complete and functional POSIX compatible operating system.
Multi Server is superior, ...
Using several servers has many advantages, if done right. If a file system server for a mounted partition crashes, it doesn't take down the whole system. Instead the partition is "unmounted", and you can try to start the server again, probably debugging it this time with gdb. The system is less prone to errors in individual components, and over-all stability increases. The functionality of the system can be extended by writing and starting new servers dynamically. (Developing these new servers is easier for the reasons just mentioned.)
But even in a multi-server system the barrier between the system and the users remains, and special privileges are needed to cross it. We have not achieved user freedom yet.
The Hurd even more so.
To quote Thomas Bushnell, BSG, from his paper ``Towards a New Strategy of OS design'' (1996):.
So the Hurd is a set of servers running on top of the Mach micro-kernel, providing a POSIX compatible and extensible operating system. What servers are there? What functionality do they provide, and how do they cooperate?
Mach Inter Process Communication
Inter-process communication in Mach is based on the ports concept. A port is a message queue, used as a one-way communication channel. In addition to a port, you need a port right, which can be a send right, receive right, or send-once right. Depending on the port right, you are allowed to send messages to the server, receive messages from it, or send just one single message.
For every port, there exists exactly one task holding the receive right, but there can be no or many senders. The send-once right is useful for clients expecting a response message. They can give a send-once right to the reply port along with the message. The kernel guarantees that at some point, a message will be received on the reply port (this can be a notification that the server destroyed the send-once right).
You don't need to know much about the format a message takes to be able to use the Mach IPC. The Mach interface generator mig hides the details of composing and sending a message, as well as receiving the reply message. To the user, it just looks like a function call, but in truth the message could be sent over a network to a server running on a different computer. The set of remote procedure calls a server provides is the public interface of this server.
How to get a port?
So how does one get a port to a server? You need something like a phone book for server ports, or otherwise you can only talk to yourself. In the original Mach system, a special nameserver is dedicated to that job. A task could get a port to the nameserver from the Mach kernel and ask it for a port (with send right) to a server that registered itself with the nameserver at some earlier time.
In the Hurd, there is no nameserver. Instead, the filesystem is used as the server namespace. This works because there is always a root filesystem in the Hurd (remember that the Hurd is a POSIX compatible system); this is an assumption the people who developed Mach couldn't make, so they had to choose a different strategy. You can use the function hurd_file_name_lookup, which is part of the C library, to get a port to the server belonging to a filename. Then you can start to send messages to the server in the usual way.
Example of hurd_file_name_lookup
As a concrete example, the special filename /servers/password can be used to request a port to the Hurd password server, which is responsible to check user provided passwords.
(explanation of the example)
Pathname resolution example
The C library itself does not have a full list of all available servers. Instead pathname resolution is used to traverse through a tree of servers. In fact, filesystems themselves are implemented by servers (let us ignore the chicken and egg problem here). So all the C library can do is to ask the root filesystem server about the filename provided by the user (assuming that the user wants to resolve an absolute path), using the dir_lookup RPC. If the filename refers to a regular file or directory on the filesystem, the root filesystem server just returns a port to itself and records that this port corresponds to the file or directory in question. But if a prefix of the full path matches the path of a server the root filesystem knows about, it returns to the C library a port to this server and the remaining part of the pathname that couldn't be resolved. The C library than has to retry and query the other server about the remaining path component. Eventually, the C library will either know that the remaining path can't be resolved by the last server in the list, or get a valid port to the server in question.
Mapping the POSIX Interface
It should by now be obvious that the port returned by the server can be used to query the files status, content and other information from the server, if good remote procedure calls to do that are defined and implemented by it. This is exactly what happens. Whenever a file is opened using the C libraries open() call, the C library uses the above pathname resolution to get a port to a server providing the file. Then it wraps a file descriptor around it. So in the Hurd, for every open file descriptor there is a port to a server providing this file. Many other C library calls like read() and write() just call a corresponding RPC using the port associated with the file descriptor.
File System Servers
So we don't have a single phone book listing all servers, but rather a tree of servers keeping track of each other. That's really like calling your friend and asking for the phone number of the blond girl at the party yesterday. He might refer you to a friend who hopefully knows more about it. Then you have to retry.
This mechanism has huge advantages over a single nameserver. First, note that standard unix permissions on directories can be used to restrict access to a server (this requires that the filesystems providing those directories behave). You just have to set the permissions of a parent directory accordingly and provide no other way to get a server port.
But there are much deeper implications. Most of all, a pathname never directly refers to a file, it refers to a port of a server. That means that providing a regular file with static data is just one of the many options the server has to service requests on the file port. A server can also create the data dynamically. For example, a server associated with /dev/random can provide new random data on every io_read() on the port to it. A server associated with /dev/fortune can provide a new fortune cookie on every open().
While a regular filesystem server will just serve the data as stored in a filesystem on disk, there are servers providing purely virtual information, or a mixture of both. It is up to the server to behave and provide consistent and useful data on each remote procedure call. If it does not, the results may not match the expectations of the user and confuse him.
A footnote from the Hurd info manual:
(1) You are lost in a maze of twisty little filesystems, all alike....
Because a server installed in the filesystem namespace translates all filesystem operations that go through its root path, such a server is also called "active translator". You can install translators using the settrans command with the -a option.
Active vs Passive
Many translator settings remain constant for a long time. It would be very lame to always repeat the same couple of dozens settrans calls manually or at boot time. So the Hurd provides a filesystem extension that allows to store translator settings inside the filesystem and let the filesystem servers do the work to start those servers on demand. Such translator settings are called "passive translators". A passive translator is really just a command line string stored in an inode of the filesystem. If during a pathname resolution a server encounters such a passive translator, and no active translator does exist already (for this node), it will use this string to start up a new translator for this inode, and then let the C library continue with the path resolution as described above. Passive translators are installed with settrans using the -p option (which is already the default).
So passive translators also serve as a sort of automounting feature, because no manual interaction is required. The server start up is deferred until the service is need, and it is transparent to the user.
When starting up a passive translator, it will run as a normal process with the same user and group id as those of the underlying inode. Any user is allowed to install passive and active translators on inodes that he owns. This way the user can install new servers into the global namespace (for example, in his home or tmp directory) and thus extend the functionality of the system (recall that servers can implement other remote procedure calls beside those used for files and directories). A careful design of the trusted system servers makes sure that no permissions leak out.
In addition, users can provide their own implementations of some of the system servers instead the system default. For example, they can use their own exec server to start processes. The user specific exec server could for example start java programs transparently (without invoking the interpreter manually). This is done by setting the environment variable EXECSERVERS. The systems default exec server will evaluate this environment variable and forward the RPC to each of the servers listed in turn, until some server accepts it and takes over. The system default exec server will only do this if there are no security implications. (XXX There are other ways to start new programs than by using the system exec server. Those are still available.)
Let's take a closer look at some of the Hurd servers. It was already mentioned that only few system servers are mandatory for users. To establish your identity within the Hurd system, you have to communicate with the trusted systems authentication server auth. To put the system administrator into control over the system components, the process server does some global bookkeeping.
But even these servers can be ignored. However, registration with the authentication server is the only way to establish your identity towards other system servers. Likewise, only tasks registered as processes with the process server can make use of its services.
Authentication
The Hurd auth server is used to establish the identity of a user for a server. Such an identity (which is just a port to the auth server) consists of a set of effective user ids, a set of effective group ids, a set of available user ids and a set of available group ids. Any of these sets can be empty.
Operations on authentication ports
If you have two identities, you can merge them and request an identity consisting of the unions of the sets from the auth server. You can also create a new identity consisting only of subsets of an identity you already have. What you can't do is extending your sets, unless you are the superuser which is denoted by having the user id 0.
Establishing trusted connections
Finally, the auth server can establish the identity of a user for a server. This is done by exchanging a server port and a user identity if both match the same rendezvous port. The server port will be returned to the user, while the server is informed about the id sets of the user. The server can then serve or reject subsequent RPCs by the user on the server port, based on the identity it received from the auth server.
Anyone can write a server conforming to the auth protocol, but of course all system servers use a trusted system auth server to establish the identity of a user. If the user is not using the system auth server, matching the rendezvous port will fail and no server port will be returned to the user. Because this practically requires all programs to use the same auth server, the system auth server is minimal in every respect, and additional functionality is moved elsewhere, so user freedom is not unnecessarily restricted.
Password Server
The password server sits at /servers/password and runs as root. It can hand out ports to the auth server in exchange for a unix password, matching it against the password or shadow file. Several utilities make use of this server, so they don't need to be setuid root.
Process Server
The process server is responsible for some global bookkeeping. As such it has to be trusted and is not replaceable by the user. However, a user is not required to use any of its service. In that case the user will not be able to take advantage of the POSIXish appearance of the Hurd.
The Mach Tasks are not as heavy as POSIX processes. For example, there is no concept of process groups or sessions in Mach. The proc server fills in the gap. It provides a PID for all Mach tasks, and also stores the argument line, environment variables and other information about a process (if the mach tasks provide them, which is usually the case if you start a process with the default fork()/exec()). A process can also register a message port with the proc server, which can then be requested by anyone. So the proc server also functions as a nameserver using the process id as the name.
The proc server also stores some other miscellaneous information not provided by Mach, like the hostname, hostid and system version. Finally, it provides facilities to group processes and their ports together, as well as to convert between pids, process server ports and mach task ports.
Although the system default proc server can't be avoided (all Mach tasks spawned by users will get a pid assigned, so the system administrator can control them), users can run their own additional process servers if they want, implementing the features not requiring superuser privileges.
Filesystems
We already talked about translators and the file system service they provide. Currently, we have translators for the ext2, ufs and iso9660 filesystems. We also have an nfs client and an ftp filesystem. Especially the latter is intriguing, as it provides transparent access to ftp servers in the filesystem. Programs can start to move away from implementing a plethora of network protocols, as the files are directly available in the filesystem through the standard POSIX file interface.
Developing the Hurd
The Hurd server protocols are complex enough to allow for the implementation of a POSIX compatible system with GNU extensions. However, a lot of code can be shared by all or at least similar servers. For example, all storage based filesystems need to be able to read and write to a store medium splitted in blocks. The Hurd comes with several libraries which make it easy to implement new servers. Also, there are already a lot of examples of different server types in the Hurd. This makes writing a new server easier.
libdiskfs is a library that supports writing store based filesystems like ext2fs or ufs. It is not very useful for filesystems which are purely virtual, like /proc or files in /dev.
libnetfs is intended for filesystems which provide a rich directory hierarchy, but don't use a backing store (for example ftpfs, nfs).
libtrivfs is intended for filesystems which just provide a single inode or directory. Most servers which are not intended to provide a filesystem but other services (like /servers/password) use it to provide a dummy file, so that file operations on the servers node will not return errors. But it can also be used to provide meaningful data in a single file, like a device store or a character device.
Store Abstraction
libstore provides a store abstraction, which is used by all store based filesystems. The store is determined by a type and a name, but some store types modify another store rather than providing a new store, and thus stores can be stacked. For example, the device store type expects a Mach device, but the remap store expects a list of blocks to pick from another store, like remap:1+:device:hd2, which would pick all blocks from hd2 but the first one, which skipped. Because this functionality is provided in a library, all libstore using filesystems support many different store kinds, and adding a new store type is enough to make all store based filesystems support it.
Debian GNU/Hurd
The Debian distribution of the GNU Hurd that I started in 1998 is supposed to become a complete binary distribution of the Hurd that is easy to install.
Status of the Debian GNU/Hurd binary archive
See for the most current version of the statistic.
Status of the Debian infrastructure
While good compatibiity can be achieved at the source level, the binary packages can not always express their relationship to the available architectures sufficiently.
For example, the Linux version of makedev is binary-all, where a binary-all-linux relationship would be more appropriate.
More work has to be done here to fix the tools.
Status of the Debian Source archive
Most packages are POSIX compatible and can be compiled without changes on the Hurd. The maintainers of the Debian source packages are usually very kind, responsiver and helpful.
The Turtle autobuilder software () builds the Debian packages on the Hurd automatically.
Debian GNU/Hurd: Good idea, bad idea?
The sheet lists the advantages of all groups involved.
End
List of contacts. | http://www.gnu.org/software/hurd/hurd-talk.html | CC-MAIN-2016-50 | refinedweb | 4,076 | 61.06 |
Name | Synopsis | Description | Return Values | VALID STATES | Errors | TLI COMPATIBILITY | Attributes | See Also
#include <xti.h> int t_rcvv(int fd, struct t_iovec *iov, unsigned int iovcount, int *flags);
This function receives either normal or expedited data. The argument fd identifies the local transport endpoint through which data will arrive, iov points to an array of buffer address/buffer size pairs (iov_base, iov_len). The t_rcvv() function receives data into the buffers specified by iov0.iov_base, iov1.iov_base, through iov [iovcount-1].iov_base, always filling one buffer before proceeding to the next.
Note that the limit on the total number of bytes available in all buffers passed:.
The argument iovcount contains the number of buffers which is limited to T_IOV_MAX, which is an implementation-defined value of at least 16. If the limit is exceeded, the function will fail with TBADDATA.
The argument flags may be set on return from t_rcvv() and specifies optional flags as described below.
By default, t_rcvv() operates in synchronous mode and will wait for data to arrive if none is currently available. However, if O_NONBLOCK is set by means of t_open(3NSL) or fcntl(2), t_rcvv()_rcvv() or t_rcv(3NSL) calls. In the asynchronous mode, or under unusual conditions (for example, the arrival of a signal or T_EXDATA event), the T_MORE flag may be set on return from the t_rcvv() call even when the number of bytes received is less than the total size of all the receive buffers. Each t_rcvv() with the T_MORE flag set indicates that another t_rcvv() must follow to get more data for the current TSDU. The end of the TSDU is identified by the return of a t_rcvv() the amount of buffer space passed in iov is greater than zero on the call to t_rcvv(), then t_rcvv()_rcvv() which will return with T_EXPEDITED set in flags. The end of the ETSDU is identified by the return of a t_rcvv() call with T_EXPEDITED set and T_MORE cleared. If the entire ETSDU is not available it is possible for normal data fragments to be returned between the initial and final fragments of an ETSDU.
If a signal arrives, t_rcvv() returns, giving the user any data currently available. If no data is available, t_rcvv() returns –1, sets t_errno to TSYSERR and errno to EINTR. If some data is available, t_rcvv() via the EM interface.
On successful completion, t_rcvv() returns the number of bytes received. Otherwise, it returns –1 on failure and t_errno is set to indicate the error.
T_DATAXFER, T_OUTREL.
On failure, t_errno is set to one of the following:
iovcount is greater than T_IOV_MAX.:
fcntl(2), t_getinfo(3NSL), t_look(3NSL), t_open(3NSL), t_rcv(3NSL), t_snd(3NSL), t_sndv(3NSL), attributes(5)
Name | Synopsis | Description | Return Values | VALID STATES | Errors | TLI COMPATIBILITY | Attributes | See Also | http://docs.oracle.com/cd/E19253-01/816-5170/6mbb5et6a/index.html | CC-MAIN-2015-35 | refinedweb | 459 | 52.9 |
Stallman Critical of OSDL Patent Project 226
PatPending writes to mention a News.com article about Richard Stallman's objections to the OSDL patent project. He argues that the project may actually be 'worse than nothing', as it will undermine certain legal tactics. From the article: "'Thus, our main chance of invalidating a patent in court is to find prior art that the Patent Office has not studied,' Stallman wrote. Second, patent applicants could use the prior art uncovered by the OSDL to write patent claims that simply avoid the technologies used in the tagged software. 'The Patent Office is eager to help patent applicants do this,' Stallman wrote. Finally, he wrote, a 'laborious half measure' such as the Open Source as Prior Art project could divert attention from the real problem: that software is patentable in the first place."
Aboslutly correct. (Score:5, Insightful)
Aboslutly correct.
Thank God (Score:2)
Re: (Score:2, Insightful)
I guess I'm going to be one of the people chanting "down with this project" now?
Re: (Score:3, Insightful)
Right now, the problems he was talking about are more real, DRM, and trusted computing are real problems that affect you right now.
He hasn't changed, but the reality did change into what he said it would.
Software patents right now have a harmful effect, but they c
Re:Thank God (Score:5, Interesting)
Drug and hardware patents are also problematic, but the reform had better be well considered, or the cure could be worse than the disease. The specific case of software, however, is one where we can eschew playing without destabilizing the economy too readily.
Moral correctness is not enough (Score:5, Insightful)
Sure, in the long term, and a perfect world, you might want to get rid of software patents. Right now however they are real and are here and measure that combat them face to face have some merit.
Re: (Score:2)
We must continue to point out that it's not only broken, but that software patents are a mistake to begin with.
You don't need the perfect world, you need to put in the efforts to take political steps to see that congress ends software patents.
Re: (Score:3, Interesting)
Indeed. Look at crypto export regulations. A lot of people now think that cryptography isn't meaningfully regulated, but in reality, only mass-market software is free from the onerous restrictions. If you start selling, say, a secure wireless keyboard over the Internet, you can still be charged with a crime. (Why do you think there are *still* no actually-secure wireless keyboards on the market?)
Re: (Score:3, Interesting)
-1 Analogy
No it's not like that at all. It's not like anything, except the plain statement that patents, designed for finite, physical objects, should not be applied to infinitely reproducible items like software.
Software is not a house, a car or any other physical thing. Please stop pretending it is.
Re: (Score:3, Insightful)
Re:Moral correctness is not enough (Score:4, Insightful)
Because chances are the algorithm you created was most likely neither novel nor unique to the large amounts of algorithms created before you. As in... Your algorithm had to be based on some math that everyone knows or at the most an obscure math professor came up with years ago.
You aren't writing your own language but taking from knowledge of mankind and applying it to your own methods.
Secondly, copyrights protect someone from copying your code, but not your methods because if someone can simply recreate your algorithm simply by looking at the results and not even see any of your source code then again... your algorithm was neither novel nor unique and therby not deserve a patent.
However, your effort and code should be copyrighted and protected by such methods.
Re:Moral correctness is not enough (Score:5, Insightful)
Re: (Score:2)
Re: (Score:3, Insightful)
Re:Moral correctness is not enough (Score:4, Insightful)
----
Freedom is on the March! [movingtofreedom.org]
Re: (Score:2)
I also beleive that patents in regards to software don't fit the timeframe for patents on physical devices. It would be a far different situation if patents were only valid on software concepts for 3-5 years opposed to 20.
I would seriously challenge anyone to name a software concept from the past 20 years that doesn't h
OK (Score:2)
Re:Moral correctness is not enough (Score:5, Funny)
Re:Moral correctness is not enough (Score:5, Insightful)
The same reason you spend time writing software at all (that others with more resources may duplicate and undercut): The new algorithm solves a particular need of yours. It is useful.
This is why Sir Charles Hoare created the quicksort in 1960. It probably didn't even occur to him that this was something he should prevent others from using, and he still found it useful to invent. Thank God he did not -- could not -- patent it, or it would have been over a decade before people could have taken free advantage of the fastest-average-time general sorting algorithm known today. Imagine everyone else had been doing the same thing -- locking up merge sort, bin sort, r/b binary trees, avl binary trees, b-trees, etc etc. With all these foundations of computer science locked up in patents for 14-20 years, how much progress do you think the software world would have made compared to what it did with free access to all these ideas? Remember, we're talking about a fourth of the entire existence of computers.
Why does software not being a physical object make it less suitable to be patented?
Because software is math.
That's all it is. A program is just a series of mathematical operations performed by a computer. Now the computer is an invention. But the software is just a calculation. Patenting a software algorithm is like patenting a sequence of button pushes on your calculator, and by "like" I mean "is very literally the same".
Imagine if Sir Issac Newton had decided to lock away his Calculus? He might have had some legal troubles from Leibniz, but once they came to an amicable arangement, everyone else would have been out of luck. Is Calculus not a great invention? Of course! But like all math, it is an invention whose benefit comes from what could be built upon it. Thank goodness that Newton published his book and did not restrict others from using what it described, or you have to wonder where we'd be today.
Why shouldn't software be patentable? Because it's a patent on math, the fundamental language of the universe.
Re: (Score:2)
Re: (Score:3, Insightful)
Given patents are restrictions, patents are only allowed to exist where necessary, and solely for the "greater good" of society.
Without patents there would be no protection for inventors' inventions, so the theory says they wouldn't invent anything, and society would suffer.
Large businesses already have large cash reserves and an infra
Re: (Score:3, Insightful)
Except you don't have to reduce software to simpler elements to call it math.
Software is math, in the same way that "3 * y^2 + (7 / 6)x = z" is math.
Now you may argue that "3 * y^2 + (7 / 6)x" is actually a series of characters that represent math, but again, that's exactly the same as software. Software is a machine-readable representation of a series of mathematical statements, while the equation
Re: (Score:3, Interesting)
Your argument is effectively saying that it wouldn't. After all, it's just maths, right? Anyone can do it and we know it all already, so there's no no need to incentivise new research.
What? You think I'm arguing that neither math nor its reliable and spe
Re: (Score:2)
Because there are laws covering ideas and, however wrong they might be, they pass the test of applicability. Ultimately, patents were designed to present the rapid duplication of physical objects (and explicitly not ideas).
I'll get to development costs i
Re: (Score:2)
It is quite easy to bring the product to fore, in case of software.
Re: (Score:2)
Re: (Score:2)
The advantage you should (and naturally) have is that you can put the product into production and profit from it before anyone else--sometimes that is all it takes to achieve market dominance. If you invent a new type of software, you will be the originator that everyone will see as the genuine thing or real deal. By the time others copy it, you'll have improved the product for the next release of the software. Why do you think even though there are tons of iPod knockoffs that iPods are still unrivaled as t
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
It not anything nearly that general. Or, at least, we don't know that it is. What we know is that we've tried applying patents to software, and over the last few decades, it's proven to be detrimental.
Personally, I think you should be able to file a patent on nearly any invention, but patents should be
Re: (Score:2)
Does the problem still exist? Yes.
Does the law firm help? YesI would call it a "better than nothing" measure but I wouldn't call it a solution.
Re: (Score:2)
Sure, in the long term, and a perfect world, you might want to get rid of software patents. Right now however they are real and are here and measure that combat them face to face have some merit.
IMHO, a closer analogy to Stallman's position would be: "it's like saying people shouldn't spend money on wireless home security cameras if it makes them neglect securing their windows and doors, and particularly if it will make them even le
Where is your counterargument? (Score:2)
Re:Aboslutly correct. (Score:4, Insightful)
We are two months from an important mid-term election, two years from a presidential election. Patent reform ranks somewhere below The Bridge to Nowhere on the national political agenda.
Re: (Score:2)
Considering how patenting software is stifling innovation, I consider it pretty important.
"Aboslutly "
you know, I proof read that and still screwed it up. sigh.
Re: (Score:2)
The thing is, you have to be realistic. You might see a slightly more centrist Congress after November. But that is all you are likely to see.
Absolutism is impractical (Score:4, Insightful)
If not, how many ideas do we want to see slip into proprietary hands while we maintain our moral purism about software patents? This is a political issue, and political agendas live, eat, sleep & breathe half-measures. According to Stallman, "If we are not careful, this can sap the pressure for a real solution." Erm, what pressure? Where is the well-funded, politically connected lobby that's creating more pressure for a Real Solution than beneficiaries of software patents can create in the opposite direction? `Cause short of that, we all know that we're not going to see a Real Solution anytime soon.
IMO, the idea of "Open Source as Prior Art" is basically a good one that needs some tweaking. If Stallman is correct (and I have no way of knowing whether he is) that "when prior art is considered by the Patent Office during the patent-granting process, it usually loses any weight it might have had in a court case," then that might be a problem. However, I can't understand how patent holders of a variation on an OSDL-tagged thingamabob could (a) claim their idea is patentable because of some variation, and still (b) go after the FOSS-derived works. Wouldn't the very granting of the patent in spite of the OSDL art be the basis for establishing non-infringement?
Stallman wants the very idea of ideas to be irrevocably tied to freedom. That's a beautiful vision, and God bless him if he can ever pull it off; I'm (sadly) not optimistic. Meanwhile, I'll settle for having as many of them as possible stay clean from proprietary claims. Failing both, anonymous/pseudonymous coding & releasing might be our only refuge.
Not entirely (Score:2)
It is correct as far as it goes, but what he's failing to realize is what is in place today.
In an ideal world, software wouldn't be patentable. But we don't live in an ideal world. Therefore, it might be good to deal with the situation at hand first.
That may be true... (Score:2)
After gathering enough evidence (while, at the same time, actually protecting people from lawsuits), we will win either by actually educating patent officers to the point where it's no longer fashionable to patent a system for swinging on a swing, or something even more ridiculous in
Stallman... half right (Score:3, Insightful)
Re:Stallman... half right (Score:4, Insightful)
I don't believe anything which could be described as an algorithm should be patentable. I also don't believe that you should patent public API's, as such "programming interfaces" are by definition intended for use by other programs; public APIs normally are widely distributed in documentation, which at least prevents others from patenting the APIs which you might release (as your release will obviously constitute prior art). I suppose that if you implement computer software which is sufficiently original, not completely obvious after 5 minutes of thought, and is not representable as a mathematical algorithm, that might deserve the protection of a patent, but for the most part, simple copyright ought to provide enough protection....
Re: (Score:2, Interesting)
I suppose that if you implement computer software which is sufficiently original, not completely obvious after 5 minutes of thought, and is not representable as a mathematical algorithm, that might deserve the protection of a patent
So was everyone asleep in that part of computational theory where they point out that everything (including hardware) is reducible to a mathematical algorithm?
Re: (Score:3, Interesting)
In theory, perhaps. More accurately, ideal hardware can be represented or modelled by mathematical algorithms, but real-world hardware exhibits a number of differences from ideal models, including non-perfect TTL response: real transistors aren't ideal binary on-off devices and exhibit non-linear behavior especially as they heat up or run outside of
Re: (Score:2)
Perhaps it's cheaper in the short term, but if letting the worst 10% of software patents go through annoys enough people that we're able to get rid of all software patents, or the worst 90%, it would be cheaper in the long run to allow obvious "spam patents".
What's broken: the obvious "spam patents" or the system that approves
If your kitchen counter was on fire... (Score:3, Insightful)
Bad Analogies aplenty in this thread (Score:3, Insightful)
Ooh! Let me try! (Score:5, Funny)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2, Funny)
Re: (Score:2)
Re: (Score:3, Funny)
Or is it more like starting a fire in my house without locks on the doors or windows?
Or, wait, maybe it's like setting my lock on fire and waiting for a bunch of people or organizations to pour water into new fireproofing techniques?
Or maybe it's more like a car where the hood is welded shut and a fire starts inside it and yo
Re:If your kitchen counter was on fire... (Score:4, Insightful)
Playing the odds (Score:4, Interesting)
I'd bet on RMS, smelly hippy though he is, being right in the mid to long term, if for no other reason than he hasn't (to the best of my knowledge) been wrong yet. In any prediction. Ever.
In purely practical terms, the OSDL patent project is like trying to put out a burning forest by standing close enough to sweat on it.
Have you read what RMS writes? (Score:2)
c
Re:Playing the odds (Score:5, Funny)
Re: (Score:2)
Re: (Score:3, Insightful)
Re: (Score:3, Funny)
Re: (Score:2)
Re: (Score:3, Funny)
So would I.
Re: (Score:2)
Re: (Score:2)
...but with blackjack? And hookers?
Re: (Score:2)
Your over-sensitivity is silly. I'm an RMS fanboy; I've traded emails with him on numerous occasions, and he even congratulated me on writing my daughter's birth announcement in C and GPLing it. Still, RMS is the archetype of the smelly hippie hacker. That's a factual observation and not some random insult.
Re:Playing the odds (Score:5, Funny)
---- baby.c ----
/* This code is distributable under the terms of the GPL. However, I *
* retain full rights to its output for up to eighteen years. */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void main()
{
void *a = malloc((size_t) weight);
sleep(270 * 24 * 60 * 60);
if (fork())
{
free(a);
my.weight -= 20;
wait();
}
else
{
my.length = 18; /* Inches */
my.weight = 101;
printf("Hello, world!\n");
}
}
--------
Re: (Score:2)
You just took a wrong turn, dude.
Oh! You're just a troll. If that was a bombshell (him being opposed to software patents, not "intelle
no patents != no IP protection (Score:2)
Ever heard of copyright? It's part of what's called 'intellectual property' as are trademarks. Being anti-software patents is not saying programmers can't protect their IP, many people believe that copyright does this adequately and patents are inappropriate for software IP protection. Just like saying that books shouldn't be patented is not an attack on authors IP rights.
Re: (Score:2)
Better than that? You don't seem to be really aware of copyrights as IP protection for software, so let's revisit the topic being addressed again then:
You wrote [slashdot.org] "Then Stallman drops the bombshell: he doesn't believe a software developer should have any right to protect its intellectual property in the f
patent GPL? (Score:5, Interesting)
Re: (Score:2)
Actually I think you are right (and I think the OSDL is doing the right thing), problem is there is no other way. If there was a way seperate from what the OSDL is doing then great. I don't think there is. I don't think that the establishment will allow change as massive as abolishing SW patents. Next best thing is a Db that demonstrates that everything is enough a deritive of prior art as to not be patentable.
-nB
Re: (Score:3, Insightful)
Re: (Score:2)
This is a cop-out argument. If you write software and choose not to protect it, the copyright is meanlingless. Putting a copyright notice on your software and thus signaling to the world that you intend to protect it (as RMS does) is just as active an act as filing for a patent.
Re:patent GPL? (Score:5, Insightful)
Stallman's issue isn't with copyright - his issue is with people not voluntarily giving up their code to the community. He is all for copyright and ownership of code. His problem is that software is not something you should be able to patent, and that the OSDL initiative distracts from this point.
Re: (Score:2)
Sure you can... IF the patent-holder allows you to do so. That is OSDL's goal.
Oh yes it is [gnu.org]. In particular, his issue is that copyrights were meant as a concession to artists & inventors to further the public good. The public gives up its freedom to use certain arts, ideas, and inventions for a short period of time in exchange for making those things public knowledge. But nowa
Re: (Score:2)
But that's the whole problem - people shouldn't be allowed to have that kind of power over software. Having a law you disagree with shouldn't be fixed by begging people not to enforce it. That kind of goal puts us at the mercy of patent holders. If you agree with Stallman, and think that software patents are bad in part because it means you can't make free software without violating patents, that basically makes the entire free so
Re: (Score:2)
Suggesting that RMS should deal with patent laws the same way he dealt with copyright laws is like suggesting he use a plunger to extinguish a kitchen fire since clogged drains and kitchen fires are both "household problems".
The GPL allows software authors to publish and distribute their software in a
Re: (Score:2)
Stallman and the FSF -aren't- against software copyrights as a matter of principle. He does call for reducing the length of copyright and the scope of what it can restrict, but not for an outright abolition. On the other hand, the FSF (and incidentally I agree) regards patents as inappropriate in any case involving software. That is, in fact, their position-software should be eligible only for copyright, never for patents.
You can read more here, [gnu.org] which probably explains it a lot more thoroughly then I do.
Re: (Score:3, Interesting)
Because something like the GPL cannot work for patents. Every time the design is changed, you have to take out a new patent, which costs a large amount of money. In effect, this would be a fee for modifying the software. There is no way to construct such a system that is compati
Software patents aren't going anywhere (Score:2, Insightful)
Re: (Score:2)
I'm going to go stare at the corner for a while.
Re: (Score:2)
Two hundred years ago, liberal democracy was an oddity, now it has spread over the globe [wikipedia.org]. More recently, we gained the 40-hour work week and young children no longer work in mines (in America and Western Europe at
RMS is against higher quality patents? (Score:2)
Re: (Score:2)
Horns Of A Dilemna (Score:5, Insightful)
Such a strategy is not dishonest - even when behaving with the highest integrity, inadvertent patent violation is not only possible, but likely. You should not knowingly violate patents, but you aren't required to help the patent holders identify offenders either.
By hating both simultaneously, RMS has given himself a very tough row to hoe. Open software is highly vulnerable to patent litigation.
Re: (Score:3, Interesting)
I hate to ask this, but if someone uses your code and uses it in their own... Isn't that a copyright violation?
I say this because just because you have the code doesn't make the process easy to copy. Unless of course yo
Re: (Score:2)
Many brilliant and inventive ideas can often be implemented in a few lines of code. The Fast Fourier Transform and Quick Sort are just two examples (although neither were patented).
Re: (Score:2)
Re: (Score:2)
But I would bet most software patents do not have both properties. Certainly in my industry (geophysical processing) this is the case. The very things that make patents less known also their violation less obvious. Thus the patents you are most familiar with are not necessari
a grey solution is no solution (Score:2, Insightful)
This debate has been rehashed so much, but I really get tired of hearing some things like:
"Software patents are here to stay get used to it."
Bloody hell, how defeatest is that. They aren't here to stay, but they will be if that is going to be people's attitude. Also aiming at stop gap measures is a complete waste of resources and will only give softwar
Abstraction Physics = software not patentable (Score:2)
Stallman is correct that this OSDL based project is of FALSE intent.
The intent is to deceive and distract from the real issue.
When honesty of the matter (the nature of software) is dismissed via non-sequeturs and illogical irrational response, you just can't help but know what the genuine intent of the effort is.
There is no real excuse to not address the matter correctly. So why is it not being honestly addressed, but instead the presentation of so called short t
Say it aint so! (Score:3, Insightful)
But the truth is they WANT software patents. I don't see them lobbying to change the status quo. All they are interested in the "quality":
Stallman: Ding? If not:
IBMicrosoft: "Thank you little critters for making our patent applications the strongest on the planet. Now we can make sure that nobody will ever overturn our patent on quicksort, mergesort, bubblesort, mydickinyourassort...and don't forget the youinventedandIpatentedsort [wikipedia.org]"
Backfire is an understatement...
I work at OSDL... (Score:3, Informative)
I don't actually work on this particular project, but I did contribute some of the verbage for the project's main page. Not because I particularly believe in the project, but because my best friend asked it as a favor.
Like generally EVERYONE, I believe software patents should be abolished. Like RMS, I worry this project might be a crutch for the software patent system. Part of me wants to just see the patent office fall smack on its face and be forced to drop the whole idea of software patents entirely.
But realistically, come on, that is head-in-the-sand thinking. Software patents aren't going to simply go away because we wish it so. The U.S. Patent Office itself doesn't have the authority to stop granting software patents. Getting rid of them is going to take a concerted effort by a LOT of people, and ultimately may simply come down to the whims of whomever is in control of the U.S. government. From what I've seen, most people don't care enough about software patents to put time into fighting to eliminate them. (Speaking for myself, I'd rather be fighting the U.S. government about global warming or international relations, before I'd fight about software patents.)
Despite my reservations, I'm actually glad to see OSDL taking action against bad software patents. It actually has the USPTO in good solid dialog with the community, and has engaged a wide variety of FOSS organisations like SourceForge and OSU-OSL on issues geared towards realistic, feasible approaches to mitigation of the problem. Last week OSDL held an on-site meeting with several representatives from the USPTO and various FOSS organizations to start towards some really cool solutions. While I philosophically am of the same mind as RMS about eliminating software patents entirely, I am seeing this OSDL effort making actual, tangible progress towards at least eliminating the absurd patent stories that keep appearing here on Slashdot.
That said, I wish things were this simple. My friend that was organizing this project has left OSDL to go work for Canonical on Ubuntu. While he says it's mainly because he *really* wants to contribute his efforts towards improving Ubuntu's security, I suspect secretly a part is because of his true feelings about software patents. Whatever the case, in practice this prior art effort has suffered a major setback by the loss of its primary technical person.
In the end, like always, it comes down to the rest of us. What do you think about software patents? Do you care enough to put your own time into solving the issues? Do you choose to do nothing and allow any form of software patents at all? Would you prefer to at least eliminate the bad ones? Or do you wish to devote time to getting rid of all software patents entirely? The easiest thing to do is what my friend, myself, and RMS are doing, and simply ignore it with the wish that software patents should just magically go away. The harder but probably more effective thing would be to put time into some sort of project aimed at pushing back and achieving some progress. I really respect those who have chosen this more difficult course, and suspect in the end they will be the ones that define our future situation in regards to software patents.
Re: (Score:3, Insightful)
Not a workable solution. Virtually the entire software industry is taking out patents for defensive reasons if nothing else. Even companies that otherwise are FOSS friendly are. Who on earth, for example, would you recommend that we buy highly specialized trust account software from?
Please get some REAL news (Score:2)
Re: (Score:2)
The part that really sucks is that I have to file these damned things, simply because our system allows them. I'm trying to think of just ONE software patent that made a creative invetor some money...
Re: (Score:2)
You're not seriously saying that no piece of patented software has made money are you?
Re: (Score:2)
Overall, software patents hamper creativity in America. Worse, it gives all the competing nations a huge boost, since they do not recognise our software patents. I know darned well my life at a tiny startup would be easier without software patents. These beasts cost us $10K-$20K each (which small companies can't afford), and all they do
Re: (Score:3, Informative)
I can see it now.
You can't use patent X unless you agree to license Y. No application that enforces DRM. No use by the military. Insert your favorite political cause here.
Re: (Score:2) | http://slashdot.org/story/06/09/21/2130243/stallman-critical-of-osdl-patent-project | CC-MAIN-2015-11 | refinedweb | 4,915 | 61.56 |
Thoughts, props and rants in the world of Build Czar at Atalasoft
It's been a while, and my handy new environment script is working well with most of our current builds (there are over 100 CCNet projects currently).
Today I'm going to touch briefly on something that helped me, and was really easy to setup. First, some background, as usual.
At Atalasoft we have a lot of our functionality in DotImage split into different libraries. Those libraries build independently of one-another, but have very similar setups. Up until a few weeks ago, they each had their own NAnt build script, which contained some form or another of the build environment script I wrote about previously. I decided it was not only possible, but necessary for our sanity, to pull the builds of all of those libraries into one, coherent build file and utilize the environment build script I wrote. Finally, I needed to make it so our new library binaries are checked into source control, and merged over to the main DotImage project, alieviating the hassle and potential forgetfulness of engineers (I'm guilty of forgetting once, myself).
If you find yourself in this situation, a number of builds and one build script that will _do_it_all_ for you, you may run into a problem like I did. I put the Library.build script in a central location (C:\build\tools) next to where everything is built (C:\build\<project>). Once I did that, all the relative paths in the Library.build were to that of its location, not the working directory! This was surprising, but also something I had a bit of trouble getting around. In the build script I needed to know the current working directory, not the directory of the script. If anyone out there has any better ideas, let me know.
First, it's easy to find your working directory in C#:
System.IO.Directory.GetCurrentDirectory();
and it's easy to call C# from within NAnt (check out the script task)
<script language="C#" prefix="test" > <code> <![CDATA[ [Function("test-func")] public static string Testfunc( ) { return "some result !!!!!!!!"; } ]]> </code> </script> <echo message='${test::test-func()}'/>
As you can see, you define the function, and give it a simple attribute to locate it with. Anywhere after that script block is defined you can call that test::test-func() in your NAnt build script. The only downside to this method is the overhead. Each time NAnt uses this build script it'll generate a class with your function, and then compile that to an assembly, load it up and call that function! Like I said, we have over 100 projects and a good chunk are libraries using this! It's better if you can incorporate this into your custom task/type dll, as described in one of mine or Jake's previous blog posts.
I've personally created a new project for our company custom tasks and types and followed the NAnt convention of foldering it out. I have
Atalasoft.NAnt
->Functions
-->Functions.cs
->Tasks
--> FileRegex.cs, RemoveTFSBindings.cs, etc.
->Types
--> AtalaRegex.cs, AtalaRegexCollection.cs, etc.
So you can see, there's a Functions.cs file in a Functions folder. Perhaps later if we have more custom functions we'll end up with more files, for now there's just the one.
Now, just add the GetCurrentDirectory() function into the Functions.cs file
using System;using System.IO;using NAnt.Core;using NAnt.Core.Attributes;namespace Atalasoft.NAnt.Functions{ [FunctionSet("Atala", "Atala")] class Functions : FunctionSetBase { public Functions(Project project, PropertyDictionary properties) : base(project, properties) { } [Function("GetCWD")] public static String GetCWD() { return Directory.GetCurrentDirectory(); } }}
(Notice the attributes; these are what we'll use in the build script to access this function).
Build your DLL as before and place it next to the NAnt.exe and when NAnt runs the next time, your new function will be available to use without the compiling overhead.
I use it for my library build script like this:
<exec program="devenv.com" commandline=""${Atala::GetCWD()}\${Dir.Source}\${sln.filename}" /UseEnv /build ${Build.Config} /out "${Atala::GetCWD()}\buildRelease.log"" verbose="true" />
Now, all our libraries, no matter where they are, can use this build script, and all I have to do in CCNet is fill in the blanks depending on the particular library.
The side effect of having one build script for all projects is you have the ease of editing one file. Add a new CCNet project that checks source control for changes in your build script and all your build servers will be updated when it changes! The other side effect is if you make a small change to the Library script for one library, it has to work with all of them.
Now, if only with my 100 projects I had an easy interface with which to manage them all!
You've been kicked (a good thing) - Trackback from DotNetKicks.com | http://www.atalasoft.com/cs/blogs/dterrell/archive/2008/06/25/custom-functions-in-nant.aspx | CC-MAIN-2014-15 | refinedweb | 821 | 63.8 |
Opened 8 years ago
Last modified 4 years ago
#11565 needs_work enhancement
RSA Cryptosystem — at Version 18
Description (last modified by )
The Rivest, Shamir and Adleman encryption system is a widely accepted public key encryption scheme. The security depends on the difficulty of factoring the product of large primes.
Change History (20)
Changed 8 years ago by
comment:1 Changed 8 years ago by
- Component changed from PLEASE CHANGE to cryptography
- Owner changed from tbd to mvngu
comment:2 Changed 8 years ago by
comment:3 Changed 8 years ago by
well done, keep working
comment:4 Changed 8 years ago by
comment:5 Changed 8 years ago by
Just a few quick observations:
- What is the intended use of the code one included in Sage? If it's for teaching you would probably want to expose more of the details. In fact, for educational purposes it's probably better to do the whole construction "in the open" instead of wrapping it in a class, unless the educational part is wrapping things in classes. For actual cryptographic use, one would probably prefer a whole protocol library. The algorithm is a very small part of deploying cryptography in a secure manner.
- In your code you call
euler_phi(n)to compute the private key d from e. Since the public key is (n,e), anyone could do that same calculation. That means that if it is doable for you to compute the private part of the key, then it is also doable for anyone. You don't have an advantage. (HINT: the key is that euler_phi computes the factorisation of n. If you would make sure that 2p-1 and 2q-1 are actually prime, you would know the factorization of n and hence euler_phi(n). But you should not call euler_phi(n), because that throws away your advantage).
comment:6 Changed 8 years ago by
Thank you nbruin. This was a valid information for me. I will correct it very soon. Keep supporting me in future also
comment:7 Changed 6 years ago by
- Milestone changed from sage-5.11 to sage-5.12
comment:8 Changed 6 years ago by
- Milestone changed from sage-6.1 to sage-6.2
comment:9 Changed 5 years ago by
- Milestone changed from sage-6.2 to sage-6.3
comment:10 Changed 5 years ago by
- Milestone changed from sage-6.3 to sage-6.4
Changed 5 years ago by
Major rewrite of the module, with the goal of a pedagogical implementation.
comment:11 Changed 5 years ago by
I've rewritten ajeeshr's original module, to address nbruin's concerns and to have an implementation that is simpler and better suited for teaching. In summary, I made the following changes:
- Eliminated calls to euler_phi. These were unnecessary, because we know the primes, and $\phi(pq) = (p-1)*(q-1)$.
- Made primality checks optional (but enabled by default).
- Combined the methods that generate public and private keys into a single method, calculate_keys. This is more representative of how actual keygen programs are used.
- Stopped using Mersenne Primes. The original author seems to have been using them to allow the encoding of large messages, but I don't think this is necessary for a teaching module.
- Added more accessible references.
comment:12 Changed 5 years ago by
Hi! Can you make this a branch on the Trac serve with the git workflow? Also, what connection will this have to the (thus far) only currently implemented public system in that folder in Sage? Finally, should this be globally imported, or imported the way that one is? Thanks!
comment:13 Changed 5 years ago by
- Branch set to u/peter.story/rsa_cryptosystem
comment:14 Changed 5 years ago by
- Commit set to 4b667369410afa8400b009b8f4f5cc0ad968c78c
In the associated branch, I've added RSACryptosystem to the global namespace. Is there any reason why this is a bad idea?
BlumGoldwasser, the public key system already included with Sage, has a very similar API to RSACryptosystem. There are a few differences:
- In RSACryptosystem, I combined the
public_keyand
private_keymethods into a single
calculate_keysmethod. This is because the exponent
ewould have had to be calculated independently (and identically) in the two methods. In BlumGoldwasser, the keys can more naturally be calculated independently.
- I am missing a
random_keymethod. This would be an easy addition, but I'm not sure how valuable it is; for RSACryptosystem it would only need to find two primes, and plug them into
calculate_keys.
BlumGoldwasser doc:
comment:15 Changed 5 years ago by
comment:16 Changed 5 years ago by
comment:17 Changed 5 years ago by
- Milestone changed from sage-6.4 to sage-6.6
- Status changed from new to needs_review
Presumably rather 6.7, but there's no new milestone yet.
By definition, factoring large primes is exceptionally easy... ;-)
comment:18 Changed 5 years ago by
Haha, good catch! Changed the description to "factoring the product of large primes."
This is the python code I implemented in python. Just copy this into the public_key folder in crypto, import the class in this code into all.py in the public_key and re-build sage and run it in a worksheet, its simple!!! | https://trac.sagemath.org/ticket/11565?version=18 | CC-MAIN-2019-43 | refinedweb | 866 | 65.93 |
Embeddings are one of the most versatile techniques in machine learning, and a critical tool every ML engineer should have in their toolbelt. It’s a shame, then, that so few of us understand what they are and what they’re good for!
The problem, perhaps, is that embeddings sound slightly abstract and esoteric:
In machine learning, an embedding is a way of representing data as points in n-dimensional space so that similar data points cluster together.
Sound boring and unimpressive? Don’t be fooled! Because once you understand this ML multitool, you’ll be able to build everything from search engines to recommendation systems to chatbots, and a whole lot more. Plus, you don’t have to be a data scientist with ML expertise to use them, nor do you need a huge labeled dataset.
Have I convinced you how neat these bad boys are? 🤞
Good. Let’s dive in. In this post, we’ll explore:
- What embeddings are
- What they’re used for
- Where and how to find open-source embedding models
- How to use them
What can you build with embeddings?
Before we talk about what embeddings are, let’s take quick stock of what you can build with them. Vector embeddings power:
- Recommendation systems (i.e. Netflix-style if-you-like-these-movies-you’ll-like-this-one-too)
- All kinds of search
- Text search (like Google Search)
- Image search (like Google Reverse Image Search)
- Chatbots and question-answering systems
- Data preprocessing (preparing data to be fed into a machine learning model)
- One-shot/zero-shot learning (i.e. machine learning models that learn from almost no training data)
- Fraud detection/outlier detection
- Typo detection and all manners of “fuzzy matching”
- Detecting when ML models go stale (drift)
- So much more!
Even if you’re not trying to do something on this list, the applications of embeddings are so broad that you should probably keep reading, just in case.
What are embeddings?
Embeddings are a way of representing data–almost any kind of data, like text, images, videos, users, music, whatever–as points in space where the locations of those points in space are semantically meaningful.
The best way to intuitively understand what this means is by example, so let’s take a look at one of the most famous embeddings, Word2Vec.
Word2Vec (short for word to vector) was a technique invented by Google in 2013 for embedding words. It takes as input a word and spits out an n-dimensional coordinate (or “vector”) so that when you plot these word vectors in space, synonyms cluster. Here’s a visual:
With Word2Vec, similar words cluster together in space–so the vector/point representing “king” and “queen” and “prince” will all cluster nearby. Same thing with synonyms (“walked,” “strolled,” “jogged”).
For other data types, it’s the same thing. A song embedding would plot similar-sounding songs nearby. An image embedding would plot similar-looking images nearby. A customer-embedding would plot customers with similar buying habits nearby.
You can probably already see how this is useful: embeddings allow us to find similar data points. I could build a function, for example, that takes as input a word (i.e. “king”) and finds me its ten closest synonyms. This is called a nearest neighbor search. Not terribly interesting to do with single words, but imagine instead if we embedded whole movie plots. Then we could build a function that, given the synopsis of one movie, gives us ten similar movies. Or, given one news article, recommends semantically similar articles.
Additionally, embeddings allow us to compute numerical similarity scores between embedded data points, i.e. “How similar is this news article to that one?” One way to do this is to compute the distance between two embedded points in space and say that the closer they are, the more similar they are. This measure is also known as Euclidean distance. (You could also use dot product, cosine distance, and other trigonometric measures.)
Similarity scores are useful for applications like duplicate detection and facial recognition. To implement facial recognition, for example, you might embed pictures of people’s faces, then determine that if two pictures have a high enough similarity score, they’re of the same person. Or, if you were to embed all the pictures on your cell phone camera and found photos that were very nearby in embedding space, you could conclude those points were likely near-duplicate photos.
Similarity scores can also be used for typo correction. In Word2Vec, common misspellings–”hello,” “helo,” “helllo,” “hEeeeelO”–tend to have high similarity scores because they’re all used in the same contexts.
The graphs (way) above also illustrate an additional and very neat property of Word2Vec, which is that different axes capture grammatical meaning, like gender, verb tense, and so on. This means that by adding and subtracting word vectors, we can solve analogies, like “man is to woman as king is to ____.” It’s quite a neat feature of word vectors, though this trait doesn’t always translate in a useful way to embeddings of more complex data types, like images and longer chunks of text. (More on that in a second.)
What kinds of things can be embedded?
So many kinds of things!
Text
Individual words, as in the case of Word2Vec, but also entire sentences and chunks of text. One of open source’s most popular embedding models is called the Universal Sentence Encoder (USE). The name is a bit misleading, because USE can be used to encode not only sentences but also entire text chunks. Here’s a visual from the TensorFlow website. The heat map shows how similar different sentences are according to their distance in embedding space.
Imagine, for example, that I wanted to create a searchable database of New York Times articles.
Now suppose I search this database with the text query “food.” The most relevant result in the database is the article about the burrito, even though the word “food” doesn’t appear in the article headline. If we searched by the USE embeddings of the headlines rather than by the raw text itself, we’d be able to capture that–because USE captures semantic similarity of text rather than overlap of specific words.
It’s worth noting here that since we can associate many data types with text–captions for images, transcripts for movies–we can also adapt this technique to use text search for multimedia. As an example, check out this searchable video archive.
Try it out: How to do text similarity search and document clustering in BigQuery | by Lak Lakshmanan | Towards Data Science
Images
Images can also be embedded, which enables us to do reverse-image search, i.e. “search by image.” One example is vision product search, which also happens to be a Google Cloud product by the same name.
Imagine, for example, that you’re a clothing store and you want to build out a search feature. You might want to support text queries like “leather goth studded mini skirt.” Using something like a USE embedding, you might be able to match that text user query with a product description. But wouldn’t it be neat if you could let users search by image instead of just text? So that shoppers could upload, say, a trending top from Instagram and see it matched against similar products in your inventory? (That’s exactly what this tutorial shows you how to build.)
One of my favorite products that uses image search is Google Lens. It matches camera photos with visually similar products. Here, it tries to match online products that look similar to my pair of sneakers:
As with sentence embeddings, there are lots of free-to-use image embedding models available. This TensorFlow Hub page provides a bunch, under the label “feature vector.” These embeddings were extracted from large deep learning models that were initially trained to do image classification on large datasets. To see a demo of image search powered by MobileNet embeddings, check out this demo that lets you upload a photo and searches all of Wikimedia to find similar images.
Unfortunately, unlike sentence embeddings, open-source image embeddings often need to be tuned for a particular task to be high-quality. For example, if you wanted to build a similarity search for clothing, you’d likely want a clothing dataset to train your embeddings on. (More on how to train embeddings in a bit.)
Read More: Compression, search, interpolation, and clustering of images using machine learning | by Lak Lakshmanan | Towards Data Science
Products and Shoppers
Embeddings are especially useful in the retail space when it comes to making product recommendations. How does Spotify know which songs to recommend listeners based on their listening histories? How does Netflix decide which movies to suggest? How does Amazon know what products to recommend shoppers based on purchase histories?
Nowadays, the cutting-edge way to build recommendation systems is with embeddings. Using purchase/listening/watching history data, retailers train models that embed users and items.
What does that mean?
Imagine, for example, that I’m a frequent shopper at an imaginary, high-tech book-selling site called BookShop. Using purchase history data, BookShop trained two embedding models:
The first, its user embedding model, maps me, a book-buyer, to user space based on my purchase history. I.e. because I buy a lot of O’Reilly tech guides, pop science books, and fantasy books, this model maps me close to other nerds in user space.
Meanwhile, BookSpace also maintains an item embedding model that maps books to item space. In item space, we’d expect books of similar genres and topics to cluster together. So, we’d find the vector representing Philip K. Dick’s Do Androids Dream of Electric Sheep nearby to the vector representing William Gibson’s Neuromancer, since these books are topically/stylistically similar.
How are embeddings created?
To recap, so far we’ve talked about:
- What types of apps embeddings power
- What embeddings are (a mapping of data to points in space)
- Some of the data types that can actually be embedded
What we haven’t yet covered is where embeddings come from, or, more specifically: how to build a machine learning model that takes in data and spits out semantically meaningful embeddings based on your use case.
Here, as in most of machine learning, we have two options: the pre-trained model route and the DIY, train-your-own model route.
Pre-Trained Models
If you’d like to embed text–i.e. to do text search or similarity search on text–you’re in luck. There are tons and tons of pre-trained text embeddings free and easily available for your using. One of the most popular models is the Universal Sentence Encoder model I mentioned above, which you can download here from the TensorFlow Hub model repository. Using this model in code is pretty straightforward. This sample is snatched directly from the TensorFlow website:
import tensorflow_hub as hub
embed = hub.load("")
embeddings = embed([
"The quick brown fox jumps over the lazy dog.",
"I am a sentence for which I would like to get its embedding"])
print(embeddings)
Personally, I think it’s absolutely mind-blowing that you can accomplish something as sophisticated as sentence embeddings in so few lines of Python code.
To actually get use out of these text embeddings, we’ll need to implement nearest neighbor search and calculate similarity. For that, let me point you to this blog post I wrote recently on this very topic–building text/semantically intelligent apps using sentence embeddings.
Open-source image embeddings are easy to come by too. Here’s where you can find them on TensorFlow Hub. Again, to be useful for domain-specific tasks, it’s often useful to fine-tune these types of embeddings on domain-specific data (i.e. pictures of clothing items, dog breeds, etc.)
Finally, I’d be remiss not to mention one of the most hype-inducing embedding models released as of late: OpenAI’s CLIP model. CLIP can take an image or text as input and map both data types to the same embedding space. This allows you to build software that can do things like: figure out which caption (text) is most fitting for an image.
Training Your Own Embeddings
Beyond generic text and image embeddings, we often need to train embedding models ourselves on our own data. Nowadays, one of the most popular ways to do this is with what’s called a Two-Tower Model. From the Google Cloud website:
The Two-Tower model trains embeddings by using labeled data. The Two-Tower model pairs similar types of objects, such as user profiles, search queries, web documents, answer passages, or images, in the same vector space, so that related items are close to each other. The Two-Tower model consists of two encoder towers: the query tower and the candidate tower. These towers embed independent items into a shared embedding space, which lets Matching Engine retrieve similarly matched items.
I’m not going to go into detail about how to train a two-tower model in this post. For that, I’ll direct you to this guide on Training Your Own Two-Tower Model on Google Cloud, or this page on Tensorflow Recommenders, which shows you how to train your own TensorFlow Two-Tower/recommendation models.Special thanks to Kaz Sato for his early feedback!
By Dale Markowitz Applied AI Engineer
Source Google Cloud | https://liwaiwai.com/2022/03/27/meet-ais-multitool-vector-embeddings/ | CC-MAIN-2022-27 | refinedweb | 2,256 | 62.17 |
Whereas in Python source code we only need to include a module docstrings using the directive .. automodule:: mypythonmodule, we will have to explicitely define Javascript modules and functions in the doctrings since there is no native directive to include Javascript files.
pyjsrest is a small utility parsing Javascript doctrings and generating the corresponding Restructured file used by Sphinx to generate HTML documentation. This script will have the following structure:
=========== filename.js =========== .. module:: filename.js
We use the .. module:: directive to register a javascript library as a Python module for Sphinx. This provides an entry in the module index.
The contents of the docstring found in the javascript file will be added as is following the module declaration. No treatment will be done on the doctring. All the documentation structure will be in the docstrings and will comply with the following rules.
Basically we document javascript with RestructuredText docstring following the same convention as documenting Python code.
The doctring in Javascript files must be contained in standard Javascript comment signs, starting with /** and ending with */, such as:
/** * My comment starts here. * This is the second line prefixed with a `*`. * ... * ... * All the follwing line will be prefixed with a `*` followed by a space. * ... * ... */
Comments line prefixed by // will be ignored. They are reserved for source code comments dedicated to developers.
By default, the function directive describes a module-level function.
Its purpose is to define the function prototype such as:
.. function:: loadxhtml(url, data, reqtype, mode)
If any namespace is used, we should add it in the prototype for now, until we define an appropriate directive:
.. function:: jQuery.fn.loadxhtml(url, data, reqtype, mode)
We will define function parameters as a bulleted list, where the parameter name will be backquoted and followed by its description.
Example of a javascript function docstring:
.. function:: loadxhtml(url, data, reqtype, mode) cubicweb loadxhtml plugin to make jquery handle xhtml response fetches `url` and replaces this's content with the result Its arguments are: * `url` * `mode`, how the replacement should be done (default is 'replace') Possible values are : - 'replace' to replace the node's content with the generated HTML - 'swap' to replace the node itself with the generated HTML - 'append' to append the generated HTML to the node's content
Javascript functions handle arguments not listed in the function signature. In the javascript code, they will be flagged using /* ... */. In the docstring, we flag those optional arguments the same way we would define it in Python:
.. function:: asyncRemoteExec(fname, arg1=None, arg2=None) | https://docs.cubicweb.org/book/annexes/docstrings-conventions.html | CC-MAIN-2018-34 | refinedweb | 416 | 55.13 |
To view parent comment, click here.
To read all comments associated with this story, please click here.
:: I agree with you that the Freecell Solver coverage is a weak point of the essay.
Very weak indeed, first you go talking about portability... and the first thing one finds when downloading the source is autoconf... you dismiss you own point.
And then, autoconf is not enough... for instance it does not build out of the tarball on MacOS. Very simple to fix but still weakens even more the portability argument. Why does not it build? Simple enough, while claiming that C code is portable because there exists the ANSI C spec... you go and do:
# include <malloc.h>
Which is not part of ANSI C. Dear sir, malloc's() prototype is part of <stdlib.h>.
Not only that but all you header files are guarded by macros that start with a double underscore... but all such identifiers are reserved and should not be used by programs (see section 7.1.3 of the spec.) Another portability problem since those identifiers belong to the compiler, not to you.
Member since:
2005-10-10
I agree with you that the Freecell Solver coverage is a weak point of the essay. However, as I note in my site's containing page ( ), I could not convey the fact that as far as Freecell Solver is concerned, not only will writing it in a different language than C will be much slower, but it will also feel wrong. (and it will).
The reason I gave Freecell solver as an example is because it's a project I headed (and thus am very familiar with it and can testify for it), and because I think C is the ideal language for its problem domain. I daresay I was not very successful. | http://www.osnews.com/thread?42794 | CC-MAIN-2014-52 | refinedweb | 304 | 75.4 |
Earthly Powers
- All
- Fast Infoset
- General
- Java
- REST
Devoxx 2008 interview with Ted Neward
Hot on the heals of the my JAX-RS Devoxx 08 presentation on Parleys (2,094 views so far, that is my biggest audience yet :-) ) is the interview i did with Ted Neward. This was the first time i have done something like that, but i found Ted put me at ease and i enjoyed the discussion.
Posted at 11:27AM Jun 29, 2009 by Paul Sandoz in REST | Comments[0]
Devoxx 2008 video presentation online
See here for the video presentation i did @ Devoxx 2008 on JAX-RS.
The Parleys interface is really slick, perhaps the best interface combination of slides/video i have seen.
Posted at 03:10PM Jun 08, 2009 by Paul Sandoz in REST | Comments[1]
JavaOne slides for JAX-RS and Jersey
Here are the slides for the JAX-RS technical session Marc and I presented on Wednesday.
Here are the slides for the Jersey BOF @ 7.30pm on Thursday.
Posted at 11:28PM Jun 04, 2009 by Paul Sandoz in Java | Comments[1]
Jersey 1.1.0-ea is released.
Posted at 02:26PM May 04, 2009 by Paul Sandoz in REST | Comments[0]
Jersey 1.0.3 is released.
Posted at 11:11AM Apr 16, 2009 by Paul Sandoz in REST | Comments[7]
Jersey and Spring enterprise tech tip
An new enterprise tech tip explaining how to get started with Jersey and Spring is available.
Additionally, see here for JavaDoc and here for a Spring sample.
Posted at 10:06AM Apr 14, 2009 by Paul Sandoz in REST | Comments[0]
Jersey features and documentation
Posted at 02:36PM Apr 03, 2009 by Paul Sandoz in REST | Comments[0]
NetBeans 6.7 m3, maven and Jersey
NetBeans 6.7 milestone 3 has support for maven web projects with RESTful Web services using Jersey:
Posted at 01:25PM Apr 03, 2009 by Paul Sandoz in REST | Comments[0]
Glassfish v3, EJB 3.1 and Jersey
With Glassfish V3 promoted build 43 (or greater) and the latest Jersey 1.0.3-SNAPSHOT it is now possible to create no-interface-view session beans (or POJO session beans) deployed in the war and those beans may be either (root) resource or provider classes.
A big thanks to Ken Saks who provided the hooks in the Glassfish EJB module so Jersey can dynamically plug-in if Glassfish EJB support is available.
For example one could develop the following root resource class:
@Stateless @Path("ssb") public class StatelessSessionRootResource { @Context private UriInfo ui;@GET public String get() { return "GET: " + ui.getRequestUri().toASCIIString(); } }
Notice the annotated field, ui, to obtain an instance of UriInfo. Jersey will defer to JNDI to obtain an instance of the session bean (using the EJB 3.1 portable naming mechanism) and the EJB module will inform Jersey when an instance of the session bean is constructed so that Jersey gets a chance to inject Jersey/JAX-RS artifacts.
Session beans can also be used for sub-resources. For example one can add another resource class:
@Stateless public class StatelessSessionResource { @Context private UriInfo ui; @GET public String get() { return "GET: " + ui.getRequestUri().toASCIIString(); } }
and then modify the StatelessSessionRootResource class to be as follows:
@Stateless @Path("ssb") public class StatelessSessionRootResource { @Context private UriInfo ui; @GET public String get() { return "GET: " + ui.getRequestUri().toASCIIString(); } @EJB StatelessSessionResource r;@Path("sub") public StatelessSessionResource getSub() { return r; } }
A reference to StatelessSessionResource is injected onto the root resource class and then the sub-resource locator method, getSub, returns that reference.
Alternatively the same functionality can be achieved using the Jersey specific feature of returning the class:
@Path("sub/class") public Class<StatelessSessionResource> getSubClass() { return StatelessSessionResource.class; }
See here for a simple maven project, which contains the resource classes presented above, and can be built to create a war file to deploy to Glassfish V3. The following URIs will exercise the application:
Posted at 01:44PM Apr 02, 2009 by Paul Sandoz in REST | Comments[2]
JavaOne and CommunityOne sessions and BOFs.
Posted at 10:40AM Apr 01, 2009 by Paul Sandoz in Java | Comments[1]
Developing SGMP Connectors using JAX-RS (Screencast)
See Santaigo's blog entry for more details.
Posted at 04:00PM Feb 26, 2009 by Paul Sandoz in REST | Comments[0]
Jersey 1.0.2 is released.
Posted at 03:20PM Feb 12, 2009 by Paul Sandoz in REST | Comments[2]
A Christmas present for Jersey ant users?
!).
Posted at 03:12PM Dec 19, 2008 by Paul Sandoz in REST | Comments[4]
Devoxx slides and examples for the JAX-RS presentation
A PDF of my Devoxx presentation can be found here.
The simple example project i used to demonstrate some JAX-RS features can be found here. This is a maven project. It can be loaded into NetBeans 6.5 if using the maven plugin.
The EJB example can be found here. This is a NetBeans 6.5 project using Jersey 1.0 as shipped with NetBeans 6.5. Note that this currently relies on Glassfish only specific behaviour and is intended as a demostration of where JAX-RS EE 6 functionality is heading.
The simple Security example leveraging Web container security, that i had no time to present, can be found here. This is a NetBeans 6.5 project using Jersey 1.0 as shipped with NetBeans 6.5. I wish i had time to present this as it would have given me the opporunity to have a great rant at the limited support for HTTP authentication in browsers such as Firefox. The user could be so much more in control of authenticated sessions...
Posted at 04:02PM Dec 15, 2008 by Paul Sandoz in REST | Comments[2]
Jersey, Glassfish, and EJBs as root resources
Jersey supports EJB 3.0 beans as root resources as follows:
- Annotate a local or remote interface with @Path and annotate methods as appropriate; and
- Ensure that the local or remote interface in 1) is registered by file/directory or package scanning.
The registration mechanism in 2) is no different for registering non-EJBs. The caveat: it currently only works with Glassfish, which supports JNDI lookup of an EJB reference using the fulling qualified class name of the local or remote interface.
The JSR 311 expert group is currently considering approaches to integrate JAX-RS with EJB 3.1, which should present some nice improvements, namely EJBs bundled in the war and EJBs with no interfaces. I have high hopes we can retain the current ease of use registration aspects with JAX-RS as presented here and then it should be really simple to use EJBs as POJOs in the web tier directly serving HTTP requests.
There are already some EJB 3.1 features ready in Glassfish Prelude, as highlighted by Ken, with update centre instructions from Mahesh. Now i need to find the time to experiment...
Posted at 11:23AM Dec 02, 2008 by Paul Sandoz in REST | Comments[0] | http://blogs.sun.com/sandoz/ | crawl-002 | refinedweb | 1,161 | 62.17 |
Alright, Now the purpose of the program is to generate two random numbers both from the pool of 1-50 and have them come in the form of the question asking the user to input the sum. They get two tries and after that it says your wrong and prompts you to press return and the program ends. So far it seemed fine til i got the if loop. Something isn't right.
Could someone tell me what I'm doing wrong? Thanks!
Code:#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand((unsigned)time(0)); int answer; int realanswer; int random_integer1; int random_integer2; int lowest=0, highest=49; int range=(highest-lowest)+1; for(int index=0; index<1; index++){ random_integer1 = lowest+int(range*rand()/(RAND_MAX + 1.0)); endl; } { for(int index=0; index<1; index++){ random_integer2 = lowest+int(range*rand()/(RAND_MAX + 1.0)); endl; cout << "If I add " << random_integer1 << " and " << random_integer2 << " then what do I have? " << endl; cin >> answer; } { system("PAUSE"); } { if (answer == realanswer) { cout << "You are Right! " << endl; } else { if (answer != realanswer) { cout << "Whoops Try again! :" << endl; } else { if (answer == realanswer) { cout << "You are Right :" << endl; } else { if (answer != realanswer) cout << "The answer was :" << realanswer << endl; } system("PAUSE"); return 0; } } } } } | https://cboard.cprogramming.com/cplusplus-programming/98369-problems-if-loop.html | CC-MAIN-2017-43 | refinedweb | 206 | 66.23 |
Documentation
The friendly Operating System for the Internet of Things
Board specific definitions for the SLSTK3402A starter kit.
More...
Board specific definitions for the SLSTK3402A starter kit.
Definition in file board.h.
#include "cpu.h"
#include "periph_conf.h"
#include "periph/gpio.h"
#include "periph/spi.h"
This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.
Go to the source code of this file.
Define the GPIO pin to enable the BC, to allow serial communication via the USB port.
Connection to the on-board Sharp Memory LCD (LS013B7DH03).
Connection to the on-board temperature/humidity sensor (Si7021). | http://doc.riot-os.org/slstk3402a_2include_2board_8h.html | CC-MAIN-2020-24 | refinedweb | 103 | 54.39 |
Worked-Out Example 0¶
Decrypting a Password¶
Problem: crack an encrypted file by brute force. Assume that the password is a five-letter lower-case word and that you know that the plain text contains my name.
(The complete code for this example and a secret message comes with the jug source)
This is the ultimate parallel problem: try very many keys (26**5 ~ 11M), but there is no interaction between the different tasks.
The brute force version is very simple:
for p in product(letters, repeat=5): text = decode(ciphertext, p) if isgood(text): passwd = "".join(map(chr, p)) print('%s:%s' % (passwd, text))
However, if we have more than one processor, we’d like to be able to tell
jug to use multiple processors.
We cannot simply have each password be its own task: 11M tasks would be too much!
So, we are going to iterate over the first letter and a task will consist of trying every possibility starting with that letter:
@TaskGenerator def decrypt(prefix, suffix_size): res = [] for p in product(letters, repeat=suffix_size): text = decode(ciphertext, np.concatenate([prefix, p])) if isgood(text): passwd = "".join(map(chr, p)) res.append((passwd, text)) return res @TaskGenerator def join(partials): return list(chain(*partials)) fullresults = join([decrypt([let], 4) for let in letters])
Here, the
decrypt function returns a list of all the good passwords it
found. To simplify things, we call the
join function which concatenates all
the partial results into a single list for convenience.
Now, run
jug:
$ jug execute jugfile.py & $ jug execute jugfile.py & $ jug execute jugfile.py & $ jug execute jugfile.py &
You can run as many simultaneous processes as you have processors. To see what is happening, type:
$ jug status jugfile.py
And you will get an output such as:
Task name Waiting Ready Finished Running ---------------------------------------------------------------------------------------- jugfile.join 1 0 0 0 jugfile.decrypt 0 14 8 4 ........................................................................................ Total: 1 14 8 4
There are two task functions:
decrypt, of which 8 are finished, 14 are ready
to run, and 4 are currently running; and
join which has a single instance,
which is
waiting: it cannot run until all the
decrypt tasks have
finished.
Eventually, everything will be finished and your results will be saved in
directory
jugdata in files with names such as
jugdata/5/4/a1266debc307df7c741cb7b997004f The name is simply a hash of the
task description (function and its arguments).
In order to make sense of all of this, we write a final script, which loads the results and prints them on stdout:
import jug jug.init('jugfile.py', 'jugdata') import jugfile results = jug.task.value(jugfile.fullresults) for p, t in results: print("%s\n\n Password was '%s'" % (t, p))
jug.init takes the jugfile name (which happens to be
jugfile.py) and
the data directory name.
jug.task.value takes a
jug.Task and loads its result. It handles more
complex cases too, such as a list of tasks (and returns a list of their
results). | http://jug.readthedocs.io/en/latest/decrypt-example.html | CC-MAIN-2017-39 | refinedweb | 499 | 64.91 |
Python is a general-purpose programming language which can be used in many ways. This ubiquitous language has a very large community and has been used by the researchers as well as the developers for quite a long time.
Python Standard Library
Python’s standard library contains built-in modules which provide access to system functionality such as file I/O. It contains several different kinds of components and data types which can be considered as a part of the core of a language. The library also contains built-in functions and exceptions which can be used by all Python codes without the need of an import statement.
Packages
The method of structuring Python’s module namespace by using “dotted module names” is known as packages. For instance, the module name X.Y designates a submodule y in a package named X. Packaging mainly depends upon the target environment as well as the deployment experience.
How to use them
Packages are consisted of multiple files and are harder to distribute. If you have a pure Python code and you know your deployment environment which supports your version of Python, in that case, you can easily use Python’s native packaging tools to create a source distribution package or sdist which is a compressed archive containing one or more packages or modules. Python’s native packaging is mostly built for distributing reusable code known as libraries between the developers.
Here is a video of Python’s recommended built-in library and tool packaging technologies.
How The Deployment Is Critical
One of the crucial reasons is that the researchers do not have the right tools or expertise in order to deploy their machine learning models. The domain experts work on open source tools, train models with some subset of data, and the process goes on ubtil the software engineering team receives the model from the data science team which sometimes causes the outcomes of the model to change. This process is quite a challenge for larger organisations but this can be made easier and usable when the model is made to be encapsulated behind some APIs by which other applications can use to connect with the model.
Some Important Python Libraries
This web application framework is written in Python and is based on Werkzeug WSGI toolkit and Jinja2 template engine. It is a flexible microframework which does not require any particular project or code layout.
Flask installation and Setup
from flask import Flask
app = Flask(name)
@app.route(‘/’)
def hello_world():
return ‘Hello World’
pip install Flask
FLASK_APP=hello.py flask run
This is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. With this library, you can generate plots, histograms, power spectra, bar charts, etc. Not to forget that Matplotlib was used to reveal the first black hole image.
Matplotlib Installation:
python -m pip install -U pip
python -m pip install -U matplotlib
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is basically designed to help the developers take applications from concept to completion.
Django Installation:
pip install Django
git clone
pip install -e django/
Pyramid is a small, fast, down-to-earth Python web framework and is developed as part of the Pylons Project. This open source web application framework is designed to make creating web applications easier. With Pyramid, you can write very small applications without knowing a lot.
Pyramid Installation on Windows:
cd \
set VENV=c:\env
python -m venv %VENV%
cd %VENV%
%VENV%\Scripts\pip install “pyramid==version”
Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library.
Bottle Installation:
wget
python virtualenv.py develop
source develop/bin/activate(develop)
pip install -U bottle
References:
- Modules from Python Documentation, Read here.
- An Overview of Packaging for Python, Read here.
- The Python Standard Library, Read here.
- Deploying Machine Learning Models is Hard, But It Doesn’t Have to Be, Read here. | https://www.analyticsindiamag.com/5-python-libraries-to-package-and-deploy-machine-learning-models/ | CC-MAIN-2019-26 | refinedweb | 684 | 52.49 |
I've ported Python to a realtime operating system and embedded it in an application that controls machinery. Python will be used to expose an API to end users. It seems prudent to disable threads. I undefined WITH_THREAD. Now I run into this in threadmodule.c: #error "Error! The rest of Python is not compiled with thread support." #error "Rerun configure, adding a --with-threads option." #error "Then run `make clean' followed by `make'." Problem is, I've never run configure, and probably could not if I wanted to. I used the NT distribution and hacked it into submission. All the Python source code I'm using is now checked into a source control system. I doubt that "configure" could handle that. I don't use "make" either. Can someone tell me how to "configure" for no threads by hand? Does it suffice just to remove the offending file threadmodule.c? If that is the case, why the error message rather than just #ifndef WITH_THREAD #else // the thread stuff #endif I removed the file from the project just to see what would happen. The project built without reporting an error, and the program seems to run Python okay. | http://mail.python.org/pipermail/python-list/2004-November/274646.html | CC-MAIN-2013-20 | refinedweb | 198 | 77.64 |
I have a function which should handle all errors:
def err(e):
import traceback
message = traceback.print_exc()
print(message)
if __name__ == "__main__":
try:
1/0 # just sample
except Exception as e:
err(e)
integer division or modulo by zero
traceback
You're passing the exception to your function so why use
traceback, you've got
e there; just grab
e.__traceback__ if you need the traceback:
import traceback def err(e): tb = e.__traceback__ # print traceback traceback.print_tb(tb)
For an option that doesn't depend on dunders, you could use
sys.exc_info and keep the traceback:
import traceback, sys def err(e): *_, tb = sys.exc_info() # print traceback traceback.print_tb(tb) | https://codedump.io/share/EvwW5irtkFxz/1/how-to-get-python-exception-traceback-in-function | CC-MAIN-2018-13 | refinedweb | 112 | 57.87 |
C++ program to calculate the difference between two time periods
In this tutorial, we’ll learn how to calculate the difference between two given time periods in C++. The time periods should be provided by the user. The user can provide two time periods. It should be in the form of hours, minutes and seconds.
To understand this example we need to have vast knowledge in C++ topics such as Structures, Functions and Pointers. Kindly find the links mentioned below on the topics Structures, Functions and Pointers attached for better understand.
Consider an example, as it would be helpful further.
Time period 1 = 9 : 6 : 2
Time period 2 = 5 : 9 : 3
The Time difference = 3 : 56 : 59
Difference between the two time periods using C++
- In the below program, the user will be giving the two time periods in the form of hours, minutes and seconds such that the structure variable stores t1 and t2 respectively.
- TimeDifference() function can be used to find the difference between the time periods.
- Finally, the output screen will display the time period difference from the main() function without returning to it ( call by reference).
Also, refer to the following topics for better understand:
Structures in C++
Functions in C++
Pointers in C++
Program:
#include <iostream> using namespace std; struct TIME_PERIOD { int sec; int min; int hours; }; void TimeDifference(struct TIME_PERIOD, struct TIME_PERIOD, struct TIME_PERIOD *); int main() { struct TIME_PERIOD t1, t2, difference; cout << "Enter the Time Period 1." << endl; cout << "Enter hours, minutes and seconds of Time Period 1: "; cin >> t1.hours >> t1.min >> t1.sec; cout << "Enter the Time Period 2." << endl; cout << "Enter hours, minutes and seconds of Time Period 2: "; cin >> t2.hours >> t2.min >> t2.sec; TimeDifference(t1, t2, &difference); cout << endl << "The Time Period difference is: " << t1.hours << ":" << t1.min << ":" << t1.sec; cout << " - " << t2.hours << ":" << t2.min << ":" << t2.sec; cout << " = " << difference.hours << ":" << difference.min << ":" << difference.sec; return 0; } void TimeDifference(struct TIME_PERIOD t1, struct TIME_PERIOD t2, struct TIME_PERIOD *difference) { if(t2.sec > t1.sec) { --t1.min; t1.sec += 60; } difference->sec = t1.sec - t2.sec; if(t2.min > t1.min) { --t1.hours; t1.min += 60; } difference->min = t1.min-t2.min; difference->hours = t1.hours-t2.hours; }
Output:
Enter the Time Period 1. Enter hours, minutes and seconds of Time Period 1: 12 45 35 Enter the Time Period 2. Enter hours, minutes and seconds of Time Period 1: 6 21 23 The Time Period difference is: 12:45:35 - 6:21:23 = 6:24:12 | https://www.codespeedy.com/cpp-program-to-calculate-the-difference-between-two-time-periods/ | CC-MAIN-2022-27 | refinedweb | 417 | 55.74 |
Async I/O and ThreadPool Deadlock (Part 2)
Async I/O and ThreadPool Deadlock (Part 2)
Join the DZone community and get the full member experience.Join For Free
Sensu is an open source monitoring event pipeline. Try it today.
Parallel Execution
Now, let’s complicate our lives with some concurrency, shall we?
If we are to spawn many processes, we could (and should) utilize all the cores at our disposal. Thanks to
Parallel.For and
Parallel.ForEach this task is made much simpler than otherwise.
public static void ExecAll(List<KeyValuePair<string, string>> pathArgs, int timeout) { Parallel.ForEach(pathArgs, arg => ExecWithAsyncTasks(arg.Key, arg.Value, timeout)); }
Things couldn’t be any simpler! We pass a list of executable paths and their arguments as
KeyValuePair and a timeout in milliseconds. Except, this won’t work… at least not always.
First, let’s discuss how it will not work, then let’s understand the why before we attempt to fix it.
When Abstraction Backfires
The above code works like a charm in many cases. When it doesn’t, a number of waits timeout. This is unacceptable as we wouldn’t know if we got all the output or part of it, unless we get a clean exit with no timeouts. I first noticed this issue in a completely different way. I was looking at the
task manager
Process Explorer (if not using it, start now and I promise not to tell anyone,) to see how amazingly faster things are with that single
ForEach line. I was expecting to see a dozen or so (on a 12-core machine) child processes spawning and vanishing in quick succession. Instead, and to my chagrin, I saw most of the time just one child! One!
And after many trials and head-scratching and reading, it became clear that the waits were timing out, even though clearly the children had finished and exited. Indeed, because typically a process would run in much less time than the timeout, it was now slower with the parallelized code than with the sequential version. This wasn’t obvious at first, and reasonably I suspected some children were taking too long, or they had too much to write to the output pipes that could be deadlocking (which wasn’t unfamiliar to me).
Testbed
To troubleshoot something as complex as this, one should start with clean test-case, with minimum number of variables. This calls for a dummy child that would do exactly as I told it, so that I could simulate different scenarios. One such scenario would be not to spawn any children at all, and just test the
Parallel.ForEach with some in-proc task (i.e. just a local function that does similar work to that of a child).
using System; using System.Threading; namespace Child { class Program { static void Main(string[] args) { if (args.Length < 2 || args.Length % 2 != 0) { Console.WriteLine("Usage: [echo|fill|sleep|return] "); return; } DoJob(args); } private static void DoJob(string[] args) { for (int argIdx = 0; argIdx < args.Length; argIdx += 2) { switch (args[argIdx].ToLowerInvariant()) { case "echo": Console.WriteLine(args[argIdx + 1]); break; case "fill": var rd = new Random(); int bytes = int.Parse(args[argIdx + 1]); while (bytes-- > 0) { // Generate a random string as long as the . Console.Write(rd.Next('a', 'z')); } break; case "sleep": Thread.Sleep(int.Parse(args[argIdx + 1])); break; case "return": Environment.ExitCode = int.Parse(args[argIdx + 1]); break; default: Console.WriteLine("Unknown command [" + args[argIdx] + "]. Skipping."); break; } } } } }
Now we can give the child process commands to change its behavior, from dumping data to its output to sleeping to returning immediately.
Once the problem is reproduced, we can narrow it down to pin-point the source. Running the exact same command in the same process (i. e. without spawning another process) results in no problems at all. Calling
DoJob 500 times directly in
Parallel.ForEach finishes in under 500ms (often under 450ms). So we can be sure Parallel.ForEach is working fine.
public static void ExecAll(List<KeyValuePair<string, string>> pathArgs, int timeout) { Parallel.ForEach(pathArgs, arg => Task.Factory.StartNew(() => DoJob(arg.Value.Split(' '))).Wait() ); }
Even executing as a new task (within the
Parallel.ForEach) doesn’t result in any noticeable different in time. The reason for this good performance when running the jobs in new tasks is probably because the
ThreadPool scheduler does fetch the task to execute immediately when we call
Wait() and executes it. That is, because both the
Task.Factory.StartNew() call as well as the
DoJob() call are executed ultimately on the
ThreadPool, and because Task is designed specifically to utilize it, when we call
Wait() on the task, it knows that it should schedule the next job in the queue, which in this case is the job of the task on which we executed the Wait! Since the caller of
Wait() happens to be running on the
ThreadPool, it simply executes it instead of scheduling it on a different thread and blocking. Dumping the
Thread.CurrentThread.ManagedThreadId from before the
Task.Factory.StartNew() call and from within
DoJob shows that indeed both are executed in the same thread. The overhead of creating and scheduling a Task is negligible, so we don’t see much of a change in time over 500 executions.
All this is great and comforting, but still doesn’t help us resolve the problem at hand: why aren’t our processes spawned and executed at the highest possible efficiency? And why are they timing out?
In the next part we’ll dive deep into the problem and find out what is going on.
Sensu: workflow automation for monitoring. Learn more—download the whitepaper. }} | https://dzone.com/articles/async-io-and-threadpool-0 | CC-MAIN-2018-51 | refinedweb | 943 | 66.84 |
Author: Chris Brown
This article is excerpted from the newly published bookSUSE LinuxCopyright © 2006 O’Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O’Reilly Media.
The documentation uses the metaphor of “immunizing” the applications, but the product does not actually prevent an application from being infected or compromised. Rather, it limits the damage that an application can do if this should happen.
If we must have a medical metaphor, “quarantine” might be better, or you might think of it as offering the program a large white handkerchief to sneeze into to prevent it from spreading germs.
AppArmor was originally a closed-source product, but became open source in January 2006. It is included with SUSE Linux 10.1 and with SLES9 SP3. It was also included with SUSE Linux 10.0, but the profiling tool was deliberately restricted in scope and required the purchase of a license file to become fully functional.
How Do I Do That?
To give you a feel for how AppArmor works, in this lab I’ll use it to profile and contain a very simple C program. Whilst this example is undeniably simplistic, it does help to show how AppArmor actually works.
Here’s the program that you will profile. It’s called
scribble, because it scribbles on files:
#include <stdio.h>
int main(int argc, char *argv[]) { int i; FILE *fd; for (i=1; i<argc; i++) { fd = fopen(argv[i], "w"); if (fd == NULL) { fprintf(stderr, "fopen failed for %sn", argv[i]); return 1; } fprintf(fd, "scribbled on file %sn", argv[i]); fclose(fd); } }
If you can’t read C, don’t worry, it doesn’t really matter. The program loops over its command-line arguments, treating each as a filename. For each one, it tries to open the file for writing, writes a line of text to it, then closes the file. If it can’t open the file, it prints an error message. I created the source file scribble.c in my home directory and compiled it with:
$
cc scribble.c -o scribble
Before proceeding further, you must ensure that the
apparmor module is loaded into the kernel. To do this, run the following command as root:
#
rcapparmor start
To build a profile for this application, you can use YaST. From YaST’s main screen, select Novell AppArmor from the panel on the left, then Add Profile Wizard from the panel on the right. On the wizard’s first screen, you’re invited to enter the name of the application you want to profile. Since I built
scribble in my home directory, I entered the name /home/chris/scribble then clicked Create. On the next screen, you’re invited to “start the application to be profiled in another window and exercise its functionality now”. The idea is to run the program and make it do the full range of things that it is “supposed to do”. In this case, I simply ran my little program with the command:
$
./scribble apple orange /tmp/banana
causing it to open and write to three files. As the program runs, AppArmor records each resource that is accessed in the system log, /var/log/messages. You can run the program as many times as you want to get a complete, representative profile. When you’re done profiling, click the button labeled “Scan system log for AppArmor events.” Now we’re taken one by one through the events that AppArmor logged. For each one, AppArmor makes suggestions about what should be added to the profile. An example is shown in the figure.
Adding a rule to an AppArmor profile
In this figure, the program’s action of writing to the file /home/chris/apple has been noted and you’re offered a number of choices of what should be added to the profile to allow this. This is where you need to put your thinking cap on. One of the options is to allow access just to that one file: /home/chris/apple. Another option proposed by AppArmor is a generalization — namely, to allow writing to a file called apple in any user’s home directory (/home/*/apple). Clicking the Glob button will suggest a still broader rule to add to the profile; in this case /home/*/*. (“Glob” is short for “globbing,” a slang Unix expression relating to the use of filename wildcards.) The button labeled “Glob w/Ext” will broaden the pattern using a
* wildcard, but retain the filename extension. For example, /home/chris/testimage.png would be broadened to /home/chris/*.png. Obviously, you need to make your own judgment here about what makes sense for the application. Having selected an appropriate rule, click Allow to add it to the profile, or click Deny if you don’t want it added to the profile. You’ll need to proceed event by event through the activities that AppArmor has logged in order to complete the profile.
Once the profile is built, AppArmor will automatically begin to enforce it. If I now try to use
scribble to write to a file that’s within the profile, all is well, but if I try to access a file that’s not in the profile, it fails:
$
./scribble apple
$ ./scribble mango
fopen failed for mango
The restrictions imposed by AppArmor are, of course, in addition to those imposed by the underlying filesystem. For example,
$
./scribble /etc/passwd
will fail regardless of AppArmor, because I don’t have write permission on the file.
Profiling needs to be done with care. Too tight a profile means that the application can’t do its job. For example, one version of AppArmor I tested shipped with a profile for the PDF viewer
acroread, which, if enforced, prevented Adobe Acrobat Reader from viewing the AppArmor documentation!
How It Works
AppArmor installs a module into the Linux kernel that monitors resource usage of programs according to their profiles. A profile can be interpreted in one of two modes: enforce mode, and complain (or learning) mode. In complain mode (used by the create profile wizard), AppArmor logs a line to /var/log/audit/audit.log through the kernel logging daemon
klogd for each resource that the application accesses. Here’s a typical entry:
type=APPARMOR msg=audit(1144091465.305:6): PERMITTING w access to /home/chris/apple (scribble(26781) profile /home/chris/scribble active /home/chris/scribble)
In the second stage of profile generation, the profile wizard works its way through these lines, prompting you for the rules to be added. Behind the scenes, the utility
logprof does the work here. (
logprof can also be used to build the profile from the command line instead of using the YaST wizard.)
In enforce mode, system calls made by the process for resources not explicitly allowed by the profile will fail (and a message will be logged to /var/log/messages).
The profiles are stored in the directory /etc/apparmor.d. They are loaded into the kernel by the program
apparmor_parser. The profile for my little /home/chris/scribble application is written to the file home.chris.scribble. The profile I generated looks like this. The line numbers are for reference; they are not part of the file.
1 # Last Modified: Wed Dec 7 15:13:39 2005 2 /home/chris/scribble { 3 #include <abstractions/base> 4 5 /home/chris/orange w, 6 /home/chris/scribble r, 7 /tmp/banana w, 8 }
Line 2 (along with the matching bracket on line 8) defines the application that this profile applies to. Line 3 includes the contents of the file /etc/apparmor.d/abstractions/base. AppArmor uses a lot of
#include files to factor out common sets of access requirements into separate files. For example there are
#include files for access to audio devices, for authentication, and for access to name servers. The abstractions/base file referenced here is largely to do with allowing access to shared libraries. Lines 5 – 7 are the rules for this specific application.
To profile an application in complain mode, add the notation
flags=(complain) to line 2 of the profile, so that it reads:
/home/chris/scribble flags=(complain) {
You can also do this from the command line using:
#
complain
/etc/subdomain.d/home.chris.scribble
and you can set the profile back to enforce mode with:
#
enforce
/etc/subdomain.d/home.chris.scribble
Using
complain and
enforce also loads the new profile into the kernel.
AppArmor refers to the type of profiling I just performed as standalone profiling. It also supports systemic profiling, which puts all the profiles into complain mode and allows you to run them over many hours or days (even across reboots) to collect as complete a profile as possible.
The range of resource requests that AppArmor can allow or deny is broader than the simple file access checks used in this example. For example, it’s also capable of restricting program execution (via the
exec system call).
Table 8-4. Example profile rules
Earlier versions of AppArmor included rules that restricted the establishment of UDP and TCP connections. These rules have been removed from the current version of the product, but may be restored in a future version.
What About…
…deciding what to profile? AppArmor is not intended to provide protection against execution of ordinary tools run by ordinary users. You already have the classic Linux security model in place to constrain the activities of such programs. AppArmor is intended for use on servers which typically have few or no regular user accounts. Indeed, there is no way to define user-specific profiles in AppArmor, and there is no concept of a role.
AppArmor should be used to constrain programs that (quoting the user guide) “mediate privilege”; that is, programs that have access to resources that the person using the program does not have. Examples of such programs include:
Programs that run
setuidor
setgid(i.e., which run with the identity of the program’s owner or group). You can find programs that run setuid to root with the command:
#
find / -user root -perm -4000
Programs run as
cronjobs. You can find these by ferreting around in the crontab files in directories such as /etc/cron.d, /etc/cron.daily, /etc/cron.weekly, and so on.
Web applications; for example, CGI scripts or PHP pages invoked by a web server.
Network applications that have open ports. AppArmor provides a little utility called
unconfinedthat uses the output from
netstat -nlpto identify programs that are currently running with open network ports, but which currently have no profile.
Where to Learn More
For a brief but more technical overview, read the
apparmor manpage. For full details of the syntax of the profile files, read the
apparmor.d manpage.
There’s an interesting comparison of containment technologies such as chroot, Xen, selinux, and AppArmor at.
SUSE Linux 10.0 contains a detailed user guide for AppArmor in PDF format. Although it’s thorough, it is rather labored and has a decidedly non-open-source feel; it even contains the immortal line “contact your sales representative for more information.” This guide has been removed in SUSE Linux 10.1, but documentation is available by following the the links here. | https://www.linux.com/news/protect-your-applications-apparmor/ | CC-MAIN-2021-49 | refinedweb | 1,876 | 63.49 |
As todb pointed out in the last weekly metasploit update wrapup we recently added two new exploits for Flash: CVE-2015-3090 and CVE-2015-3105, based on the samples found in the wild.
As you're probably aware, the last years, and especially the end of 2014 and 2015, Flash has become the trending target for browser exploits in the wild. Here is a summary of Flash vulnerabilities abused by different Exploit Kits. It is based on the contagiodump overview and the Malware Dont Need Coffe blog data. It also shows the vulnerabilities actually supported in Metasploit, and the targets for every exploit. It's just a summary, maybe the vulnerability set is not complete! I'm not a malware researcher after all!
As you can read, we are doing our best to keep the Framework up to date with Flash vulnerabilities exploited in the wild, so hopefully people can simulate/test them from a confident source. Because of the amount of Flash exploits, we've added a kind of Flash exploitation library to make easier the task of adding them to the framework. We'd like to share 5 cents about how to use this code.
Let me start by refreshing our memory... Since
2013 Oct 2012 (thanks Haifei Lei) a common technique to exploit Flash vulnerabilities has been to abuse the AS3 Vectors, for both spraying and to achieve full memory read/write. It is facilitated by the Flash allocator and the own Vector object layout, whose length lives together with its data. The abuse of these objects has been well explained in the past. The first (and excellent) explanation which I can remind is the one provided by Haifei Li in his article Smashing the Heap with Vector: Advanced Exploitation Technique in Recent Flash Zero-day Attack. And it is precisely the technique used by the exploits in the Framework. Since I don't think I can explain it better than Haifei Li I recommend you to check the above link before going ahead, in case you're not familiar with the topic.
That said, back to the Metasploit Framework, let me start by helping you to locate the source code for the Flash exploitation library in the code base. It can be found on the data directory, at data/external/source/flash_exploiter path. Actually it supports exploitation for Adobe Flash (32 bits), ActiveX and plugin versions, for both Windows and Linux platforms. (Remark: we're not testing Flash coming with Google Chrome and IE since Windows 8, so the exploits available on MSF don't cover these targets actually). Last but not least, worths to say this code uses some ideas from @hdarwin89, whose flash exploits can be found on its own repository.
So, summarizing, the goal is which new Flash exploits just need to provide an "Exploit" class. An Exploit object must be able to corrupt a
Vector.<uint>'s length with the value 0x3fffffff or longer. Once this condition has been achieved the Exploit just needs to create a new "Exploiter" instance and allow the magic to happen. Here is an "Exploit" template:
package { import flash.display.Sprite import flash.display.LoaderInfo import mx.utils.Base64Decoder import flash.utils.ByteArray public class Exploit extends Sprite { private var uv:Vector.<uint> private var b64:Base64Decoder = new Base64Decoder() private var payload:ByteArray private var platform:String private var os:String private var exploiter:Exploiter public function Exploit() { platform = LoaderInfo(this.root.loaderInfo).parameters.pl os = LoaderInfo(this.root.loaderInfo).parameters.os var b64_payload:String = LoaderInfo(this.root.loaderInfo).parameters.sh var pattern:RegExp = / /g; b64_payload = b64_payload.replace(pattern, "+") b64.decode(b64_payload) payload = b64.toByteArray() /* The exploit code here. The goal is to corrupt the uv vector length with 0x3fffffff or bigger. */ exploiter = new Exploiter(this, platform, os, payload, uv, 0x13e) } } }
A couple of things to take into account. First of all, notice which the Exploit template get the platform and the operating system (as the shellcode) from FlashVars. It is because BrowserExploitServer provides this information from a prior stage, and we're using it, but you could get it by writing your own AS code on the exploit, of course.
The second important thing is the Exploiter constructor documentation, because it's the last call which the Exploit should do:
/* Creates an Exploiter instance and runs the exploitation magic * exp: Exploit object instance, its toString() vtable entry will be overwritten to achieve EIP. * pl: target platform, "linux" and "win" supported * os: target operating system for "win" platforms, "Windows 8.1" and "Windows 7" supported * p: ByteArray with the payload to execute * uv: Vector.<uint> whose length is overwritten with 0x3ffffffff or longer * uv_length: original uv's length, so the Exploiter can (hopefully) restore everything after exploitation. */ public function Exploiter(exp:Exploit, pl:String, os:String, p:ByteArray, uv:Vector.<uint>, uv_length:uint):void
Most of the Flash exploits in the framework have been written or migrated to use the Exploiter code, but be careful, because we keep updating the Exploiter code, and not all of them use the last version of the code! The Flash modules actually using the flash_exploiter code are: CVE-2014-0515, CVE-2014-0556, CVE-2014-0569, CVE-2014-8440, CVE-2015-0311, CVE-2015-0313, CVE-2015-0336, CVE-2015-0359, CVE-2015-3090 and CVE-2015-3105.
And that's all for today! Stay tuned for more Flash exploits and the new Browser Autopwn being developed by sinn3r. We find the combination of these a powerful way to simulate targeted campaigns on your next pentest! | https://blog.rapid7.com/2015/06/30/more-on-flash-exploits-into-the-framework/ | CC-MAIN-2020-45 | refinedweb | 926 | 54.93 |
Thread-local storage
From HaskellWiki
No facility for thread-local storage exists yet in an.
Robert Dockins has put forward a proposal[1].
Frederik Eaton posted an example API to the Haskell mailing list [2]. It depends on two new functions 'withParams' and 'getParams'.
import qualified Data.Map as M import Data.Maybe import Data.Unique import Data.IORef import Data.Typeable -- only these 2 must be implemented: withParams :: ParamsMap -> IO () -> IO () getParams :: IO ParamsMap -- type ParamsMap = M.Map Unique Value data Value = forall a . (Typeable a) => V a type IOParam a = IORef (Unique, a) newIOParam :: Typeable a => a -> IO (IOParam a) newIOParam def = do k <- newUnique newIORef (k,def) withIOParam :: Typeable a => IOParam a -> a -> IO () -> IO () withIOParam p value act = do (k,def) <- readIORef p m <- getParams withParams (M.insert k (V value) m) act getIOParam :: Typeable a => IOParam a -> IO a getIOParam p = do (k,def) <- readIORef p m <- getParams return $ fromMaybe def (M.lookup k m >>= (\ (V x) -> cast x))]. | http://www.haskell.org/haskellwiki/index.php?title=Thread-local_storage&oldid=5251 | CC-MAIN-2014-23 | refinedweb | 164 | 77.53 |
Making ConcurrentDictionary GetOrAdd thread safe using Lazy
I was browsing the ASP.NET Core MVC GitHub repo the other day, checking out the new 1.1.0 Preview 1 code, when I spotted a usage of
ConcurrentDictionary that I thought was interesting. This post explores the
GetOrAdd function, the level of thread safety it provides, and ways to add additional threading constraints.
I was looking at the code that enables using middleware as MVC filters where they are building up a filter pipeline. This needs to be thread-safe, so they sensibly use a
ConcurrentDictionary<>, but instead of a dictionary of
RequestDelegate, they are using a dictionary of
Lazy<RequestDelegate>. Along with the initialisation is this comment:
// 'GetOrAdd' call on the dictionary is not thread safe and we might end up creating the pipeline more // once. To prevent this Lazy<> is used. In the worst case multiple Lazy<> objects are created for multiple // threads but only one of the objects succeeds in creating a pipeline. private readonly ConcurrentDictionary<Type, Lazy<RequestDelegate>> _pipelinesCache = new ConcurrentDictionary<Type, Lazy<RequestDelegate>>();
This post will explore the pattern they are using and why you might want to use it in your code.
tl;dr; To make a
ConcurrentDictionaryonly call a delegate once when using
GetOrAdd, store your values as
Lazy<T>, and use by calling
GetOrAdd(key, valueFactory).Value.
The GetOrAdd function
The
ConcurrentDictionary is a dictionary that allows you to add, fetch and remove items in a thread-safe way. If you're going to be accessing a dictionary from multiple threads, then it should be your go-to class.
The vast majority of methods it exposes are thread safe, with the notable exception of one of the
GetOrAdd overloads:
TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory);
This overload takes a key value, and checks whether the key already exists in the database. If the key already exists, then the associated value is returned; if the key does not exist, the provided delegate is run, the value is stored in the dictionary, and then returned to the caller.
For example, consider the following little program.
public static void Main(string[] args) { var dictionary = new ConcurrentDictionary<string, string>(); var value = dictionary.GetOrAdd("key", x => "The first value"); Console.WriteLine(value); value = dictionary.GetOrAdd("key", x => "The second value"); Console.WriteLine(value); }
The first time
GetOrAdd is called, the dictionary is empty, so the value factory runs and returns the string
"The first value", storing it against the key. On the second call,
GetOrAdd finds the saved value and uses that instead of calling the factory. The output gives:
The first value The first value
GetOrAdd and thread safety.
Internally, the
ConcurrentDictionary uses locking to make it thread safe for most methods, but
GetOrAdd does not lock while
valueFactory is running. This is done to prevent unknown code from blocking all the threads, but it means that
valueFactory might run more than once if it is called simultaneously from multiple threads. Thread safety kicks in when saving the returned value to the dictionary and when returning the generated value back to the caller however, so you will always get the same value back from each call.
For example, consider the program below, which uses tasks to run threads simultaneously. It works very similarly to before, but runs the
GetOrAdd function on two separate threads. It also increments a counter every time the
valueFactory is run.
public class Program { private static int _runCount = 0; private static readonly ConcurrentDictionary<string, string> _dictionary = new ConcurrentDictionary<string, string>(); public static void Main(string[] args) { var task1 = Task.Run(() => PrintValue("The first value")); var task2 = Task.Run(() => PrintValue("The second value")); Task.WaitAll(task1, task2); PrintValue("The third value") Console.WriteLine($"Run count: {_runCount}"); } public static void PrintValue(string valueToPrint) { var valueFound = _dictionary.GetOrAdd("key", x => { Interlocked.Increment(ref _runCount); Thread.Sleep(100); return valueToPrint; }); Console.WriteLine(valueFound); } }
The
PrintValue function again calls GetOrAdd on the
ConcurrentDictionary, passing in a
Func<> that increments the counter and returns a string. Running this program produces one of two outputs, depending on the order the threads are scheduled; either
The first value The first value The first value Run count: 2
or
The second value The second value The second value Run count: 2
As you can see, you will always get the same value when calling
GetOrAdd, depending on which thread returns first. However the delegate is being run on both asynchronous calls, as shown by
_runCount=2, as the value had not been stored from the first call before the second call runs. Stepping through, the interactions could look something like this:, and returns the value
"The first value"back to the concurrent dictionary. The dictionary checks there is still no value for
"key", and inserts the new
KeyValuePair. Finally, it returns
"The first value"to the caller.
Thread B completes its invocation and returns the value
"The second value"back to the concurrent dictionary. The dictionary sees the value for
"key"stored by Thread A, so it discards the value it created and uses that one instead, returning the value back to the caller.
Thread C calls
GetOrAddand finds the value already exists for
"key", so returns the value, without having to invoke
valueFactory
In this case, running the delegate more than once has no adverse effects - all we care about is that the same value is returned from each call to
GetOrAdd. But what if the delegate has side effects such that we need to ensure it is only run once?
Ensuring the delegate only runs once with Lazy
As we've seen, there are no guarantees made by
ConcurrentDictionary about the number of times the
Func<> will be called. When building a middleware pipeline, however, we need to be sure that the middleware is only built once, as it could be doing some bootstrapping that is expensive or not thread safe. The solution that the ASP.NET Core team used is to use
Lazy<> initialisation.
The output we are aiming for is
The first value The first value The first value Run count: 1
or similarly for
"The second value" - it doesn't matter which wins out, the important points are that the same value is returned every time, and that
_runCount is always 1.
Looking back at our previous example, instead of using a
ConcurrentDictionary<string, string>, we create a
ConcurrentDictionary<string, Lazy<string>>, and we update the
PrintValue() method to create a lazy object instead:
public static void PrintValueLazy(string valueToPrint) { var valueFound = _lazyDictionary.GetOrAdd("key", x => new Lazy<string>( () => { Interlocked.Increment(ref _runCount); Thread.Sleep(100); return valueToPrint; })); Console.WriteLine(valueFound.Value); }
There are only two changes we have made here. We have updated the
GetOrAdd call to return a
Lazy<string> rather than a
string directly, and we are calling
valueFound.Value to get the actual string value to write to the console. To see why this solves the problem, lets step through the example to see an example of what happens when we run the whole program., returning an uninitialised
Lazy<string>object. The delegate inside the
Lazy<string>has not been run at this point, we've just created the
Lazy<string>container. The dictionary checks there is still no value for
"key", and so inserts the
Lazy<string>against it, and finally, returns the
Lazy<string>back to the caller.
Thread B completes its invocation, similarly returning an uninitialised
Lazy<string>object. As before, the dictionary sees the
Lazy<string>object for
"key"stored by Thread A, so it discards the
Lazy<string>it just created and uses that one instead, returning it back to the caller.
Thread A calls
Lazy<string>.Value. This invokes the provided delegate in a thread safe way, such that if it is called simultaneously by two threads, it will only run the delegate once.
Thread B calls
Lazy<string>.Value. This is the same
Lazy<string>object that Thread A just initialised (remember the dictionary ensures you always get the same value back.) If Thread A is still running the initialisation delegate, then Thread B just blocks until it finishes and it can access the result. We just get the final return
string, without invoking the delegate for a second time. This is what gives us the run-once behaviour we need.
Thread C calls
GetOrAddand finds the
Lazy<string>object already exists for
"key", so returns the value, without having to invoke
valueFactory. The
Lazy<string>has already been initialised, so the resulting value is returned directly.
We still get the same behaviour from the
ConcurrentDictionary in that we might run the
valueFactory more than once, but now we are just calling
new Lazy<>() inside the factory. In the worst case, we create multiple
Lazy<> objects, which get discarded by the
ConcurrentDictionary when consolidating inside the
GetOrAdd method.
It is the
Lazy<> object which enforces that we only run our expensive delegate once. By calling
Lazy<>.Value we trigger the delegate to run in a thread safe way, such that we can be sure it will only be run by one thread at a time. Other threads which call
Lazy<>.Value simultaneously will be blocked until the first call completes, and then will use the same result.
Summary
When using
GetOrAdd , if your
valueFactory is idempotent and not expensive, then there is no need for this trick. You can be sure you will always get the same value with each call, but you need to be aware the
valueFactory may run multiple times.
If you have an expensive operation that must be run only once as part of a call to
GetOrAdd, then using
Lazy<> is a great solution. The only caveat to be aware of is that
Lazy<>.Value will block other threads trying to access the value until the first call completes. Depending on your use case, this may or may not be a problem, and is the reason
GetOrAdd does not have these semantics by default. | http://andrewlock.net/making-getoradd-on-concurrentdictionary-thread-safe-using-lazy/ | CC-MAIN-2016-50 | refinedweb | 1,665 | 53.31 |
Part. I'll start by recapping some basics from the introduction to JiBX in Part 2. -- which you're then required to use in your application --.
The biggest single difference between JiBX and the other data binding frameworks is in how they handle an input XML document. Most XML parsers for the Java language implement the SAX2 API for use by the application program. This API has been refined over a period of years and is supported by many different parser implementations, including the most fully-featured parsers available today.
Despite it's widespread usage, the SAX2 API has some serious drawbacks for many types of XML processing. These result from the style of interface implemented by SAX2 -- a push parsing approach. In push parsing, you define methods within your code that implement interfaces defined by the parser API. You then pass these methods (in the form of a handler) to the parser, along with a document to be parsed. The parser goes through the text of the document and interprets it according to XML rules, calling your handler methods to report the document components (elements, character data content, and so forth.) as it finds them in the text. Once the parser has completely processed the input document, it returns control back to your application -- but in the meantime the parser is in control.
The problem with this approach is that it requires your
handler code to always know where the parser is in the document, and to
interpret the components appropriately. At the most basic level, an element
containing a simple text value is reported as three (or more) separate
components: first the start tag, then the text (which may be in multiple
pieces), and finally the end tag. Your handler generally needs to accumulate
text until the end tag is reported, and then do something with the text. The "something" it does may be affected by other items, such as the
attributes of the start tag, so that's more information that needs to be
held. The net result is that handler code for push parsing
tends to involve a lot of
String matching on
element names in chained
if statements (or the equivalent using a
java.util.Hashtable). This is messy
to write and messy to maintain, not to mention inefficient.
Pull parsing turns. Take the case of an element that contains text: You can write your code with the knowledge that the element you're processing has text content, and just process it directly -- effectively one call to get the start tag, one call to get the content, and a third to get the end tag.
Better yet, you can write a method that handles any element that contains a text value -- just call the method with the expected element name, and it can return the text content (or an error, if the expected element is missing). This is especially convenient for building objects from XML (which is what unmarshalling is all about). Most XML documents use fixed ordering of child elements, so processing the children of a particular element becomes as simple as just making one call after another to this method. This is both simpler and faster than a SAX2-style handler approach.
JiBX extensively uses this technique of combining multiple parser operations in a single method. It wraps an internal pull parser interface in an unmarshalling context class that defines a variety of element and attribute access methods. These methods handle both parsing and data conversions to primitive types, along with specialized types of operations such as tracking objects with unique identifiers. Here are some examples of these methods:
parsePastStartTag(ns, name)-- Parses past the start of element, which must be the next parse component seen other than character data. Leaves the parse positioned following the start tag.
attributeText(ns, name)-- Gets text value of required attribute from current start tag.
attributeInt(ns, name, dflt)-- Gets
intvalue of optional attribute from current start tag (returning default value if attribute is not present).
parseContentText(ns, name)-- Parses past the end of the current element, which must have only character data content. Returns the content.
parseElementText(ns, name)-- Parses the next element, which must have only character data content. Returns the content.
Wrapping the parser within an unmarshalling context allows a wide variety of access methods to be defined with a minimum of code. It also provides isolation from the actual parser being used. Because of this, the generated code that gets added to your classes is not specific to a particular parser, or even to a particular type of parser. This may be an important concern for the future. Right now the unmarshalling context is coded to use a parser that implements the XMLPull interface, an informal standard defined by some of the leading developers in the area of pull parsing. In the future, there's likely to be a Java technology standard for pull parsers. When that standard becomes available, JiBX will be able to use the standard with only minor changes to the unmarshalling context code.
JiBX uses a second type of context, the marshalling context, for writing an XML document when marshalling. Just as the unmarshalling context wraps the parser and provides a variety of specialized convenience methods for unmarshalling, the marshalling context wraps an output stream and provides its own set of convenience methods. These methods provide a component-at-a-time interface for constructing the output document. Here's a simplified list of basic methods:
startTag(nsi, name)-- Generates start tag without attributes.
startTagAttributes(nsi, name)-- Generates start tag with attributes to be added.
attribute(nsi, name, value)-- Adds attribute to current start tag (value may be
Stringor primitive type).
closeStartEmpty()-- Closes start tag with no content (empty element).
closeStartContent()-- Closes start tag with content to follow.
textContent(value)-- Adds character data content to current element (
Stringor primitive).
endTag(nsi, name)-- Generates end tag for element.
This interface for generating XML is simpler than those used by many other frameworks. It's designed primarily for use by code that's added by the JiBX framework rather than written by hand, so it avoids state checks and similar safeguards. It does properly handle escaping special characters as entities in text, but other than that it's up to the calling program to use the interface properly.
In the form shown here, this interface works with namespace indices. The marshalling context keeps an internal array of prefixes for namespaces, so looking up the prefix when generating output is just a matter of indexing into this array (as opposed to requiring a mapping operation, which would be needed if actual namespace URIs were passed). This approach is a compromise that simplifies handling without throwing away flexibility. An earlier version of the interface required static construction of qualified names (including a namespace prefix, if needed) for elements and attributes. This worked well for generating text output, but would have been difficult to convert to other forms of output (such as a parse event stream for building a DOM representation of the document).The newer form of the interface makes conversion much easier.
Java-centric versus XML-centric
Most of the data binding frameworks for Java language programs are focused on code generation from W3C XML Schema grammars. Using this approach, you start with a Schema grammar for the documents to be processed, then use a program that's part of the data binding framework to generate the Java language source code for a set of classes (the object model) that correspond to the Schema. This works well for many applications, especially those where the Schema grammars are defined in advance and not subject to change during the course of the project. For these types of applications, the object model constructed from a Schema can provide a very fast way to start working with documents.
The main drawback to the generated object model approach is that it ties your code directly to the structure of the XML document. Because of this, I call it an XML-centric approach. With a generated object model, your application code is forced to use an interface that reflects the XML structure rather than the structure the application may want to impose on the data in a document. This means there's no isolation between the XML and your application -- if the XML document structure (the Schema) changes in any significant respect, you'll need to regenerate the object model and change your application code to match.
A few data binding frameworks (including JiBX) have implemented an alternative approach, generally called mapped binding. This is what I call a Java-centric approach. It works with classes you define in your application rather than forcing the use of a set of generated classes. Although this is convenient for developers, it makes the framework's job more complex. The framework somehow needs to get data into and out of the application classes in a consistent manner, without forcing the application classes to follow a rigid model. This is where another of the differences between JiBX and the other data binding frameworks enters in.
Reflecting on performance
When a framework needs to get data into and out of a variety of Java language classes, the usual way of doing this is by using reflection. This is the approach taken by Castor, for instance, in its mapped binding support. is a way of accessing information about a Java language class at runtime. It can be used to access fields and methods in instances of a class, providing a way of dynamically hooking together classes at runtime without the need for any source code links between the classes.
Reflection is a great basis for many types of frameworks that work with Java classes, but it does have some drawbacks when used for data binding. For one thing, it generally requires you to use public fields or methods in your classes to allow reflection to operate properly. This means you need to provide access to internal state information as part of your public API, when really it should only be accessible by the binding framework. Reflection also suffers a performance disadvantage when compared to calling a method or accessing a field directly in compiled code.
Because of these limitations I wanted to avoid using reflection for data binding in JiBX. The developers of the Java Data Objects (JDO) specification had faced similar problems in moving data between Java language objects and databases. In their case, they avoided using reflection by instead working directly with class files, adding code to the classes generated by the compiler in order to provide direct access for the framework. I chose to use this same approach for JiBX.
The JDO team came up with a great term to describe the process of munging (see Resources) the class files generated by a compiler: "Byte code enhancement." Sounds much better than saying your class files are being "mangled" or "implanted", doesn't it? I don't think I can improve on the term, so I'm just shamelessly expropriating it for use by the JiBX framework as well.
The actual class file modifications are done by a JiBX component called the binding compiler. The binding compiler is executed at program assembly time -- after you've compiled your Java language source code to class files, but before packaging or executing the class files. The binding compiler reads one or more binding definition documents (see Defining bindings). For each class included in any of the bindings it adds the appropriate marshalling or unmarshalling code.
In general, you get a pair of added methods in your bound class files for each marshalling or unmarshalling binding that includes that class. There are some exceptions to this -- if a class is treated exactly the same way in multiple bindings those bindings reuse a single set of methods, and some types of binding operations may require more or fewer added methods. Four methods per binding (two for marshalling, two for unmarshalling) is about the average, though.
The binding compiler also generates some added support classes that go along with the added methods. Basically, one small helper class is added for each class that's included in any of the bindings, along with a separate class per binding. In the special case of unmarshalling forward references to objects identified by an ID value, the equivalent of a small inner class is also generated to fill in the value of the forward-referenced object once it's been unmarshalled.
Normally the total number of added classes and the total size of the added code is fairly small. The sample you can download from the JiBX site includes an example based on the Part 2 test code (see Resources). This generates 6 added classes and 23 added methods, with a total added size of 9 KB, to handle a binding involving 5 classes. This sounds like a lot -- but compare this with other alternatives based on code generation from a grammar in Figure 1. This shows the total code size for JiBX, including both base classes and the added binding code, compared with the total generated code size for the other frameworks. Only Quick is able to do better than JiBX in code size.
Figure 1. Binding code comparison
The JiBX binding compiler described in the last section works from binding definitions that you supply. Binding definitions are themselves XML documents, with a DTD grammar included in the download. Unlike most other data binding frameworks, JiBX supports using any number of binding definitions in combination. You can, for instance, unmarshal a document using one binding, make changes, then marshal the data objects to an output document using a different binding.
A binding definition lets you control such basic details as whether a
particular simple property of a class (such as a primitive value, or a
String) is mapped to an element or formatters
for converting simple values to and from text.
However, JiBX goes beyond this simple form of mapping. Other data binding frameworks generally force each XML element with complex content (attributes or child elements) to be mapped to and from a distinct object, so that your object model directly matches the layout of your XML documents. With JiBX you can be more flexible: Child elements can be defined using a subset of the properties of an object, and properties of a referenced object can be included directly as simple child elements or attributes of the current element. This lets you make many types of changes to either your class structure or your XML document structure without needing to change the other to match.
I call this type of mapping, where XML elements do not correspond directly to Java language objects, a structure mapping. For a simple example of how this works with JiBX, consider the following XML document:
Listing 1. Sample XML document
Most data binding frameworks support mapping this document to instances of classes along the lines of:
Listing 2. Classes matching document structure
Most frameworks also allow you to change the names of the fields,
to use
customerName instead of
name, and
first rather than
firstName, for example. Some
frameworks also use get/set methods rather than the public fields shown
here, but the principle remains the same.
What most frameworks will not allow you to do is to bring
the values within the
name element into the object that corresponds
to the
customer element. In other words, you can't map the XML to this
class:
Listing 3. Same data in a single class
Nor can you map the XML to a pair of classes like these:
Listing 4. Classes with different structure
JiBX does allow you to do this type of mapping. This means the structure of your objects is not tied to the structure of the XML -- you can restructure your object classes without needing to change the XML format used for external data transfer. I'll give you specifics on this (including actual mapping files for the above pair of examples) in the next article in this series.
The basic architecture of JiBX is very different from those of other XML data binding frameworks for Java applications. This leads to both advantages and drawbacks when comparing JiBX with these other frameworks. On the plus side, JiBX gains the advantages of very fast operation, a compact runtime, and greater isolation between XML document formats and Java language object structures. On the minus side, it's based on a relatively unproven parser technology and does not support the validation flexibility provided by some of the alternatives (especially JAXB).
Some of the other differences between JiBX and alternative frameworks are less clear-cut. For instance, JiBX's technique of class file enhancement offers the advantage of keeping your source code clean -- the binding code is added after you compile, so you never need to deal with it directly -- but at the costs of an added step in the build process and potential confusion in tracking problems in your code accessed during marshalling or unmarshalling. For some users and applications, one or another of these factors will be more important than others.
Part 4 of this series will dive into the details of using JiBX in your applications. Once I've shown you how to use it I'll also return to this issue of what I see as JiBX's weaker points, and go on to suggest some possible ways in which these can be strengthened in the future. Check out Part 4 to get the rest of the JiBX story!
-).
- If you need background on XML, try the developerWorks "Introduction to XML tutorial" (August 2002).
- Review the author's previous developerWorks articles covering performance (September 2001) and usage (February 2002) comparisons for Java XML document models.
- Go to the source(Forge) to find out about the widely used SAX2 parser API for push parsing XML.
- Learn about the fast and flexible XmlPull parser API developed by some of the leading pull parser researchers.
- Track the progress of the Java Specification Request for a Streaming API for XML (StAX).
-).
- Find out more about the Java Architecture for XML Binding (JAXB), the evolving standard for Java Platform data binding.
- Take a closer look at the Castor framework, which supports both mapped and generated bindings.
-.
- Curious what "munging" means? Look it up in The Jargon Dictionary.
-_1<<
Dennis Sosnoski (dms@sosnoski.com) is the founder and lead consultant of. | http://www.ibm.com/developerworks/library/x-databd3/index.html | crawl-002 | refinedweb | 3,081 | 59.03 |
Using OLE DB Connections from Script Tasks
I write scripts on a pretty regular basic, and often need to access database connections from them. It’s pretty easy to do this if you are using an ADO.NET connection. However, if you are using OLE DB, you have to go through a couple of additional steps to convert the connection to an ADO.NET version. Matt Masson posted a great code sample for doing this conversion.
I use a slightly altered version of this code pretty regularly. It’s been modified to support both OLE DB and ADO.NET connections, so that I can switch connections without having to change the script code.
To use it, you need to add a reference in your script project to Microsoft.SqlServer.DTSRuntimeWrap. Then, add the following to the usings section at the top of the script:
using System.Data.Common; using Wrap = Microsoft.SqlServer.Dts.Runtime.Wrapper;
For the code to get the connection, use the following:
ConnectionManager cm = Dts.Connections["MyConnection"]; DbConnection conn = null; if (cm.CreationName == "OLEDB") { Wrap.IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as Wrap.IDTSConnectionManagerDatabaseParameters100; conn = cmParams.GetConnectionForSchema() as DbConnection; } else { conn = cm.AcquireConnection(null) as DbConnection; } if (conn.State == ConnectionState.Closed) { conn.Open(); } // TODO: Add your code here conn.Close(); Dts.TaskResult = (int)ScriptResults.Success;
You can use the “conn” object to perform actions against the connection. Since it’s using the common DBConnection interface, you can use it against any database connection that you have an ADO.NET provider for (which includes OLE DB providers).
Looks good, but I need to do the same thing from a Script Componant. Any ideas? | http://agilebi.com/jwelch/2011/08/17/oledb-connections-in-script-tasks/ | CC-MAIN-2015-32 | refinedweb | 273 | 52.36 |
Like linked lists, trees are made up of nodes. A common kind of tree
is a binary tree, in which each node contains a reference to two
other nodes (possibly null). and two
tree references.
The process of assembling a tree is similar
to the process of assembling a linked list.
Each constructor invocation builds a single node.
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
The cargo can
be any type, but the arguments for left and right should be
tree nodes. left and right are optional; the default
value is None.
To print a node, we just print the cargo.
One way to build a tree is from the bottom up.
Allocate the child nodes first:
left = Tree(2)
right = Tree(3)
Then create the parent node and link it to the children:
tree = Tree(1, left, right);
We can write this code more concisely by nesting constructor
invocations:
>>> tree = Tree(1, Tree(2), Tree(3))
Either way, the result is the tree at the beginning of the
chapter.
Any time you see a new data structure, your first
question should be, "How do I traverse it?" The most natural
way to traverse a tree is recursively. For example, if the
tree contains integers as cargo, this function returns their sum:
def total(tree):
if tree == None: return 0
return total(tree.left) + total(tree.right) + tree.cargo
The base case is the empty tree, which contains no cargo, so
the sum is 0.
The recursive step
makes two recursive calls to find the sum of the child trees.
When the recursive calls complete,
we add the cargo of the parent and return the
total.:
>>> tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3))).
We can traverse an expression tree and print the contents like this:
def printTree(tree):
if tree == None: return
print tree.cargo,
printTree(tree.left)
printTree(tree.right):
>>> tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3)))
>>> printTree(tree)
+ 1 * 2 3:
def printTreInorder(tree.right).
Asented(tree.left, level+1):
>>> printTreeIndented(tree)
3
*
2
+
1
If you look at the output sideways, you see a simplified version
of the original figure..:
>>> tokenList = [9, '*', 11, 'end']
>>> tree = getProduct(tokenList)
>>> printTreePostorder(tree)
9 11 *
>>> tokenList = [9, '+', 11, 'end']
>>> tree = getProduct(tokenList)
>>> printTreePostorder(tree)
9Product, we can handle
an arbitrarily long product:
def getProduct(tokenList):
a = getNumber(tokenList)
if getToken(tokenList, '*'):
b = getProduct(tokenList) # this line changed
return Tree ('*', a, b)
else:
return a:
>>> tokenList = [2, '*', 3, '*', 5 , '*', 7, 'end']
>>> tree = getProduct(tokenList)
>>> printTreePostorder(tree)
2 3 5 7 * * *. a name
more descriptive of its new role..
def get.
In this section, we develop a small program that uses a tree
to represent a knowledge base.
The program interacts with the user to create a tree of questions
and animal names. Here is a sample run:
Are you thinking of an animal? y
Is it a bird? n
What is the animals name? dog
What question would distinguish a dog from a bird? Can it fly
If the animal were dog the answer would be? n
Are you thinking of an animal? y
Can it fly? n
Is it a dog? n
What is the animals name? cat
What question would distinguish a cat from a dog? Does it bark
If the animal were cat the answer would be? n
Are you thinking of an animal? y
Can it fly? n
Does it bark? y
Is it a dog? y
I rule!
Are you thinking of an animal? n:
def. | http://greenteapress.com/thinkpython/thinkCSpy/html/chap20.html | CC-MAIN-2017-47 | refinedweb | 602 | 75.91 |
Ryan Dahl, creator of Node.js, has spent the last year and a half working on Deno, a new runtime for JavaScript that is supposed to fix all the inherent problems of Node.
Don’t get me wrong, Node is a great server-side JavaScript runtime in its own right, mostly due to its vast ecosystem and the usage of JavaScript. However, Dahl admits there are a few things he should have thought about more — security, modules, and dependencies, to name a few.
In his defense, it’s not like he could envision how much the platform would grow in such a short period of time. Also, back in 2009, JavaScript was still this weird little language that everyone made fun of, and many of its features weren’t there yet.
What is Deno, and what are its main features?
Deno is a secure Typescript runtime built on V8, the Google runtime engine for JavaScript.
It was built with:
- Rust (Deno’s core was written in Rust, Node’s in C++)
- Tokio (the event loop written in Rust)
- TypeScript (Deno supports both JavaScript and TypeScript out of the box)
- V8 (Google’s JavaScript runtime used in Chrome and Node, among others)
So let’s see what features Deno offers.
Security (permissions)
Among the most important of Deno’s features is its focus on security.
As opposed to Node, Deno by default executes the code in a sandbox, which means that runtime has no access to:
- The file system
- The network
- Execution of other scripts
- The environment variables
Let’s take a look at how the permission system works.
(async () => { const encoder = new TextEncoder(); const data = encoder.encode('Hello world\n'); await Deno.writeFile('hello.txt', data); await Deno.writeFile('hello2.txt', data); })();
The script creates two text files called
hello.txt and
hello2.txt with a
Hello world message within. The code is being executed inside a sandbox, so it has no access to the file system.
Also note that we are using the Deno namespace instead of the fs module, as we would in Node. The Deno namespace provides many fundamental helper functions. By using the namespace, we are losing the browser compatibility, which will be discussed later on.
When we run it by executing:
deno run write-hello.ts
We are prompted with the following:
⚠️Deno requests write access to "/Users/user/folder/hello.txt". Grant? [a/y/n/d (a = allow always, y = allow once, n = deny once, d = deny always)]
We are actually prompted twice since each call from the sandbox must ask for permission. Of course if we chose the
allow always option, we would only get asked once.
If we choose the
deny option, the
PermissionDenied error will be thrown, and the process will be terminated since we don’t have any error-handling logic.
If we execute the script with the following command:
deno run --allow-write write-hello.ts
There are no prompts and both files are created.
Aside from the
--allow-write flag for the file system, there are also
--allow-net,
--allow-env, and
--allow-run flags to enable network requests, access the environment, and for running subprocesses, respectively.
Modules
Deno, just like browsers, loads modules by URLs. Many people got confused at first when they saw an import statement with a URL on the server side, but it actually makes sense — just bear with me:
import { assertEquals } from "";
What’s the big deal with importing packages by their URLs, you may ask? The answer is simple: by using URLs, Deno packages can be distributed without a centralized registry such as
npm, which recently has had a lot of problems, all of them explained here.
By importing code via URL, we make it possible for package creators to host their code wherever they see fit — decentralization at its finest. No more
package.json and
node_modules.
When we start the application, Deno downloads all the imported modules and caches them. Once they are cached, Deno will not download them again until we specifically ask for it with the
--reload flag.
There are a few important questions to be asked here:
What if a website goes down?
Since it’s not a centralized registry, the website that hosts the module may be taken down for many reasons. Depending on its being up during development — or, even worse, during production — is risky.
As we mentioned before, Deno caches the downloaded modules. Since the cache is stored on our local disk, the creators of Deno recommend checking it in our version control system (i.e., git) and keeping it in the repository. This way, even when the website goes down, all the developers retain access to the downloaded version.
Deno stores the cache in the directory specified under the
$DENO_DIR environmental variable. If we don’t set the variable ourselves, it will be set to the system’s default cache directory. We can set the
$DENO_DIR somewhere in our local repository and check it into the version control system.
Do I have to import it by the URL all the time?
Constantly typing URLs would be very tedious. Thankfully, Deno presents us with two options to avoid doing that.
The first option is to re-export the imported module from a local file, like so:
export { test, assertEquals } from "";
Let’s say the file above is called
local-test-utils.ts. Now, if we want to again make use of either
test or
assertEquals functions, we can just reference it like this:
import { test, assertEquals } from './local-test-utils.ts';
So it doesn’t really matter if it’s loaded from a URL or not.
The second option is to create an imports map, which we specify in a JSON file:
{ "imports": { "http/": "" } }
And then import it as such:
import { serve } from "http/server.ts";
In order for it to work, we have to tell Deno about the imports map by including the
--importmap flag:
deno run --importmap=import_map.json hello_server.ts
What about package versioning?
Versioning has to be supported by the package provider, but from the client side it comes down to just setting the version number in the URL like so:.
Browser compatibility
Deno aims to be browser-compatible. Technically speaking, when using the ES modules, we don’t have to use any build tools like webpack to make our application ready to use in a browser.
However, tools like Babel will transpile the code to the ES5 version of JavaScript, and as a result, the code can be run even in older browsers that don’t support all the newest features of the language. But that also comes at the price of including a lot of unnecessary code in the final file and bloating the output file.
It is up to us to decide what our main goal is and choose accordingly.
TypeScript support out of the box
Deno makes it easy to use TypeScript without the need for any config files. Still, it is possible to write programs in plain JavaScript and execute them with Deno without any trouble.
Summary
Deno, the new runtime for TypeScript and JavaScript, is an interesting project that has been steadily growing for quite some time now. But it still has a long way to go before it’s considered production-ready.
With it’s decentralized approach, it takes the necessary step of freeing the JavaScript ecosystem from the centralized package registry that is npm.
Dahl says that he expects to release version 1.0 by the end of the summer, so if you are interested in Deno’s future developments, star its repository. “What’s Deno, and how is it different from Node.js?”
Why should people commit the modules into their repo? Man, it’s a waste of space. I had hoped Node.js creators will follow Go creators in terms of managing package.
Yes would it be possible to get a citation for the Deno team recommending storing the cache in the project directory?
@alastair
“Relying on external servers is convenient for development but brittle in production. Production software should always bundle its dependencies. In Deno this is done by checking the $DENO_DIR into your source control system, and specifying that path as the $DENO_DIR environmental variable at runtime.”
@Maciej thanks for the reply; I more meant a link to wherever the Deno team recommended storing the cache in the project directory *over* the system’s default cache directory.
Great article on the whole btw, really interesting stuff.
This is very surprising, it’s like asking to check-in node_modules to avoid dependency issues. Which actually would avoid a ton of issues but it makes the git repository huge and hard to use.
There are typically tens of thousands of files in node_modules, that’s why we avoid to commit this folder. I wonder how this will work in practice, I actually wouldn’t mind taking longer to clone a repo if it ensures that no-one will run into versioning issues in the project, due to different machines having installed different versions of some library.
I don’t understand these complaints. How is bundling dependencies and cloning them later any different than doing an `npm install`? You have to download these files one way or another…
I guess the difference will be that in npm you are downloading a lot of garbage with every package like readme files etc. In deno on the other hand you will be caching nothing more than minified javascript.
Well, a package represents a artifact, while a repo should only hold source code and configs. | https://blog.logrocket.com/what-is-deno/ | CC-MAIN-2019-39 | refinedweb | 1,600 | 62.58 |
Introduction:
The DriveInfo class in C# is one of the important classes in
the System.IO namespace, since it can get the system information like drive type, the space,
etc.., We will discuss this class in detail with a sample application.
How to Get the Drives:
The drives in the system can be used by the GetDrives method
in the DriveInfo class. It will return a collection of DriveInfo objects.
DriveInfo[] driveInfo = DriveInfo.GetDrives();
DriveInfo Class:
The System.IO namespace has a class which helps the
users to interact with the system to get the file details, directory details
and system information. The DriveInfo class is a readonly class and can be used
to get details about the drives.
It has the following properties in the DriveInfo class. Let
us see the one by one.
DriveInfo driveInfo = new DriverInfo("Drive Name");
The drive name has to be passed as constructor to get the
details about the drive in the system.
Name:
The name is one of the property in the DriveInfo class which
gives the name of the drive like C or D...
DriveType:
The DriveType is enum type in the System.IO namespace and it
has set of enum numbers.
It will give the details of type f DriveType. As you know
that there are some times of drive like system drive, removable drive, cd rom...
Ready:
This is Boolean type of property which tell us whether the
drive is ready or not. Because some the drive allocated for the device like
removable, CD ROM. But it will be enabled when the device is plugged with the
device.
TotalSize:
The total size of the drive can be manipulated based on the
device state. If it is system drive then it will be ready when the OS is
running. But the same time the device like Removable and CD ROW size will be
manipulated only when the state is Ready. Otherwise it will not give any such
details.
AvailableFreeSpace:
This is also one of the peoperty in the class and which
tells the available space in the drive when the state of the device is ready.
VolumeLabel:
Every drive will have the volume label, which will be
returned by the driveinfo class.
Conclusion:
The DriveInfo class is one of the very useful classes to
scale the drive information. The source code attached in the article.
DriveInfo Class in C# with an Example
Dig Out on Named vs Optional Arguments Clear Implementation in C# 4.0
Hi dudes,
Thank you very much for reading this.
Hi Senthilkumar. Good article.
well explained... good work..
Nice article, Senthilkumar. It is so helpful.
great work. | http://www.c-sharpcorner.com/UploadFile/skumaar_mca/driveinfo-class-in-C-Sharp-with-example/ | crawl-003 | refinedweb | 441 | 74.59 |
304c61a24f909168c16793ccf7c686237e53d003 (commit) from cb7be1590e9b18e272e72eb4e910a7ad06a53bd0 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log -----------------------------------------------------------------;a=commitdiff;h=304c61a24f909168c16793ccf7c686237e53d003 commit 304c61a24f909168c16793ccf7c686237e53d003 Author: DJ Delorie <dj@redhat.com> Date: Wed Dec 5 12:39:47 2018 -0500 test-container: move postclean outside of namespace changes During postclean.req testing it was found that the fork in the parent process (after the unshare syscall) would fail with ENOMEM (see recursive_remove() in test-container.c). While failing with ENOMEM is certainly unexpected, it is simply easier to refactor the design and have the parent remain outside of the namespace. This change moves the postclean.req processing to a distinct process (the parent) that then forks the test process (which will have to fork once more to complete uid/gid transitions). When the test process exists the cleanup process will ensure all files are deleted when a post clean is requested. Signed-off-by: DJ Delorie <dj@redhat.com> Reviewed-by: Carlos O'Donell <carlos@redhat.com> [BZ #23948] * support/test-container.c: Move postclean step to before we change namespaces. diff --git a/ChangeLog b/ChangeLog index 8d2494e..d98a9ce 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,9 @@ +2018-12-10 DJ Delorie <dj@redhat.com> + + [BZ #23948] + * support/test-container.c: Move postclean step to before we + change namespaces. + 2018-12-10 Joseph Myers <joseph@codesourcery.com> * scripts/gen-as-const.py (main): Handle --python option. diff --git a/support/test-container.c b/support/test-container.c index df450ad..1d1aebe 100644 --- a/support/test-container.c +++ b/support/test-container.c @@ -921,6 +921,43 @@ main (int argc, char **argv) } } + if (do_postclean) + { + pid_t pc_pid = fork (); + + if (pc_pid < 0) + { + FAIL_EXIT1 ("Can't fork for post-clean"); + } + else if (pc_pid > 0) + { + /* Parent. */ + int status; + waitpid (pc_pid, &status, 0); + + /* Child has exited, we can post-clean the test root. */ + printf("running post-clean rsync\n"); + rsync (pristine_root_path, new_root_path, 1); + + if (WIFEXITED (status)) + exit (WEXITSTATUS (status)); + + if (WIFSIGNALED (status)) + { + printf ("%%SIGNALLED%%\n"); + exit (77); + } + + printf ("%%EXITERROR%%\n"); + exit (78); + } + + /* Child continues. */ + } + + /* This is the last point in the program where we're still in the + "normal" namespace. */ + #ifdef CLONE_NEWNS /* The unshare here gives us our own spaces and capabilities. */ if (unshare (CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS) < 0) @@ -974,14 +1011,6 @@ main (int argc, char **argv) int status; waitpid (child, &status, 0); - /* There's a bit of magic here, since the buildroot is mounted - in our space, the paths are still valid, and since the mounts - aren't recursive, it sees *only* the built root, not anything - we would normally se if we rsync'd to "/" like mounted /dev - files. */ - if (do_postclean) - rsync (pristine_root_path, new_root_path, 1); - if (WIFEXITED (status)) exit (WEXITSTATUS (status)); ----------------------------------------------------------------------- Summary of changes: ChangeLog | 6 ++++++ support/test-container.c | 45 +++++++++++++++++++++++++++++++++++++-------- 2 files changed, 43 insertions(+), 8 deletions(-) hooks/post-receive -- GNU C Library master sources | https://sourceware.org/ml/glibc-cvs/2018-q4/msg00277.html | CC-MAIN-2020-05 | refinedweb | 487 | 57.37 |
def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)
Can you tell me what this code does?
data class User(val name: String, val age: Int)
What about this?
The first is a Scala implementation of Euclid's algorithm for calculating the greatest common divisor. It says that if
y is 0, the GCD of
x and
y is
x, otherwise it's the GCD of
y and
x mod y.
The Scala code is essentially a direct translation of the algorithm, and even if you don't know Scala you can more or less figure it out if you know of Euclid's algorithm.
The second is a data class in Kotlin. This is a class whose main purpose is to hold data, in this case to hold a String value for name and a Int value for age.
This is again pretty clear even if you know very little Kotlin. The classes behave as you'd expect them to - you can print them out with a decent standard representation, compare instances for equality, and hash them in a reasonable way.
Now. How about this?
public class User { private final String name; private final Integer age; private User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public String getAge() { return age; } public static Builder builder() { return new Builder(); } private static class Builder { private String name; private Integer age; public Builder name(String name) { this.name = name; return this; } public Builder age(Integer age) { this.age = age; return this; } public User build() { return new User(this.name, this.age); } } @Override public int hashCode() { return Objects.hash(name, age); } @Override public boolean equals(Object o) { if (this == 0) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return Objects.equals(name, user.name) && Objects.equals(age, user.age) } @Override public String toString() { return "User{" + "name='" + name + "'" + ", age=" + age.toString() + "}"; } }
That's 66 lines of Java to create a value object which holds two variables. In functionality this isn't a million miles away from the Kotlin example earlier in this post (the major difference is the inclusion of a Builder, which achieves similar functionality to Kotlin's named arguments).
In readability it's a million miles away from the Kotlin example. For just two instance variables we have this huge load of code that makes our job of understanding the class massively more difficult.
Worse still, in 99% of cases - the code for the getters, builder, hashCode, equals, and toString are completely standard, so much so that many developers use their IDEs to generate them.
The solution I'd like to propose is the use of Project Lombok, an annotation-based code generation tool that has been around since 2009 and supports Java 6-8 (with support for 9 coming soon)
It comes with a bunch of annotations that will generate boilerplate at compile-time - avoiding the need for it to sit around in your codebase.
ToString
@ToString public class User {
This generates a valid ToString method that is equivalent to the one we wrote manually.
Equals and Hashcode
@EqualsAndHashCode public class User {
This generates the equals and hashCode methods. By default this will include all instance variables in the class but arguments can specify variables to include/exclude.
Getters
We can generate getters for each individual field by adding the
@Getter annotation.
@Getter private final String name; @Getter private final Integer age;
Or create a getter for all instance variables by applying the
@Getter annotation to the class directly.
@Getter public class User {
You can of course disable the getter on individual instance variables, by applying the
@Getter(AccessLevel.NONE) annotation.
This leaves us with three annotations on the class,
@Getter,
@EqualsAndHashCode, and
@ToString. We can simplify further by replacing these three with the single annotation
@Value.
@Value public class User {
With this single annotation we're generating valid and consistent equals, hashCode, and toString methods, and a getter for each instance variable.
Builder
Builders are a very common pattern in Java development. Not so useful in this case because there are only two variables but as your data or value objects grow they become invaluable to allow for optional constructor parameters.
However they're very repetitive and suffer from the issues mentioned earlier in this post. Adding an instance variable means the variable also needs to be added to the builder, as does a setter, and it needs to be taken into account when the builder constructs the instance.
Of course, the solution to this is the same as always.
@Builder public class User {
Just add another annotation to the class. Our code is now a lot simpler than it was at the start.
@Builder @Value public class User { private final String name; private final Integer age; }
These two annotations cut 60 lines in this tiny class. Across real codebases with much larger data and value objects it can cut thousands of lines.
These cut lines are now code that doesn't need to be tested, or kept up to date, and it's very unlikely to introduce bugs as it's always generated the same. Most importantly we can now look at the class and see immediately what it does without having to parse huge amounts of boilerplate.
Other Annotations
There are of course other annotations in Lombok. In my opinion the most useful are
@Setter, which generates setters, and
@Data which is the mutable equivalent of
@Value.
NoArgsConstructor,
RequiredArgsConstructor and
AllArgsConstructor come in handy on occasion for the same reasons I've outlined: they avoid you writing, testing, maintaining, and reading needless boilerplate.
@Log can also be useful to remove that copy and pasted line at the top of most Java classes setting up logging.
There are a number of other annotations that I believe are less useful or more experimental. You can see them all on the Lombok website.
How it works
Lombok uses JSR 269, which allows for pluggable annotation processors at compile-time. However, the JSR doesn't allow for modification of classes - only for generating new ones. So Lombok also used some internal APIs to achieve its goals.
This is the bit most people don't like about Lombok. On the surface it can seem quite hacky, and maybe a bit fragile. I'm sure there are a range of opinions on using internal APIs and I'd be happy to discuss it with you.
Lombok runs at compile time - which means the jar that is generated contains no evidence that Lombok was used. The generated methods behave exactly as if they were handwritten, and the Lombok library doesn't need to be included past compile time.
It also doesn't use reflection for the generated methods. The generated code follows the normal patterns that your IDE does, or that you would when writing by hand.
Issues
The first issue to mention is that by default, your IDE won't be able to see the generated methods until you've run the compiler that actually creates them, so it'll give you squiggly red lines when you try to use them.
There are plugins for Eclipse and IntelliJ that allow the IDEs to see the generated methods before running the compiler, but if you use something else you're out of luck.
Even with these plugins, it can still be difficult to refactor - if you want to change the name of an instance variable and the associated getter for example. The best way to deal with this is to manually write a getter - refactor that to the new name - and then remove the new getter allowing Lombok to take over. It's not the end of the world but it's not ideal.
Also, because the methods don't exist in source - this may cause issues for any static analysis you run against your source. This can be solved, through the use of the
delombok tool, which I'll talk about later in this post, but it is something to be aware of.
And finally, because of the use of internal APIs, Jigsaw in Java 9 will just block Lombok from working by default. I last saw an update on the Lombok project a few months ago where they were making good progress with Java 9 compatibility, but of course until it's working completely we can't say for certain.
Delombok
Delombok is a command which will generate the Java code for the builders, getters, setters, etc. directly inside the Java source file.
This can be used to generate the code before you run static analysis, and it's also the security in case Lombok is no longer viable at some point. One command will regenerate all of that code that was deleted.
Alternatives
IDE Generation
The most obvious alternative solution is let your IDE do it. This is what most of us are doing already. Most IDEs have getters and setters, hashCode, equals, and toString built in - and you can get plugins to generate builders.
However, as I've mentioned previously, it makes the code harder to figure out due to all the boilerplate, and it's easy to forget to re-generate something after a change.
AutoValue/Immutables
AutoValue and Immutables are two very similar projects, specifically for reducing the boilerplate around value objects.
They both use JSR 269 without the use of internal APIs, which means we can be a bit more confident that they won't stop working with a future version of the JDK. But I personally found the code that you need to write to use these projects a lot less pleasing than that which you write when using Lombok.
You create abstract classes or interfaces that define the getters, then the library generates a class implementing that interface, complete with builders etc. However you then end up with these weird class names like AutoValue_Animal, which I wouldn't say I like less than getters, but I'm not a huge fan of.
There are other solutions such as moving to another language, or just learning to love the boilerplate. But within the projects I work on we've adopted Lombok and are very happy with the subsequent improvement in the readability of our code. I'm interested in hearing other people's experiences using Lombok or other techniques to deal with Java boilerplate.
This post was originally delivered as an internal technical talk on 19/10/2017. | https://blog.jscott.me/lombok-towards-beautiful-java-code/ | CC-MAIN-2018-43 | refinedweb | 1,751 | 60.35 |
Richard Guy’s Strong Law of Small Numbers says
There aren’t enough small numbers to meet the many demands made of them.
In his article by the same name [1] Guy illustrates his law with several examples of patterns that hold for small numbers but eventually fail. One of these examples is
3! – 2! + 1! = 5
4! – 3! + 2! – 1! = 19
5! – 4! + 3! – 2! + 1! = 101
6! – 5! + 4! – 3! + 2! – 1! = 619
7! – 6! + 5! – 4! + 3! – 2! + 1! = 4421
8! – 7! + 6! – 5! + 4! – 3! + 2! – 1! = 35899
If we let f(n) be the alternating factorial sum starting with n, f(n) is prime for n = 3, 4, 5, 6, 7, 8, but not for n = 9. So the alternating sums aren’t all prime. Is f(n) usually prime? f(10) is, so maybe 9 is the odd one. Let’s write a code to find out.
from sympy import factorial, isprime def altfact(n): sign = 1 sum = 0 while n > 0: sum += sign*factorial(n) sign *= -1 n -= 1 return sum numprimes = 0 for i in range(3, 1000): if isprime( altfact(i) ): print(i) numprimes += 1 print(numprimes)
You could speed up this code by noticing that
altfact(n+1) = factorial(n+1) - altfact(n)
and tabulating the values of
altfact. The code above corresponds directly to the math, though it takes a little while to run.
So it turns out the alternating factorial sum is only prime for 15 values less than 1000. In addition to the values of n mentioned above, the other values are 15, 19, 41, 59, 61, 105, 160, and 601.
* * *
[1] The Strong Law of Small Numbers, Richard K. Guy, The American Mathematical Monthly, Vol. 95, No. 8 (Oct., 1988), pp. 697-712.
For daily tips on Python and scientific computing, follow @SciPyTip on Twitter.
3 thoughts on “Alternating sums of factorials”
A different question one could ask and is interesting is whether there are infinitely many alternating factorials which are prime.
Again I wanted to try this in Perl 6.
I noticed that each factorial was only used once, so I figured I would use the iterator API so that it would use a minimal amount of RAM.
my \factorial = ( 1, { ++$ * $_ } … * ).iterator;
my \alt-factorial = ( { factorial.pull-one – ($_//1)} … * ).iterator;
my @alt-primes = (^1000).grep: { alt-factorial.pull-one.is-prime }
say @alt-primes; # (3 4 5 6 7 8 10 15 19 41 59 61 105 160 661)
say +@alt-primes, ‘ primes’; # 15 primes
say now – INIT { now }, ” seconds”; # 127.4444326 seconds
Wondering the same question as Kosta, it occurred to me that if any f(n) has a factor <= n+1, the all f(n+k) would also have that as a factor. So the number of prime f(n) would be finite. Some C++ code and an hour of computation revealed n==3612702 as meeting that criteria.
Only then did I check Wikipedia () and see this fact as part of the article.
BTW, you list n=601 as a prime f(n), but others give n=661 instead. | https://www.johndcook.com/blog/2015/12/12/alternating-sums-of-factorials/ | CC-MAIN-2017-43 | refinedweb | 518 | 70.53 |
health 0.9.9
health #
This library combines both GoogleFit and AppleHealthKit. It support most of the values provided.
Supports iOS and Android X
Data Types #
Setup #
Apple HealthKit #
Step 1: Append the Info.plist with the following 2 entries
<key>NSHealthShareUsageDescription</key> <string>We will sync your data with the Apple Health app to give you better insights</string> <key>NSHealthUpdateUsageDescription</key> <string>We will sync your data with the Apple Health app to give you better insights</string>
Step 2: Enable "HealthKit" inside "Capabilities"
Google Fit #
For GoogleFit, the initial setup is a bit longer, and can get frustrating. Just follow this setup.
0.0.1 #
- TODO: Describe initial release.
health_example #
Demonstrates how to use the health: health: ^0.9.9
2. Install it
You can install packages from the command line:
with Flutter:
$ flutter pub get
Alternatively, your editor might support
flutter pub get.
Check the docs for your editor to learn more.
3. Import it
Now in your Dart code, you can use:
import 'package:health/health/health.dart.
Run
flutter format to format
lib/health.dart.
Maintenance issues and suggestions
Homepage URL doesn't exist. (-20 points)
At the time of the analysis the
homepage field was unreachable. | https://pub.dev/packages/health | CC-MAIN-2019-47 | refinedweb | 203 | 57.37 |
Results 1 to 3 of 3
- Join Date
- Aug 2009
- 9
- Thanks
- 0
- Thanked 0 Times in 0 Posts
C noob requires assistance. Remember my username this will happen often!!
Hi Guys,
I'm attempting to learn how to program in my freetime, part time between work. This is a problem for me. I don't have the fundamentals of any sort of programming, but have been requently advised that C is the base for all.
So, I'm trying to compile by second program based off a book called 'C Programming in Easy Steps' and getting a bit lost.
I've produced this code based of the book, and compiled it with the following result:
#include <stdioh>
int main()
{
int num=100;
double pi=3.1415926536;
printf ( "Integer is %d \n", num );
return 0;
}
vars.c:9:2: warning: no newline at end of file
What exactly does this mean? Thanks for your help in advance.
Jess.
- Join Date
- Jun 2002
- Location
- USA
- 9,073
- Thanks
- 1
- Thanked 328 Times in 324 Posts
It means there isn't an extra line after the closing curly brace. Just press enter after the curly brace to add an extra blank line. It isn't really necessary but I usually put it in anyways.OracleGuy
- Join Date
- Aug 2009
- 9
- Thanks
- 0
- Thanked 0 Times in 0 Posts
Thanks for your help again oracleguy.
J. | http://www.codingforums.com/computer-programming/175865-c-noob-requires-assistance-remember-my-username-will-happen-often.html | CC-MAIN-2017-09 | refinedweb | 233 | 81.02 |
Updated vue paginate
Install
Repository:
CDNs
bundle.run:
jsDelivr:
unpkg:
This is an updated version of vue-paginate. Original README below.
...
vue-paginate
This version only works with Vue 2.0. For Vue 1.0, check out the 1.0 branch.
The idea of
vue-paginate is pretty simple. You give it an array of items; specify how many items per page; then get your list of items paginated!
Setup
npm install vue-paginate --save
You have two ways to setup
vue-paginate:
CommonJS (Webpack/Browserify)
- ES6
import VuePaginate from 'vue-paginate' Vue.use(VuePaginate)
- ES5
var VuePaginate = require('vue-paginate') Vue.use(VuePaginate)
Include
Include it directly with a
<script> tag. In this case, you don't need to write
Vue.use(VuePaginate), this will be done automatically for you.
Usage
Before you start, you may want to check a live example on jsfiddle.
vue-paginate consists of two main components:
Paginate and
PaginateLinks. And both get registered globally once the plugin is installed.
To paginate any list of data, we have to follow these three small steps:
- Register the name of the paginated list.
- Use
Paginatecomponent to paginate and display the paginated list.
- Use
PaginateLinkscomponent to display the links for the pagination.
Now, let’s see them in an example:
Example
In this example, we have a small list of items registered in our data list.
new Vue({ el: '#app', data: { langs: ['JavaScript', 'PHP', 'HTML', 'CSS', 'Ruby', 'Python', 'Erlang'] } })
Now, let’s see how we can paginate this list to display two items per page.
First step is to register the name of our future paginated list. We register it by adding it to an array called
paginate.
new Vue({ el: '#app', data: { langs: ['JavaScript', 'PHP', 'HTML', 'CSS', 'Ruby', 'Python', 'Erlang'], paginate: ['languages'] } })
Note that you can name it the same as the original list – I named it differently here just for the sake of clarity.
Second step is to use the
Paginate component to paginate the list. Since it was globally registered by the plugin, you don’t have to import it.
This component requires at least two props to be passed. The
name of the registered paginated list –
languages in this case. And the
list that you want to paginate –
langs in this case.
After that, you start using the paginated list inside the body of that
<paginate> component. And, you get access to the paginated list using the method
paginated('languages').
Here’s how it looks in action:
<paginate name="languages" : <li v- {{ lang }} </li> </paginate>
Note how we specified the number of items per page using the
per prop. If we didn’t specify it here, it would use the default value instead, which is
3 items per page.
That’s it! Now your list has been paginated successfully. And you still have access to the original
langs list if you need it.
However, we still don’t have a way to navigate through those pages. Here’s where
PaginateLinks component comes into play.
All that component needs to know is the name of the registered paginated list. We pass that using its
for prop. Like this:
<paginate-links</paginate-links>
So, that was the third step!
Rendering PaginateLinks asynchronously
A common error users get when using this plugin is this:
[vue-paginate]:
can't be used without its companion
This error occurs for two reasons:
- You haven't added your
<paginate>yet! — Just add it and it will be fixed.
- Or your defined
<paginate>component is rendered after its companion
<paginate-links>has been rendered (usually happens when using
v-ifon
<paginate>or on one of its parents)
Here's some contrived example of the second case:
<paginate v- <li v- {{ item }} </li> </paginate> <paginate-links</paginate-links>
new Vue({ el: '#app', data: { langs: ['JavaScript', 'PHP', 'HTML', 'CSS', 'Ruby', 'Python', 'Erlang'], paginate: ['languages'], shown: false }, mounted () { setTimeout(() => { this.shown = true }, 1000) } })
If you try this example in the browser, you'll see the error described in this section. And the reason for that is because our
PaginateLinks component can't find its companion
Paginate component to show the links for — since it takes a complete second to render itself.
To fix this issue we have to tell our
PaginateLinks to wait for its companion
Paginate component to be rendered first. And we can do that simply by using
:async="true" on
<paginate-links>.
<paginate-links</paginate-links>
So the bottom line is this:
<paginate> component should always be rendered before
<paginate-links> component.
Using it inside a component's slot
Paginate and
PaginateLinks components get their current state from the parent component they're used in. You can find that state defined inside an object called
paginate. For example, if your pagination is named
languages, its state will be defined inside
paginate.languages.
But what if those components are used inside a slot? In this case, its parent component will be the slot's component (not the component it's defined in).
In this case we have to tell our pagination components where they can find the component that contains their state. We can do so using the
container prop.
Although both components,
Paginate and
PaginateLinks, use the same prop name, they take different values.
Paginate component just needs the reference to the parent component that has its state. That value is usually
this.
PaginateLinks, however, takes an object with two values:
state and
el.
state takes the current state object of the pagination. This value can be, for example,
paginate.languages.
For
el we should pass a reference to the component that contains
Paginate component. In most cases it will be the component with the slot. For example:
$refs.layout.
Example
Note: this example is based on the previous example.
<div id="app"> <layout ref="layout"> <paginate name="languages" : <li v- {{ lang }} </li> </paginate> <paginate-links </layout> </div>
Types of paginate links
vue-paginate provides us with three different types of pagination links:
- Full list of links. This is the default behavior, which displays all available page links from page 1 to N.
- Simple links. It contains only two links: Previous and Next.
- Limited links. It limits the number of displayed links, and provides left and right arrows to help you navigate between them.
Full links
To use this you don’t have to do anything; this is the default behavior.
Simple links
For this, we use the
simple prop, which accepts an object that contains the names of the Previous and Next links. For example:
<paginate-links</paginate-links>
Limited links
To activate this mode, you just need to specify the limit using the
limit prop. Like this:
<paginate-links</paginate-links>
Step Links
As in simple links, you can have next/previous links — which I call step links — in full links and limited links. To add them, use
:show-step-links="true" prop on the
PaginateLinks component you want. For example:
<paginate-links</paginate-links>
Customizing step links
The default symbols for the step links are
« for previous and
» for next. But, of course, you can change them to what you want using the
:step-links prop, like this:
<paginate-links</paginate-links>
Listening to links @change event
When the current page changes,
PaginateLinks emits an event called
change to inform you about that. It also passes the switched page numbers with it, if you need them.
<paginate-links</paginate-links>
methods: { onLangsPageChange (toPage, fromPage) { // handle here… } }
Navigate pages programmatically
Paginate component exposes a method that allows you to go to a specific page manually (not through
PaginateLinks component). That method is called
goToPage(pageNumber).
To access this method, you need to get an access to your
<paginate> component instance using
ref property.
Here's an example:
<paginate ref="paginator" name="items" : <li v- {{ item }} </li> </paginate> <button @Go to second page</button>
methods: { goToSecondPage () { if (this.$refs.paginator) { this.$refs.paginator.goToPage(2) } } }
Displaying page items count (
X-Y of Z)
A common need for paginated lists is to display the items count description of the currently viewed items. It's usually displayed in this format
X-Y of Z (e.g.
1-3 of 14).
You can get that from your
<paginate> component instance's
pageItemsCount computed property. And in order to use that, you have to get an access to that component instance using
ref property.
An example:
<paginate ref="paginator" name="items" : <li v- {{ item }} </li> </paginate> <paginate-links</paginate-links> <span v- Viewing {{$refs.paginator.pageItemsCount}} results </span>
An important thing to note here is
v-if="$refs.paginator". We needed to do that check to make sure our
<paginate> component instance is completely rendered first. Otherwise, we'll get this error:
Cannot read property 'pageItemsCount' of undefined"
Paginate container
The default element
vue-paginate uses for the
<paginate> container is
UL. But, of course, you can change it to whatever you want using the
tag prop. And the same is true for its class using the
class prop.
<paginate name="languages" : <li v- {{ lang }} </li> </paginate>
Updating the full list
Since this plugin is built using the components system, you get all the flexibility and power that regular Vue components provide. I’m talking here specifically about the reactivity system.
So, when you want to update the original list (e.g.
langs), just update it; everything will work seamlessly!
Filtering the paginated list
There’s nothing special the plugin does to support list filtering. It’s your responsibility to filter the list you pass to
<paginate> component via
list prop.
So, if we were to filter the list (or any other operation), we would have something similar to this:
// Assume we have a text input bound to `searchLangs` data via v-model for example. computed: { fLangs () { const re = new RegExp(this.searchLangs, 'i') return this.langs.filter(lang => lang.match(re)) } }
Then just pass that
fLangs to the
list prop instead of the original
langs.
Hide single page
By default, paginated links will always be displayed even if there's only one page. But sometimes you want to hide it when there's a single page — especially after filtering the items. The plugin allows you to do so by using the
:hide-single-page="true" prop.
<paginate-links</paginate-links>
Links customization
In
vue-paginate, you can customize every bit of your pagination links.
But first, let’s see the html structure used for all link types:
<ul> <li><a>1</a></li> <li><a>2</a></li> <!-- … --> </ul>
Now, let’s see what CSS selectors we often need to use:
All links containers:
ul.paginate-links
Specific links container:
ul.paginate-links.languages
languages here is the name of your paginated list.
Current page:
This only works for full & limited links.
ul.paginate-links > li.active > a
Previous & Next Links:
Obviously, this is only for simple links.
ul.paginate-links > li.prev > a
ul.paginate-links > li.next > a
Disabled Next/Previous Links:
ul.paginate-links > li.disabled > a
Limited Links:
Number links –>
ul.paginate-links > li.number > a
Left arrow –>
ul.paginate-links > li.left-arrow > a
Right arrow –>
ul.paginate-links > li.right-arrow > a
Ellipses –>
ul.paginate-links > li.ellipses > a
Adding additional classes
In some cases, especially when you're using a CSS framework, you'll need to add additional classes to your links elements. You can do so simply by using the
classes prop on your
PaginateLinks component. This prop takes an object that contains the element's selector as the key, and the class you want to add as the value.
Here's an example:
<paginate-links</paginate-links>
Note that this feature works on all link types – full links, simple links, and limited links.
License | http://tahuuchi.info/updated-vue-paginate | CC-MAIN-2021-25 | refinedweb | 1,949 | 56.86 |
21 February 2015 9 comments Python
First of all; hashing is hard. But fortunately it gets a little bit easier if it doesn't have to cryptographic. A non-cryptographic hashing function is basically something that takes a string and converts it to another string in a predictable fashion and it tries to do it with as few clashes as possible and as fast as possible.
MD5 is a non-cryptographic hashing function. Unlike things like sha256 or sha512 the MD5 one is a lot more predictable.
Now, how do you make a hashing function that yields a string that is as short as possible? The simple answer is to make the output use as many different characters as possible. If a hashing function only returns integers you only have 10 permutations per character. If you instead use
a-z and
A-Z and
0-9 you now have 26 + 26 + 10 permutations per character.
A hex on the other hand only uses
0-9 and
a-f
which is only 10 + 6 permutations. So you need a longer string to be sure it's unique and can't clash with another hash output. Git for example uses a 40 character log hex string to prepresent a git commit. GitHub is using an appreviated version of that in some of the web UI of only 7 characters which they get away with because things are often in a context of a repo name or something like that. For example github.com/peterbe/django-peterbecom/commit/462ae0c
So, what other choices do you have when it comes to returning a hash output that is sufficiently long that it's "almost guaranteed" to be unique but sufficiently short that it becomes practical in terms of storage space? I have an app for example that turns URLs into unique IDs because they're shorter that way and more space efficient to store as values in a big database. One such solution is to use a base64 encoding.
Base64 uses
a-zA-Z0-9
but you'll notice it doesn't have the "hashing" nature in that it's just a direct translation character by character. E.g.
>>> base64.encodestring('peterbengtsson') 'cGV0ZXJiZW5ndHNzb24=\n' >>> base64.encodestring('peterbengtsson2') 'cGV0ZXJiZW5ndHNzb24y\n'
I.e. these two strings are different but suppose you were to take only the first 10 characters these would be the same. Basically, here's a terrible hashing function:
def hasher(s): # this is not a good hashing function return base64.encodestring(s)[:10]
So, what we want is a hashing function that returns output that is short and very rarely clashing and does this as fast as possible.
To test this I wrote a script that tried a bunch of different ad-hoc hashing functions. I generate a list of 130,000+ different words with an average length of 15 characters. Then I loop over these words until a hashed output is repeated for a second time. And for each, I take the time it takes to generate the 130,000+ hashes and I multiply that with the total number of bytes. For example, if the hash output is 9 characters each in length that's
(130000 * 9) / 1024 ~= 1142Kb. And if it took 0.25 seconds to generate all of those the combined score is
1142 * 0.24 ~= 286 bytes second.
Anyway, here are the results:
h11 100.00 0.217s 1184.4 Kb 257.52 kbs h6 100.00 1.015s 789.6 Kb 801.52 kbs h10 100.00 1.096s 789.6 Kb 865.75 kbs h1 100.00 0.215s 4211.2 Kb 903.46 kbs h4 100.00 1.017s 921.2 Kb 936.59 kbs
(
kbs means "kilobytes seconds")
These are the functions that returned 0 clashes amongst 134,758 unique words. There were others too that I'm not bothering to include because they had clashes. So let's look at these functions:
def h11(w): return hashlib.md5(w).hexdigest()[:9] def h6(w): h = hashlib.md5(w) return h.digest().encode('base64')[:6] def h10(w): h = hashlib.sha256(w) return h.digest().encode('base64')[:6] def h1(w): return hashlib.md5(w).hexdigest() def h4(w): h = hashlib.md5(w) return h.digest().encode('base64')[:7]
It's kinda arbitrary to say the "best" one is the one that takes the shortest time multipled by size. Perhaps the size matters more to you in that case the
h6() function is better because it returns 6 character strings instead of 9 character strings in
h11.
I'm apprehensive about publishing this blog post because I bet I'm doing this entirely wrong. Perhaps there are better ways to digest a hashing function that returns strings that don't need to be base64 encoded. I just haven't found any in the standard library yet.
Follow @peterbe on Twitter
0-9 are 10 possibilities, not 9 ;-)
Right you are!
Hi! This page is currently the 6th Google result for [python fast hash]! Unfortunately, the analysis here is somewhat confused, which could lead beginners astray.
MD5 would be better described as a flawed cryptographic hash function, rather than a "non-cryptographic hash function". (MD5 tried to be cryptographically strong, and was used in that fashion for quite a while, but turned out to be broken. A truly designed-to-be non-cryptographic hash function would be simpler and faster; more on that later.)
To meaningfully compare algorithms, you should do so based on their raw output (bits/bytes), not multiple varying printable representations (hex/base64, possibly truncated). Those encoding/truncation decisions are logically separate, and can be done at the end, to any suitable algorithm.
Against a random set of inputs like your "130,000+" words, taking the same number of leading bits from either MD5 or SHA256 will be equally likely to be free of collisions. (The known flaws in MD5 only come into play if inputs are chosen adversarially to engineer collisions.)
MD5 will be faster for the same amount of input, since it is a simpler algorithm with smaller state and output. (Your timing scores based on output-characters, as modified by a further encoding/truncation choice, are a bit fishy. It's isn't typical to rate a hash's speed by output characters, and your times may be dominated by other choices in your loop.)
Given your test – 130,000 (around 2^17) random words – there's a "birthday problem" probability calculation that predicts exactly how many unique, randomly-distributed output values any hash function would need to offer to make even one collision among those 2^17 probes unlikely: around 2^34. So it's no surprise that each of your shortest surviving hashes encodes 36 bits, with just the right number of characters to go over 34 bits. (Hex characters, with 16 values, encode 4 bits. So 8 characters (8*4=32 bits) would be too few bits, while 9 characters (8*4=36) is just enough. Similarly base32 characters encode 6 bits, so 5 characters (5*6=30 bits) would be too few, while 6 characters (6*6=36 bits) is just enough.)
So what technique should be used to create the sort of usually-unique, stable, short IDs you want?
If you need to stick with the Python standard library, starting with MD5 is a defensible choice. Then if compactness in text representation matters, represent the hashes in base64. Then if you want to accept more collision-risk than is likely with the full 128 bits, use the birthday-problem calculations to pick a number of retained bits that fit your size/collision tradeoffs, and truncate away the rest.
But remember MD5 is slower than hash functions that never intended to have cryptographic collision-resistance as a goal. So if speed is a goal, you could look outside the standard library. If you'd like to use the fast non-cryptographic hash functions that Google has published, look into their projects "CityHash" or "FarmHash". (These even have 256-bit options, on the off chance that the collision-risk with 128-bits is still too high for your application.) The first 36 (or 64 or 80 or 128) bits from these should be just as good as the bits from MD5, for your purposes. Then, apply the same encoding and truncation choices as may be appropriate.
Thanks for that insightful comment. Really appreciate it!
In my Autocompeter.com service (written in Go) I actually went for version h6(). I needed it to be as small as possible and that one produces, very quickly, a hash that is only 6 characters long and seems very safe for clashes.
Hi. Your article was useful to me, but you missed a teachable moment by omitting the 'bad' hashes. See :)
Python has a built-in hash() function that's faster than all of these.
The build-in hash function will not always return the same results across different invocations of your program. Check out the note at the bottom of the hash documentation about PYTHONHASHSEED:
Yeah, I was testing in an pre 3.3. fnv is ok i guess.
Unfortunately, for many uses, the use of Python's hash function is terribly flawed. Ex.: `hash(-1) == hash(-2)` =( | https://www.peterbe.com/plog/best-hashing-function-in-python | CC-MAIN-2021-10 | refinedweb | 1,546 | 65.01 |
trying to save an image with its name intact php
trying to save an image with its name intact php - You can use basename() to determine the last part (= filename) of a path. $ image_name See the docs over at .php.
Stop saving image as images/name.jpg of image - PHP - Hi i have the upload script but it keeps uploading the image name with i have tried to take off the image but then it doesnt upload the file int the images folder how because we have to keep the image ratio intact or it will be deformed define
rename - Manual - Attempting to call rename() with such a destination filesystem will cause an " Operation .. to change evry file name with extention html into php in the directory dir . And as noted, your 'old' directory will remain on the server totally intact, which can be very confusing. .. I was using rename() 'batch-move' a bunch of images.
php - Saving an image in MYSQL vs saving to a folder - I would keep them out of the database, store them in the OS's file system and just store a relative path in a database table. This will allow you to
How to Export Basic HTML, Part 2: Images - InDesign CS2 or CS3, basic formatting intact, using a little XML Tags trickery. If in doubt, try both methods and show them to your web team; see Instead, all we've got is this, the Image section of the Export XML dialog box: . This is the folder name that InDesign CS2 automatically creates on export
Why Are Pictures not Showing in Email? - Plain Text email is, as the name implies, plain text and nothing more. . If not, and if the email you're looking at is trying to fetch images remotely, that could easily be the cause.- eBay saved search notices WITH PHOTOS intact…. so the problem
The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP - Image formats! They also saved an extra 13.8% using MozJPEG .. -type f - name '*.jpg' -exec jpeg-recompress {} {} \;. and trim those On Mac, try the Quick Look plugin for WebP (qlImageSize). To override this behavior and deliver a transformed image with its metadata intact, add the keep_iptc flag.
Automating image optimization | Web Fundamentals - The alpha channel data is left intact just deactivated. .. As an example, to add contrast to an image with offsets, try this command: .. The value can be the name of a PNG chunk-type such as bKGD , a comma-separated list . It will preserve the opacity mask of a layer and add it back to the layer when the image is saved.
replace name in php
Replace all occurrences of the search string with the - If search and replace are arrays, then str_replace() takes a value from each array .. We want to replace the name "ERICA" with "JON" and the word "AMERICA"
PHP - The str_replace() is a built-in function in PHP and is used to replace all the the search string or array of search strings by replacement string or array of replacement How to get the function name from within that function using JavaScript ?
PHP - The rename() function in PHP is an inbuilt function which is used to rename a file or directory. It makes an attempt to change an old name of a file or directory
PHP script that will find a replace %{variable_name}% - So that [NAME] in for instance a mass email is replaced by the contents of $ Reference:.
PHP substr_replace() Function - substr_replace(string,replacement,start,length) A positive number - Start replacing at the specified position in the string; Negative number - Start replacing at
8 examples of PHP str_replace function to replace strings - The str_replace function of PHP is used to replace a string with the replacement string. .. <label>To be Replaced with: </label><select name="replacestr">.
MySQL REPLACE() function - MySQL REPLACE() replaces all the occurrances of a substring within a <meta name="description" content="example-replace-function - php
Replacing a built-in PHP function when testing a component – Rob - Replacing a built-in PHP function when testing a component. Recently I first before finding one with the same name in the global namespace.
Database Search and Replace Script in PHP - Search Replace DB is a powerful tool for developers, allowing them to run a search received by email, and install it to a secret folder with an obfuscated name.
PHP: Replace an array key. - This is a tutorial on how to replace an array key in PHP. Now, let's say that you want to replace the key user_name with a new key called name. Firstly, you will
how to move images in php
move_uploaded_file - Manual - 2. convert image to standard formate (in this case jpg) and scale .. move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/ somefilename' to
PHP - Move a file into a different folder on the server - If you want to move the file in new path with keep original file name. use this: $ source_file = 'foo/image.jpg'; $destination_path = 'bar/';
php and moving images to new folders - You will need to be sure that your web server has write access to the uploads directory where you want them to reside. Then you can just do:
Uploading Files with PHP - Here we'll cover the basic upload process using PHP limiting by filetype article move on to additional things like image resizing and cropping.
Php: How To Display Only Images From A Directory Using Php [ with - Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java
51: Upload Files and Images to Website in PHP - to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. To center an image, set left and right margin to auto and make it into a block
HTML Images - <title>Placing Text Over an Image in CSS</title> top: 40%; /* Adjust this value to move the positioned div up and down */; text-align: center;; width: 60%; /* Set
How To Center an Image - How To Show Image From A Folder Using Php Source Code:. blogspot.com
Randomly Display Some Images From A Set of Images: PHP - Upload Files and Images to Website in PHP | PHP Tutorial | Learn PHP Programming
How to Position Text Over an Image Using CSS -- php/ Using
how to move image file in php
PHP - Move a file into a different folder on the server - If you want to move the file in new path with keep original file name. use this: $ source_file = 'foo/image.jpg'; $destination_path = 'bar/';
Moves an uploaded file to a new location - further validation/sanitation of the filename may be appropriate $name = basename($_FILES["pictures"]["name"][$key]); move_uploaded_file($tmp_name
Move a file with PHP. - This is a tutorial on how to move files using PHP. To do this, we will be using PHP's rename function, which essentially renames a given file or directory. For this
Move file to other directory - PHP - OK, I am trying to move an image file from one directory to another. I am using the code below $rename1 = "SpecialPictures/Advertisers/CampBC.png";
Move image to another folder and write path to database - when i upload a file to my folder called images a script is run called thumb save and creates a thumbnail of that original file but places it in the
Php : How To Move Uploaded File To Another Directory [ with - if (rename($dir.'/'.$file,$dirNew.'/'.$file)). {. echo " Files Copyed Successfully";. echo ": $dirNew/$file";. //if files you are moving are images you can print it from.
PHP move all files and folders from one directory to a new directory - PHP move_uploaded_file() Function. ❮ Complete PHP Filesystem Reference. Definition and Usage. The move_uploaded_file() function moves an uploaded file
PHP move_uploaded_file() Function - You should check for file upload errors before trying to move the file. See PHP: Error Messages Explained - Manual[^].
[Solved] Image unable to move to temporary files using - I was looking for a quick code example on recursively moving files with PHP and I only saw code snippets using PHP 5. I like using the new and
PHP 5: Recursively move or copy files - Php How To Move Uploaded File To Another Folder Source Code: .blogspot. com/2015/10
copy image from one folder to another in php
How to copy an image from one folder to another using php - You should write your code same as below : <?php $imagePath = "/var/www/ projectName/Images/somepic.jpg"; $newPath = "/test/Uploads/";
Copy image file from one folder to another - PHP - What is a simple method to copy an image in one folder on a sever to another folder on the same server. also how to delete a image file on a
how to copy a file from one folder to another with php? - how to copy a file from one folder to another with php? $file = '/usr/home/guest/example.txt'; $newfile = '/usr/home/guest/example.txt.bak'; if (! copy($file, $newfile)) { echo "failed to copy $file\n"; }else{ echo "copied $file into $newfile\n";
copy - Manual - If you try to copy a file to itself - e.g. if the target directory is just a symlink to the Copying large files under Windows 8.1, from one NTFS filesystem to another NTFS . if ( preg_match('@^image/(\w+)@ims', $arrHeader[2], $arrTokens) > 0 ) {
php - To copy an image from one folder to another, you'll have to read from the image file that you would like to copy, then create another file
PHP copy() Function - PHP copy() Function. ❮ Complete PHP Filesystem Reference. Definition and Usage. The copy() function copies a file. This function returns TRUE on success
Copying images from one directory to another - I want to go into a number of directories, get all the .jpgs, and copy them to another set of corresponding directories This is my pathetic attempt
How to Copy files from one folder to another folder using PHP - To copy files from source folder to destination php provide a copy function. This function takes two argument first is source path (source dir) and
PHP - The copy() function in PHP is an inbuilt function which is used to make a copy of a specified file. $dest: It is used to specify the path to the destination file.
how to copy a file from one folder to another with php? - You asked how to copy -- so either digitok's or ub3r's method would work. digitok's method uses an inbuilt function in PHP, while ub3r's method | http://www.brokencontrollers.com/article/10152202.shtml | CC-MAIN-2019-39 | refinedweb | 1,754 | 59.23 |
This weekend the most expected version of HMC was released for service providers to deploy it. With this version, service providers can offer OCS (IM, Collaboration, PC-toPC VoIP) services as part of their online services. At the same time support to Windows 2008 and WSS 3.0 SP1 is included in this solution.
You can have access to the bits of the solution from the following location:
Or for those who are interested in developing on top of MPS (i.e. self-service portal, namespaces, increase the business logic of the current APIs, etc.) there is a SDK available as well for developers to consume:
The documentation to migrate from previous versions is still pending, but it will be released soon. If you have HMC 4.0, you shouldn't expect too much of impact in your APIs or portals already implemented. If what you have is HMC 3.5 or earlier, you should consider a similar migration path like to HMC 4.0 with the addition of migrating LCS to OCS 2007. Don't forget to consider these migrations paths while deploying the solution. | http://blogs.technet.com/b/alexmga/archive/2008/06/16/hmc-4-5-is-available-now-deploy-deploy-deploy.aspx | CC-MAIN-2014-15 | refinedweb | 186 | 66.13 |
annoy4sannoy4s
A JNA wrapper around spotify/annoy which calls the C++ library of annoy directly from Scala/JVM.
InstallationInstallation
For linux-x86-64 or Mac users, just add the library directly as:
libraryDependencies += "net.pishen" %% "annoy4s" % "0.8.0"
If you meet an error like below when using annoy4s, you may have to compile the native library by yourself.
java.lang.UnsatisfiedLinkError: Unable to load library 'annoy': Native library
To compile the native library and install annoy4s on local machine:
- Clone this repository.
- Check the values of
organizationand
versionin
build.sbt, you may change it to the value you want, it's recommended to let
versionhave the
-SNAPSHOTsuffix.
- Run
compileNativein sbt (Note that g++ installation is required).
- Run
testin sbt to see if the native library is successfully compiled.
- Run
publishLocalin sbt to install annoy4s on your machine.
Now you can add the library dependency as (organization and version may be different according to your settings):
libraryDependencies += "net.pishen" %% "annoy4s" % "0.8.0-SNAPSHOT"
The library file generated by the g++ command in
compileNative can also be installed independently on your machine. Please reference to library search paths for more details on how to make JNA able to load the library.
UsageUsage
Create and query the index in memory mode:
import annoy4s._ val annoy = Annoy.create[Int]("./input_vectors", numOfTrees = 10, metric = Euclidean, verbose = true) val result: Option[Seq[(Int, Float)]] = annoy.query(itemId, maxReturnSize = 30)
- The format of
./input_vectorsis
<item id> <vector>for each line, here is an example:
3 0.2 -1.5 0.3 5 0.4 0.01 -0.5 0 1.1 0.9 -0.1 2 1.2 0.8 0.2
<item id>could be
Int,
Long,
String, or
UUID, just change the type parameter at
Annoy.create[T]. You can also implement a
KeyConverter[T]by yourself to support your own type.
metriccould be
Euclidean,
Angular,
Manhattanor
Hamming.
resultis a tuple list of id and distances, where the query item is itself contained.
To use the index in disk mode, one need to provide an
outputDir:
val annoy = Annoy.create[Int]("./input_vectors", 10, outputDir = "./annoy_result/", Euclidean) val result: Option[Seq[(Int, Float)]] = annoy.query(itemId, maxReturnSize = 30) annoy.close() // load an created index val reloadedAnnoy = Annoy.load[Int]("./annoy_result/") val reloadedResult: Option[Seq[(Int, Float)]] = reloadedAnnoy.query(itemId, 30) | https://index.scala-lang.org/annoy4s/annoy4s/annoy4s/0.6.0?target=_2.11 | CC-MAIN-2019-43 | refinedweb | 387 | 52.56 |
'gvar'table
Apple Advanced Typography style variations allow the font designer to build high quality styles into the typeface itself. This reduces the dependence on algorithmic styling in the graphics system. To include font variations in your font, you must also include the font variations table.
The glyph variations table (tag name:
'gvar')
allows you to include all of the data required for stylizing the glyphs
in your font.
Conceptually, variation fonts define axes over which font characteristics can vary. Thus, in the figure below, we see the Q glyph from Skia drawn at various points along the
'wght' axis. Since the minimum and maximum values have been defined as +0.7 and +1.3, respectively, the specification of a style coordinate of 1.0 refers to the style of the center 'Q.'
Multiple axes can be combined within a single font..
Data for how these axes are presented to the user is contained in the font variations table. The glyph variations table contains data which is used to determine the outline for a glyph given a combination of settings for the various axes.
This is done by using tuples. The terminology is derived from mathematics, where an n-tuple is defined as an ordered list of
n numbers. For a variation font, a tuple is an ordered list of deltas which are applied to a font at one point within the possible coordinate space defined by the axes. These deltas are added to the coordinates of the points found in the
'glyf' table to determine the actual coordinates of the points on the outline for the glyph as it is to be rendered. Hinting can then be applied to this modified outline. The hints themselves can vary for the glyph; this is controlled by the
'cvar' table.
So that a glyph can vary in its dimensions as well as its shape, tuples have entries for each point in the glyph plus entries for four "phantom points," which represent the glyph's side-bearings. These phantom points are, in order, the left-side phantom point, the right-side phantom point, the top phantom point, and the bottom phantom point.
'gvar'table
The glyph variations table consists of a glyph variations table header, glyph offset array, glyph style coordinate array, and glyph variations array. The overall structure of the glyph variations table is shown in the following figure:
The glyph variations table header format is shown in this table:
The shared coordinates of the
globalCoordCount are referenced
by the glyph tuples rather than storing the coordinates in each glyph tuple.
The number of bytes occupied by the global coordinates can be found
using the expression
offsetToData - offsetToCoord. This size
should be equal to
globalCoordCount * axisCount * sizeof(shortFrac).
That is, there are
globalCoord
shortFrac&s for
each axis in the font.
If the flag bitfield is set to 1, the offsets are type uint32. If the flag bit-field is set to 0, the offsets are type uint16.
The offset array follows the glyph variation header. The offset array
gives the offset from the beginning of the glyph variation array. This data
specifies where each glyph variation begins. The variation data is the same
order as the glyph order. This allows the length of a particular glyph variation
to be computed by subtracting the offset of the next variation from the
current one. This means that there must be
glyphCount + 1 entries
in the offset array.
The glyph variation array follows the glyph variation offset array. Each glyph variation array is padded to ensure that it start at an even bytes. Each glyph variation begins with a glyph variation array header. The format of the glyph variation array header is as follows:
The
tupleCount is a packed field comprising a flag and the
number of tuples. The format of the
tupleCount field is shown
here:
Currently, the only flag bit supported is 0x8000,
tuples_share_point_numbers.
This means that all of the tuples reference a common set of packed point
numbers that follow immediately after the tuple array.
The glyph variation header is followed by a list of tuple variations. Each tuple variation begins with a tuple variation header. The format of the tuple variation header is as follows:
The
tupleSize field is not the size of the full tuple variation data for this tuple. Rather, it refers to the number of bytes within the tupleData for the entire glyph variation which are used by this tuple. The next tuple data can actually be calculated using code something like the following:
const tupleVariation* NextTupleVariation( const tupleVariation* iTupleVar, int iAxisCount ) { int tBump = sizeof( tupleVariation ); /* four bytes == two * sizeof( UInt16 ) */ int tTupleIndex = iTupleVar->tupleIndex; if ( tTupleIndex & embedded_tuple_coord ) tBump += iAxisCount * sizeof( shortFrac ); if ( tTupleIndex & intermediate_tuple ) tBump += 2 * iAxisCount * sizeof( shortFrac ); return (const tupleVariation*)((char*)iTupleVar + tBump); }
The
tupleIndex is a packed field consisting of a flag and
an index mask into the array of global tuple coordinates. The tupleIndex
field format is described in the following table:
Point numbers are stored as a count followed by the first point number. Each subsequent point is stored as the difference between it and the previous point number. The data is packed into runs of bytes and words.
If the count will fit in 7 bits, the point count is packed into a byte. If the count will not fit in 7 bits, it is stored in 2 bytes, with the high bit of the first byte set. If count = 0, every point on the glyph is used and no data follows. If count is nonzero, a series of runs of bytes and words follows. In this case each run begins with a control byte. The control byte's high bit specifies whether the run is bytes or words and the low 7 bits specify the number of elements in the run minus 1.
The packed point count flag format is as follows:
Deltas for a tuple are stored as an array of x-deltas followed by an array of y-deltas. Each delta corresponds to a point in the glyph outline specified in the point numbers array for this tuple. The X and Y arrays are packed similar to the point numbers. Each array is a series of runs, where each run is a control byte followed by deltas. The control byte specifies the size of the data in the run in the high two bits, and the number of deltas in the low six bits.
The packed tuple delta field formats are shown in the following table. Note that if neither the 0x80 or 0x40 flags are set, then the run contains signed byte deltas.
Component glyph variations are structured very similar to glyph variations for simple glyphs. The difference is that simple glyphs are defined by points and component glyphs are defined by other glyphs. Component glyph variations describe how the position of each component specified by offsets changes and how the metrics of the parent composite glyph change. These changes are represented by fake point numbers. One fake point number is assigned to each component and then 4 more are assigned for the final glyph's metrics.
Consider the component glyph 'é'. If the accent was specified using anchor points, then there would be no use for variation data. The accent can be repositioned by moving the attachment points in either the base glyph or the accent. However, if the accent was specified by an offset, the variation data could be used to describe how its position changes.
The fake point number assignment and the delta assignments for the example component glyph are as follows:
The
'gvar' table is supported on Mac OS only via QuickDraw GX or ATSUI. Applications which do not take advantage of these technologies directly or indirectly may not use style variations within fonts.
The
'gvar' table is not supported on the Newton OS.
The
'fvar' table should have the same number of axes as the
'fvar' table. The glyph and glyph point indices should be the same as in the
'glyf' table.
The only tool currently supported for editing
'gvar' tables is ftxdumperfuser. Note that ftxdumperfuser does not have a specific XML format for
'fvar' tables; you must use the generic table format.
[Table of Contents] | http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6gvar.html | crawl-002 | refinedweb | 1,375 | 62.27 |
Django settings
This document is for Django's SVN release, which can be significantly different from previous releases. Get old docs here: 0.96, 0.95.
A Django settings file contains all the configuration of your Django installation. This document explains how settings work and which settings are available.
The basics
A Django settings file doesn’t have to define any settings if it doesn’t need to. Each setting has a sensible default value. These defaults live in the file
There’s an easy way to view which of your settings deviate from the default settings. The command python manage.py diffsettings displays differences between the current settings file and Django’s default settings.
For more, see the diffsettings documentation.
Using settings in Python code
You shouldn’t alter settings in your applications at runtime. For example, don’t do this in a view:
from django.conf import settings settings.DEBUG = True # Don't do this!
The only place you should assign to settings is in a settings file.
Security
Here’s a full list of all available settings, in alphabetical order, and their default values.
ABSOLUTE_URL_OVERRIDES the section on error reporting via e-mail for more information.
ALLOWED_INCLUDE_ROOTS
Default: True
Whether to append trailing slashes to URLs. This is only used if CommonMiddleware is installed (see the middleware docs). See also PREPEND_WWW.
AUTHENTICATION_BACKENDS
Default: ('django.contrib.auth.backends.ModelBackend',)
A tuple of authentication backend classes (as strings) to use when attempting to authenticate a user. See the authentication backends documentation for details.
AUTH_PROFILE_MODULE
Default: Not defined
The site-specific user profile model used by this site. See the documentation on user profile models for details.
CACHE_BACKEND
Default: 'simple://'
The cache backend to use. See the cache docs.
CACHE_MIDDLEWARE_KEY_PREFIX
Default: '' (Empty string)
The cache key prefix that the cache middleware should use. See the cache docs.
CACHE_MIDDLEWARE_SECONDS
Default: 600
The default number of seconds to cache a page when the caching middleware or cache_page() decorator is used.
DATABASE_ENGINE
Default: '' (Empty string)
The database backend to use. The build-in database backends are 'postgresql_psycopg2', 'postgresql', 'mysql', 'mysql_old', 'sqlite3' and 'oracle'. explictly need to use a TCP/IP connection on the local machine with PostgreSQL, specify localhost here.
DATABASE_NAME
Default: '' (Empty string)
The name of the database to use. For SQLite, it’s the full path to the database file.
DATABASE_OPTIONS
Default: {} (Empty dictionary)
Extra parameters to use when connecting to the database. Consult backend module’s document for available keywords.
DATABASE_PASSWORD
Default: '' (Empty string)
The password to use when connecting to the database. Not used with SQLite.
DATABASE_PORT
Default: '' (Empty string)
The port to use when connecting to the database. An empty string means the default port. Not used with SQLite.
DATABASE_USER
Default: '' (Empty string)
The username to use when connecting to the database. Not used with SQLite.
DATE_FORMAT. Never deploy a site with DEBUG turned on.
DEFAULT_CHARSET
Default: 'utf-8'
Default charset to use for all HttpResponse objects, if a MIME type isn’t manually specified. Used with DEFAULT_CONTENT_TYPE to construct the Content-Type header.
DEFAULT_CONTENT_TYPE
Default: 'text/html'
Default content type to use for all HttpResponse objects, if a MIME type isn’t manually specified. Used with DEFAULT_CHARSET to construct the Content-Type header.
DEFAULT_FROM_EMAIL
Default: 'webmaster@localhost'
Default e-mail address to use for various automated correspondence from the site manager(s).
DEFAULT_TABLESPACE
New in Django development version
Default: '' (Empty string)
Default tablespace to use for models that don’t specify one, if the backend supports it.
DEFAULT_INDEX_TABLESPACE
New in Django development version
Default: '' (Empty string)
Default tablespace to use for indexes on fields that don’t specify one, if the backend supports it.
DISALLOWED_USER_AGENTS
Default: () (Empty tuple)
List of compiled regular expression objects representing User-Agent strings that are not allowed to visit any page, systemwide. Use this for bad robots/crawlers. This is only used if CommonMiddleware is installed (see the middleware docs).
Default: 'localhost'
The host to use for sending e-mail.
See also EMAIL_PORT.
Default: '' (Empty string)
Password to use for the SMTP server defined in EMAIL_HOST. This setting is used in conjunction with EMAIL_HOST_USER when authenticating to the SMTP server. If either of these settings is empty, Django won’t attempt authenticaion. e-mail messages sent with django.core.mail.mail_admins or django.core.mail.mail_managers. You’ll probably want to include the trailing space.
New in Django development version
Default: False
Whether to use a TLS (secure) connection when talking to the SMTP server.
FILE_CHARSET
New in Django development version
Default: 'utf-8'
The character encoding used to decode any files read from disk. This includes template files and initial SQL data files.
FIXTURE_DIRS
Default: () (Empty tuple)
List of locations of the fixture data files, in search order. Note that these paths should use Unix-style forward slashes, even on Windows. See Testing Django Applications.
IGNORABLE_404_ENDS
Default: ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php')
See also IGNORABLE_404_STARTS and Error reporting via e-mail.
IGNORABLE_404_STARTS
Default: ('/cgi-bin/', '/_vti_bin', '/_vti_inf')
A tuple of strings that specify beginnings of URLs that should be ignored by the 404 e-mailer. See SEND_BROKEN_LINK_EMAILS, IGNORABLE_404_ENDS and the section on error reporting via e-mail.
INSTALLED_APPS
Default: () (Empty tuple)
A tuple of strings designating all applications that are enabled in this Django installation. Each string should be a full Python path to a Python package that contains a Django application, as created by django-admin.py startapp.
INTERNAL_IPS
Default: () (Empty tuple)
A tuple of IP addresses, as strings, that:
- See debug comments, when DEBUG is True
- Receive X headers if the XViewMiddleware is installed (see the middleware docs)
JING_PATH
Default: '/usr/bin/jing'
Path to the “Jing” executable. Jing is a RELAX NG validator, and Django uses it to validate each XMLField in your models. See .
LANGUAGE_CODE
Default: 'en-us'
A string representing the language code for this installation. This should be in standard language format. For example, U.S. English is "en-us". See the internationalization docs.
LANGUAGES the internationalization docs for details., make-messages.py will still find and mark these strings for translation, but the translation won’t happen at runtime — so you’ll have to remember to wrap the languages in the real gettext() in any code that uses LANGUAGES at runtime.
LOCALE_PATHS
Default: () (Empty tuple)
A tuple of directories where Django looks for translation files. See the internationalization docs section explaining the variable and the default behavior.
LOGIN_REDIRECT_URL
New in Django development version
Default: '/accounts/profile/'
The URL where requests are redirected after login when the contrib.auth.login view gets no next parameter.
This is used by the @login_required decorator, for example.
LOGIN_URL
New in Django development version
Default: '/accounts/login/'
The URL where requests are redirected for login, specially when using the @login_required decorator.
LOGOUT_URL
New in Django development version
Default: '/accounts/logout/'
LOGIN_URL counterpart.
MANAGERS
Default: () (Empty tuple)
A tuple in the same format as ADMINS that specifies who should get broken-link notifications when SEND_BROKEN_LINK_EMAILS=True.
MEDIA_ROOT
Default: '' (Empty string)
Absolute path to the directory that holds media for this installation. Example: "/home/media/media.lawrence.com/" See also MEDIA_URL.
MEDIA_URL
Default: '' (Empty string)
URL that handles the media served from MEDIA_ROOT. Example: ""
Note that this should have a trailing slash if it has a path component.
Good: "" Bad: ""
MIDDLEWARE_CLASSES
Default:
("django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.doc.XViewMiddleware")
A tuple of middleware classes to use. See the middleware docs.
MONTH_DAY_FORMAT
Default: False
Whether to prepend the “www.” subdomain to URLs that don’t have it. This is only used if CommonMiddleware is installed (see the middleware docs). See also APPEND_SLASH.
PROFANITIES_LIST
Default: '' (Empty string)
A secret key for this particular Django installation. Used to provide a seed in secret-key hashing algorithms. Set this to a random string — the longer, the better. django-admin.py startproject creates one automatically.
SEND_BROKEN_LINK_EMAILS
Default: False
Whether to send an e-mail to the MANAGERS each time somebody visits a Django-powered page that is 404ed with a non-empty referer (i.e., a broken link). This is only used if CommonMiddleware is installed (see the middleware docs). See also IGNORABLE_404_STARTS, IGNORABLE_404_ENDS and the section on error reporting via e-mail
SERIALIZATION_MODULES
Default: Not defined.
A dictionary of modules containing serializer definitions (provided as strings), keyed by a string identifier for that serialization type. For example, to define a YAML serializer, use:
SERIALIZATION_MODULES = { 'yaml' : 'path.to.yaml_serializer' }
SERVER_EMAIL
Default: 'root@localhost'
The e-mail address that error messages come from, such as those sent to ADMINS and MANAGERS. the session docs for more details.
SESSION_EXPIRE_AT_BROWSER_CLOSE
Default: False
Whether to expire the session when the user closes his or her browser. See the session docs.
SESSION_FILE_PATH
New in Django development version
Default: /tmp/
If you’re using file-based session storage, this sets the directory in which Django will store session data. See the session docs for more details.
SESSION_SAVE_EVERY_REQUEST
Default: False
Whether to save the session data on every request. See the session docs.
SITE_ID
Default: Not defined
The ID, as an integer, of the current site in the django_site database table. This is used so that application data can hook into specific site(s) and a single database can manage content for multiple sites.
See the site framework docs.
TEMPLATE_CONTEXT_PROCESSORS
Default: () (Empty tuple)
List of locations of the template source files, in search order. Note that these paths should use Unix-style forward slashes, even on Windows.
See the template documentation.
TEMPLATE_LOADERS
Default: ('django.template.loaders.filesystem.load_template_source',)
A tuple of callables (as strings) that know how to import templates from various sources. See the template documentation.
TEMPLATE_STRING_IF_INVALID
Default: '' (Empty string)
Output, as a string, that the template system should use for invalid (e.g. misspelled) variables. See How invalid variables are handled.
TEST_DATABASE_CHARSET
New in Django development version
Default: None
The character set encoding used to create the test database. The value of this string is passed directly through to the database, so its format is backend-specific.
Supported for the PostgreSQL (postgresql, postgresql_psycopg2) and MySQL (mysql, mysql_old) backends.
TEST_DATABASE_COLLATION
New in Django development version
Default: None
The collation order to use when creating the test database. This value is passed directly to the backend, so its format is backend-specific.
Only supported for mysql and mysql_old backends (see section 10.3.2 of the MySQL manual for details).
TEST_DATABASE_NAME
Default: 'django.test.simple.run_tests'
The name of the method to use for starting the test suite. See Testing Django Applications.
TIME_FORMAT using the manual configuration option (see below),
Default: Django/<version> ()
The string to use as the User-Agent header when checking to see if URLs exist (see the verify_exists option on URLField).
USE_I18N.
Creating your own settings
There’s nothing stopping you from creating your own settings, for your own Django apps. Just follow these conventions:
- Setting names are in all uppercase.
- For settings that are sequences, use tuples instead of lists. This is purely for performance.
- Don’t reinvent an already-existing setting.
Using settings without setting DJANGO_SETTINGS_MODULE django.conf.settings.configure(). explanation of TIME_ZONE, above, for why this would normally occur.) It’s assumed that you’re already in full control of your environment in these cases.
Custom default settings.
Error reporting via e-mail
Server errors
When DEBUG is False, Django will e-mail the users listed in the ADMIN setting whenever your code raises an unhandled exception and results in an internal server error (HTTP status code 500). This gives the administrators immediate notification of any errors.
To disable this behavior, just remove all entries from the ADMINS setting.
404 errors
When DEBUG is False, SEND_BROKEN_LINK_EMAILS is True and your MIDDLEWARE_CLASSES setting includes CommonMiddleware, Django will e-mail the users listed in the MANAGERS setting whenever your code raises a 404 and the request has a referer. (It doesn’t bother to e-mail for 404s that don’t have a referer.)
You can tell Django to stop reporting particular 404s by tweaking the IGNORABLE_404_ENDS and IGNORABLE_404_STARTS settings. Both should be a tuple of strings. For example:
IGNORABLE_404_ENDS = ('.php', '.cgi') IGNORABLE_404_STARTS = ('/phpmyadmin/',)
In this example, a 404 to any URL ending with .php or .cgi will not be reported. Neither will any URL starting with /phpmyadmin/.
To disable this behavior, just remove all entries from the MANAGERS setting.
Questions/Feedback
If you notice errors with this documentation, please open a ticket and let us know!
Please only use the ticket tracker for criticisms and improvements on the docs. For tech support, ask in the IRC channel or post to the django-users list. | http://www.djangoproject.com/documentation/settings/ | crawl-001 | refinedweb | 2,104 | 51.04 |
Related
Tutorial
The React useContext Hook in a Nutshell.
Early February 2019, React introduced Hooks as a way to rewrite your components as simple, more manageable, and classless.
useContext is one of the built-in Hooks, giving functional components easy access to your context. But before we dive into useContext, first some context (pun intended! 🙈).
The React Context API is a simple, easy-to-understand alternative to “prop-drilling” up and down your component tree. Instead of passing local data around and through several layers of components, it takes a step back to create global state, which is extremely useful for data that needs to be shared across components (data such as themes, authentication, preferred language, etc.)
Before Hooks came along, you would need to use class-based components. Class components could manage local state or give you the ability to pass updates back to your state-management. In a class-based component, you could set up a
contextType or a
<Consumer> and access your global state passed down from a provider. But now React has switched to light-weight, functional components and if you’re here, you probably want to do the same.
With functional components, we have an elegant, readable component. In the past, functional components were nice to use, since they were less verbose, but they were quite limited to only really receiving props and rendering a UI based on those props. With Hooks we can manage everything we had used class-based components for.
Example Context
Let’s take a look at how to access context with the
useContext Hook. First, a simple store for our example:
const colors = { blue: "#03619c", yellow: "#8c8f03", red: "#9c0312" }; export const ColorContext = React.createContext(colors.blue);
Provide Context
Then, we can provide our context to whatever branch needs it. In this instance, we create colors for the entire app, so we will wrap it in our
App:
import { ColorContext } from "./ColorContext"; function App() { return ( <ColorContext.Provider value={colors}> <Home /> </ColorContext.Provider> ); }
This provides the context to the rest of the component (represented by the
Home component). No matter how far a component is away from the Home component, as long as it is somewhere in the component tree, it will receive the
ColorContext. There are various ways of consuming our context in any component wrapped with our provider.
Consume Context
We can use
<Consumer> which is available in both class-based and functional components. It would look something like this to use in your JSX:
return ( <ColorContext.Consumer> {colors => <div style={colors.blue}>...</div>} </ColorContext.Consumer> );
Yet, consuming our context this way is only available in the return block so can’t be accessed outside of your JSX code. Of course, there are workarounds, but it isn’t going to be the most ideal.
You can give your component a context type:
MyComponent.contextType = ColorContext; then, you can access the context in your component:
let context = this.context; and that allows you to access your context outside of the JSX. Or instead, you could put in
static contextType = ColorContext;. This works pretty good for class-based components, since it simplifies how to bring your context into your component. But, it will not work in a functional component.
Enter useContext
useContext is the same as
static contextType = ColorContext, except that it’s for a functional component. At the top of your component, you can use it like this:
import React, { useContext } from "react"; const MyComponent = () => { const colors = useContext(ColorContext); return <div style={{ backgroundColor: colors.blue }}>...</div>; };
Now your component is simple, easy to read, and easy to test.
useContext is as simple as that 🤓. Make sure here that you aren’t passing
ColorContext.Consumer to useContext, we want the entire context here, not the provider or consumer. Also, instead of wrapping your JSX in a Consumer, you no longer need to in order to access your context.
useContext will do that for you.
Reference
As with all of the new Hooks, they aren’t necessarily anything new. They follow the same React patterns we have previously learned. For more information on the Hooks, see the official docs. | https://www.digitalocean.com/community/tutorials/react-usecontext | CC-MAIN-2020-34 | refinedweb | 686 | 56.45 |
OverloadedLabels
This page describes the
OverloadedLabels extension, as implemented in Phab:D1331 and included in GHC 8.0. Note that the latest proposal for OverloadedRecordFields proposes changes to
OverloadedLabels from what is described here.
Digression: implicit parametersDigression: implicit parameters
First, let's review Haskell's existing and long-standing implicit parameters. Here is how they work in GHC today.
There is a class
IPdefined thus in
GHC.IP:
class IP (x :: Symbol) a | x -> a where ip :: a -- Hence ip's signature is -- ip :: forall x a. IP x a => a
When you write
?xin an expression, what GHC does today is to replace it with
(ip @"x" @alpha), where
alphais a unification variable and
Of course, that call
(ip @"x" @alpha)gives rise to a constraint
IP "x" alpha, which must be satisfied by the context.
The form
?xin an expression is only valid with
{-# LANGUAGE ImplicitParameters #-}
The pretty printer displays the constraint
IP x tas
?x::t.
The functional dependency
x->aon class
IPimplements the inference rules for implicit parameters. (See the orginal paper.)
There is some magic with implicit-parameter bindings, of form
let ?x = e in ..., which in effect brings into scope a local instance declaration for
IP.
And that's really about it. The class
IP is treated specially in a few other places in GHC. If you are interested, grep for the string "
isIP".
Overloaded labelsOverloaded labels
Now consider the following class:
class IsLabel (x :: Symbol) a where fromLabel :: Proxy# x -> a
Exactly like
IP but without the functional dependency, and with an extra proxy argument. It is also rather similar to a version of the
IsString class from
OverloadedStrings, but with an additional parameter making the string available at the type level.
It behaves like this:
When you write
#xin an expression, what GHC does is to replace it with
(fromLabel @"x" @alpha proxy#), where
alphais a unification variable and
Of course the call
(fromLabel @"x" @alpha proxy#)gives rise to a constraint
(IsLabel "x" alpha)which must be satisfied by the context.
The form
#xin an expression is only valid with
{-# LANGUAGE OverloadedLabels #-}(which will be implied by
OverloadedRecordFields).
The pretty printer could print
IsLabel "x" tas
#x::t(but it doesn't, yet).
There is no functional dependency, and no equivalent to the implicit-parameter
let ?x=ebinding. So overloaded labels are much less special than implicit parameters.
Notice that overloaded labels might be useful for all sorts of things that are nothing to do with records; that is why they don't mention "record" in their name.
User code can call
fromLabel directly (unlike
ip), thanks to the proxy argument.
SyntaxSyntax
It's not absolutely necessary to use
#x for a field. Here are some alternatives:
We could say "if there is at least one data type in scope with a field
x, then
xis treated like
(fromLabel @"x" @alpha)". But I hate it. And it doesn't work for virtual fields like
#areaabove.
(Suggested by Edward K.) We could define a magic module
GHC.ImplicitValues, and say that if you say
import GHC.ImplicitValues( p, q, area )
then all occurrences of
p,
q,
areawill be treated as implicit values (written
#p,
#q,
#areaabove). That has the merit that it works fine for virtual fields like
area, and it removes the
#psyntactic clutter.
It leaves open questions. If you declare a H98 record with fields
p, etc, do you have to import
pfrom
GHC.ImplicitValuesas well? Presumably not? What if you import such a record?
But neither of these exploit the similarity to implicit parameters.
I really really like the similarity between the models, and I think it'd be a pity to lose it.
And would implicit parameters really be better (from a software engineering point of view) if we replaced
?x notation with
import GHC.ImplicitParameters( x )?
Note that the
#x form only behaves specially if you have
OverloadedLabels or
OverloadedRecordFields enabled. So existing libraries that use
OverloadedRecordFields as well, you'll have to put a space between an infix
(a # b) not
(a #b). But that's not so bad. And exactly the same constraint applies with
MagicHash: you must put a space between the
a and the
(a# b). I don't think this is a big deal.
#as an operator will work fine. If you want
#and its second argument, thus
#, not
The downside of the
#x syntax is that uses of lenses like
foo^.bar.baz become something like
foo ^. #bar . #baz or
foo ^. xx #bar . xx #baz (if we need a combinator
xx to turn an implicit value into a lens). However, this can be mitigated to some extent by users by making their own definitions
bar = xx #bar; baz = xx #baz.
Sadly the
#x syntax clashes with hsc2hs, so users will have to write
##x in
.hsc files. But we don't see a better alternative.
ReflectionsReflections
An
IsLabel constraint is, in effect, rather like a (family of) single-method type classes. Instead of
f :: Ix a => a -> a -> a -> Bool f i u l = inRange (l,u) i
which uses only one method from
Ix, you could write the finer-grained function
f :: (IsLabel "inRange" ((a,a) -> a -> Bool)) => a -> a -> Bool f i u l = #inRange (l,u) i
Note that this example has nothing to do with records, which is part of the point.
Perhaps
IsLabel will find other uses.
It is rather reminiscent of Carlos Camaro's System CT.
ImplementationImplementation
The implementation is fairly straightforward and close to (but simpler than) the existing
ImplicitParameters extension. The key points:
We extend the lexer to treat
#xas a single lexeme (only when
OverloadedLabelsis enabled) and parse it into a new constructor
HsOverLabel "x"of
HsSyn.
A new module
GHC.OverloadedLabelsdefines the
IsLabelclass
When the typechecker sees
HsOverLabel "x", it emits a new wanted constraint
IsLabel "x" alpha, just like
HsIPVar.
The only complicated part is that the lexer currently treats
#line pragmas, so some more substantial lexer tweaks are needed.
#specially if it is the first symbol on a line, because of
#!shell script markers and | https://gitlab.haskell.org/ghc/ghc/-/wikis/records/overloaded-record-fields/overloaded-labels | CC-MAIN-2022-21 | refinedweb | 1,016 | 56.45 |
Concurrency provides many ways to shoot yourself in the foot. The rules for today help you to know these dangers and to overcome them.
First, here are three rules for this post.
thread
shared_ptr
They are more rules which I ignore because they have no content.
This rule is quite apparent; therefore, I can make it short. Passing data to a thread by value gives you immediately two benefits:
Of course, the crucial question is: What does a small amount of data mean? The C++ core guidelines is not clear about this point. In the rule F.16 For “in” parameters, pass cheaply-copied types by value and others by reference to const to functions, the C++ core guidelines states that 4 * sizeof(int) is a rule of thumb for functions. Meaning, smaller than 4 * sizeof(int) should be passed by value; bigger than 4 * sizeof(int) by reference or pointer.
const to functions,
In the end, you have to measure the performance if necessary.
Imagine, you have an object which you want to share between unrelated threads. The key question is, who is the owner of the object and, therefore, responsible for releasing the memory? Now you can choose between a memory leak if you don't deallocate the memory or undefined behaviour because you invoked delete more than once. Most of the times, the undefined behaviour ends in a runtime crash.
// threadSharesOwnership.cpp
#include <iostream>
#include <thread>
using namespace std::literals::chrono_literals;
struct MyInt{
int val{2017};
~MyInt(){ // (4)
std::cout << "Good Bye" << std::endl;
}
};
void showNumber(MyInt* myInt){
std::cout << myInt->val << std::endl;
}
void threadCreator(){
MyInt* tmpInt= new MyInt; // (1)
std::thread t1(showNumber, tmpInt); // (2)
std::thread t2(showNumber, tmpInt); // (3)
t1.detach();
t2.detach();
}
int main(){ std::cout << std::endl;
threadCreator();
std::this_thread::sleep_for(1s); std::cout << std::endl;
}
Bear with me. The example is intentionally so easy. I let the main thread sleep for one second to be sure that it outlives the lifetime of the child thread t1 and t2. This is, of course, no appropriate synchronisation, but it helps me to make my point. The vital issue of the program is: Who is responsible for the deletion of tmpInt (1)? Thread t1 (2), thread t2 (3), or the function (main thread) itself. Because I can not forecast how long each thread runs I decided to go with a memory leak. Consequentially, the destructor of MyInt (4) is never called:
The lifetime issues are quite easy to handle if I use a std::shared_ptr.
// threadSharesOwnershipSharedPtr.cpp
#include <iostream>
#include <memory>
#include <thread>
using namespace std::literals::chrono_literals;
struct MyInt{
int val{2017};
~MyInt(){
std::cout << "Good Bye" << std::endl;
}
};
void showNumber(std::shared_ptr<MyInt> myInt){ // (2)
std::cout << myInt->val << std::endl;
}
void threadCreator(){
auto sharedPtr = std::make_shared<MyInt>(); // (1)
std::thread t1(showNumber, sharedPtr);
std::thread t2(showNumber, sharedPtr);
t1.detach();
t2.detach();
}
int main(){
std::cout << std::endl;
threadCreator();
std::this_thread::sleep_for(1s);
std::cout << std::endl;
}
Two small changes to the source code were necessary. First, the pointer in (1) became a std::shared_ptr and second, the function showNumber takes a smart pointer instead of a plain pointer.
How expensive is a thread? Quite expensive! This is the issue behind this rule. Let me first talk about the usual size of a thread and then about the costs of its creation.
A std::thread is a thin wrapper around the native thread. This means I'm interested in the size of a Windows thread and a POSIX thread.
I didn't find numbers who much time it takes to create a thread. To get a gut feeling, I made a simple performance test on Linux and Windows.
I used GCC 6.2.1 on a desktop and cl.exe on a laptop for my performance tests. The cl.exe is part of the Microsoft Visual Studio 2017. I compiled the programs with maximum optimisation. This means on Linux the flag O3 and on Windows Ox.
Here is my small test program.
// threadCreationPerformance.cpp
#include <chrono>
#include <iostream>
#include <thread>
static const long long numThreads= 1000000;
int main(){
auto start = std::chrono::system_clock::now();
for (volatile int i = 0; i < numThreads; ++i) std::thread([]{}).detach(); // (1)
std::chrono::duration<double> dur= std::chrono::system_clock::now() - start;
std::cout << "time: " << dur.count() << " seconds" << std::endl;
}
The program creates 1 million threads which execute an empty lambda function (1). These are the numbers for Linux and Windows:
This means that the creation of a thread took about 14.5 sec / 1000000 = 14.5 microseconds on Linux.
It took about 44 sec / 1000000 = 44 microseconds on Windows.
To put it the other way around. You can create about 69 thousand threads on Linux and 23 thousand threads on Windows in one second.
What is the easiest way to shot yourself in the foot? Use a condition variable! You don't believe? Wait for the next post!08
All 1580644
Currently are 127 guests and no members online
Kubik-Rubik Joomla! Extensions
Read more...
Read more... | http://www.modernescpp.com/index.php/c-core-guidelines-the-remaining-rules-to-concurrency | CC-MAIN-2019-09 | refinedweb | 842 | 74.69 |
I’ve been working on developing an iOS app in Swift . It’s my first experience developing in pure Swift, without any Objective-C. This project has taught me a lot about the current state of testing in Swift, including different testing approaches and best practices. In this post, I’ll share some of my experiences and discuss how we have approached testing different types of Swift code. I’ll also talk about some useful testing libraries.
XCTest
XCTest has been the standard out-of-the-box iOS testing framework for as long as I can remember. This is what you get by default in Swift. Though it has been around for a while, I had not used XCTest much in the past. Instead, I usually opted for Kiwi when working in Objective-C. Unfortunately, Kiwi is not supported in Swift . I wanted to give vanilla XCTest a try, so for the first few months, that’s all I used.
On one hand, I learned that XCTest is a very bare-bones and limited testing framework. This wasn’t a particularly surprising revelation—I think most people find it to be average at best.
On the other hand, I also found that you can test most things with a high success rate using just XCTest. The tests may not be the most beautiful, and they may require a lot of boilerplate, but you are usually able to find some way to write the test you want.
General Test Structure
When writing tests in XCTest, you usually create a new class that extends XCTestCase, and add your tests as methods to your new class. It usually looks like this:
class MyClassTests: XCTestCase { func testCaseA() { ... } func testCaseB() { ... } }
Synchronous Tests
Synchronous tests are usually straightforward. You instantiate the object you wish to test, call a method, and then use one of the XCTest assertions to confirm the outcome that you expect.
func testAddTwoNumbers { let adder = MyAdderClass() let result = adder.add(4, otherNumber: 8) XCTAssertEqual(result, 12) }
Asynchronous Tests
Asynchronous tests are a little more tricky, though you can usually use XCTest’s XCTestExpectation class. As an example, suppose that we have a class that takes a number as input, makes a network call to get a second number, adds them together, and calls a callback with the result. To test something like this, we probably want to be able to stub the network call to return a known value, and assert that the result callback contains an expected value. For the sake of clarity, suppose this class looks like this:
class NetworkAdder { func add(userProvidedNumber: Int, callbackWithSum: (Int) -> ()) { self.getNumberFromNetwork({ numberFromNetwork in let sum = userProvidedNumber + numberFromNetwork callbackWithSum(sum) }) } func getNumberFromNetwork(callback: (Int) -> ()) { let numberFromNetwork = // some operation that get a number callback(numberFromNetwork) } }
The standard way to test this using XCTest would be to extend NetworkAdder with an inline class, and override getNumberFromNetwork to return a fixed value. Then you can use some XCTest assertions in the callback you pass into callbackWithSum. However, you need to ensure that the test waits until the assertions are checked before exiting. To do this, you can use the XCTestExpectation class:
class NetworkAdderTests: XCTestCase { class MockNetworkAdder: NetworkAdder { override func getNumberFromNetwork(callback: (Int) -> ()) { callback(5) // force this to return 5 always for the test } } func testAddAsync() { let expectation = expectationWithDescription("the add method callback was called with the correct value") let networkAdder = MockNetworkAdder() networkAdder.add(8, callbackWithSum: { callbackWithSum in XCTAssertEqual(callbackWithSum, 13) expectation.fulfill() }) waitForExpectationsWithTimeout(1, handler: nil) } }
While the above mocking strategy requires a lot of boilerplate, it does allow you to test a wide variety of scenarios. In fact, I have found that most scenarios can be tested with some combination of the above synchronous and asynchronous examples.
Testing View Controllers
View controllers are another central testing concern. They can usually be tested effectively using UITests, which I’ll discuss later. However, sometimes unit tests are more appropriate. I have found that if you want to unit test a view controller, it’s important to instantiate it programmatically from your storyboard. This ensures that all of its outlets are properly instantiated as well. I have had several scenarios where I wanted to test the state of one or more view controller outlets at the end of a test (e.g., the text of a UILabel, the number of rows in a table view, etc.).
You can instantiate your view controllers using the storyboard by doing the following:
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let myViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MyViewControllerIdentifier") as! MyViewController myViewController.loadView()
The above code assumes that you have set the identifier on
MyViewController to MyViewControllerIdentifier. I usually run something similar to the above snippet in the before each block for my MyViewController tests.
Upgrading with Quick and Nimble
Although I was able to test most things effectively using XCTest, it didn’t feel great. My tests were often verbose, didn’t read well, and would sometimes require a lot of boilerplate code.
I wanted to try a third-party testing framework to see if it alleviated any of these issues. Quick and Nimble seem to be the defacto third-party Swift testing framework.
Quick is a testing framework that provides a testing structure similar to RSpec or Kiwi. Nimble is a library that provides a large set of matchers to use in place of XCTest’s assertions. Quick and Nimble are usually used together, though they don’t absolutely need to be.
The first thing that you get with Quick and Nimble is much better test readability. The above synchronous test written using Quick and Nimble becomes:
describe("The Adder class") { it(".add method is able to add two numbers correctly") { let adder = MyAdderClass() let result = adder.add(4, otherNumber: 8) expect(result).to(equal(12)) } }
Similarly, the asynchronous test becomes:
describe("NetworkAdder") { it(".add works") { var result = 0 let networkAdder = MockNetworkAdder() networkAdder.add(8, callbackWithSum: { callbackWithSum in result = callbackWithSum }) expect(result).toEventually(equal(13)) } }
The other really helpful item you get out-of-the-box with Nimble is the ability to expect that things don’t happen in your tests. You can do this via
expect(someVariable).toNotEventually(equal(5)) . This makes certain asynchronous tests much easier to write compared to using XCTest, such as confirming that functions are never called, exceptions are never thrown, etc.
Overall, I would strongly recommend using Quick and Nimble over XCTest. The only potential negative that I’ve observed is that XCode seems to get confused more easily when running and reporting results for Quick tests. Sometimes the run button doesn’t immediately appear next to your test code, and sometimes it can forget to report results or even run some tests when running your full test suite. These issues seem to be intermittent and are usually fixed by re-running your test suite. To be fair, I have also observed XCode exhibit the same behavior for XCTests; it just seems to happen less frequently.
Integration Testing
The last item I would like to discuss is UITests. In the past, I have used KIF or something similar to write integration-style UI tests.
I initially tried to get KIF working, but experienced some difficulty getting it to build and work in our Swift-only project. As an alternative, I decided to try the UITest functionality built into XCode, and I’m glad that I did. I have found the UI tests to be extremely easy to write, and we have been able to test large amounts of our app using them.
UITests work similarly to KIF or other such test frameworks—they instantiate your application and use accessibility labels on your UI controls to press things in your app and navigate around. You can watch these tests run in the simulator, which is pretty neat. While navigating around, you can assert certain things about your app, such as the text on a UILabel, the number of rows in a UITableView, the text they are displaying, etc.
Let’s walk through an example UITest for an app that contains a button that adds rows to a UITableView, and updates a label with the number of rows in the table. The test will press the button three times and check that a row is added for each press, and the label text is updated appropriately. The app looks like this:
The UITest code looks like this:
func testAddRowsToTable() { let app = XCUIApplication() let addRowButton = app.buttons["addRowToTableButton"] XCTAssertEqual(app.tables["tableView"].cells.count, 0) XCTAssertEqual(app.staticTexts["numTableViewRowsLabel"].label, "The table contains 0 rows") addRowButton.tap() XCTAssertEqual(app.tables["tableView"].cells.count, 1) XCTAssertEqual(app.staticTexts["numTableViewRowsLabel"].label, "The table contains 1 row") addRowButton.tap() XCTAssertEqual(app.tables["tableView"].cells.count, 2) XCTAssertEqual(app.staticTexts["numTableViewRowsLabel"].label, "The table contains 2 rows") addRowButton.tap() XCTAssertEqual(app.tables["tableView"].cells.count, 3) XCTAssertEqual(app.staticTexts["numTableViewRowsLabel"].label, "The table contains 3 rows") }
To set this test up correctly, the Add Row To Table button accessibility label was set to addRowToTableButton , the UITableView’s accessibility identifier was set to tableView , and the bottom UILabel’s accessibility identifier was set to numTableViewRowsLabel . You can watch the test run in the simulator—it looks like this:
We found it helpful to create a UITest base class where we could set up an application and do some other configuration work. This class looks like this:
import XCTest class BaseUITest: XCTestCase { var app: XCUIApplication? override func setUp() { super.setUp() app = XCUIApplication() app!.launchArguments.append("UITesting") continueAfterFailure = false // set to true to continue after failure app!.launch() sleep(1) // prevents occasional test failures } }
There are a few things to note in the above code sample. The first and most obvious is the
sleep(1) before returning from the
setUp function. We noticed that some of our tests would fail without this—presumably because the test would start running before the app was up and running in the simulator.
Additionally, we are passing a
UITesting string value into our app launch arguments. Occasionally, you will need to mock things out for your UITests (e.g., network calls, file IO, etc.). The best way we found to do this is to set a test-specific launch argument that we can check for in our code and inject UITest classes instead of production classes when injecting our app dependencies on startup. This was mostly inspired by this Stack Overflow post .
Recording Tests
A great, and often overlooked, UITest feature is the ability to record interaction sequences with your app and have XCode write your UITest for you. This won’t add any assertions into your test, but it will create a sequence of UI interactions that you can use as a starting point for your test. You can start a recording by pressing the red record button on the bottom of the screen. This will launch your app and allow you to start using it. Each screen interaction is immediately translated to a line of code that you can see show up dynamically in your test function. When you’re finished, you simply press stop recording.
UI Testing Gotchas
Aside from that one-second delay that we added to the beginning of our UI tests to prevent periodic test failures, there are a few other tricky items to be aware of.
If your test involves typing text into a text field, you need to tap on the text field first to bring it into focus (similar to what you would do if you were using the app). Additionally, you need to ensure that Connect Hardware Keyboard is unchecked on the simulator. This allows the onscreen keyboard to be used when typing into text fields, instead of your laptop keyboard.
When attempting to programmatically access elements from your app, the XCode accessibility UI shows how each control is categorized. You can modify this by selecting different categories. So, for example, to access a UIButton via
app.buttons["myButtonIdentifier"] , your control element needs to be categorized as a Button .
Most of the time, you won’t re-categorize elements, but this screen allows you to look up how to access each control in your app.
Another thing to be careful with is understanding where your app starts when it is launched. If you have an app that requires user login, and it either starts on the login screen if the user is not logged in, or takes the user to the app if they are, your UI tests need to be aware of this. In our tests, we first check to see if the user is logged in and either continue running or log them in/out as » Testing with Swift – Approaches & Useful Libraries
评论 抢沙发 | http://www.shellsec.com/news/15912.html | CC-MAIN-2017-09 | refinedweb | 2,113 | 53.71 |
Allows gnuplot to compile on OS X 10.3
There were two modifications
1. S_OUTPUT had to be renamed (conflicted with an
OpenTransport constant) In this patch, I renamed it to
S_OUTPUT_. Might want to look into putting this into some
kind of namespace to "properly" fix this problem.
2. removed the is_3d_plot extern from tkcanvas.trm. For
some reason this was causing a conflict with is_3d_plot
from command.h, even though they were supposed to be
the same thing. Very strange. Perhaps there's some
mysterious macro screwing around behind the scenes?
Contact Info:
Ethan Tira-Thompson
ejt@andrew.cmu.edu
Nobody/Anonymous
2003-10-29
a patch file for the changes listed above
Hans-Bernhard Broeker
2003-10-30
Logged In: YES
user_id=27517
1) C has no namespaces to move to, and certainly not
regarding the preprocessing phase. You just have to avoid
stuff already used by others.
2) Please explain that "conflict" in more detail. The error
message from the compiler would be needed at minimum, a
preprocessed source file might be even more helpful (--> -
save-temps option of GCC).
Gordon Miller
2003-11-24
Logged In: YES
user_id=125426
When doing a build on my MacOSX 10.3 system I got the same
error. The conflict arises due to a duplicate declaration
of S_OUTPUT. It is declared in gnuplot as en enumeration
and is also declared within an unnamed enumeration in one of
the MacOSX header files (I can't remember which one off of
the top of my head).
I performed the same modifications (not using the patch) as
the original author of this patch and was able to
successfully compile gnuplot from CVS. Of course, having
one of the enumerations terminate with an underscore while
the rest do not isn't really appealing. As for namespaces I
think that coming up with a more unique naming convention
(GP_S_OUTPUT maybe) would be nice. I'd be more than happy
to work on a renaming to get it working cleanly.
I do development on both Linux and MacOSX
Hans-Bernhard Broeker
2003-12-01
Hans-Bernhard Broeker
2003-12-01
Logged In: YES
user_id=27517
Today I checked in a patch to fix issue 1) (renamed S_OUTPUT
to SET_OUTPUT --- appending a _ just felt wrong).
That still leaves me puzzled as to issue 2). I've yet to
see a description of that "conflict".
Christopher Fonnesbeck
2003-12-01
Logged In: YES
user_id=28680
Your patch worked fine for me. Builds and isntalls without a hitch
now.
Chris Fonnesbeck
chris at fonnesbeck.org
Hans-Bernhard Broeker
2004-03-29
Logged In: YES
user_id=27517
Per, I'm handing this over to you. I guess this can be
closed as Fixed, but have no way of checking.
Hans-Bernhard Broeker
2004-03-29
Per Persson
2004-03-29
Per Persson
2004-03-29
Logged In: YES
user_id=350616
1) Is fixed by the 2003-12-01 patch (as well as the new aquaterm.trm)
2) I don't see the problems described by the original poster.
So, I consider this issue Fixed and will close it as such. Should (2)
surface again then it should be assigned a new issue # of its own. | http://sourceforge.net/p/gnuplot/patches/91/ | CC-MAIN-2014-41 | refinedweb | 537 | 73.47 |
How to check the Vue Version Quickly
In this tutorial, we are going to learn about how to check the vue version currently we are using in our project.
Note: This tutorial assumes that you already created a new vue project using the vue-cli.
Using the Vue.version
We can use the
Vue.version property to check the current vue version during a runtime.
Example:
In your
main.js file add the following
log.
main.js
import Vue from 'vue' import App from './App.vue' console.log(Vue.version); // 2.6.11 new Vue({ render: h => h(App), }).$mount('#app')
Using the terminal
Inside the terminal, you can check the vue version by running the following npm command.
npm list vue
Output:
vue@2.6.11
or you can view the vue version directly, inside your project by opening a
package.json file.
package.json
{ "name": "vue-todo", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "core-js": "^3.6.4", "vue": "^2.6.11" }, | https://reactgo.com/check-vue-version/ | CC-MAIN-2021-17 | refinedweb | 181 | 61.43 |
Hi
We are experiencing performance problems with a C++ program that we cannot explain. The example below shows the problem. A loop assigns a value to a string 3 million times - this starts off taking about 1s. Between calls to this loop we make a call to the localtime function, after the call the string assignment loop takes 10-20 times longer.
Calls to localtime, ctime and to the boost local_time functions give this performance degradation, but calls to gmtime do not.
Can anyone help explain why this is happening!
#include <iostream>
#include <string>
#include <time.h>
//#include "boost/date_time/posix_time/posix_time.hpp"
using namespace std;
//using namespace boost::posix_time;
std::string doLoop()
{
cout << "LOOP START" << endl;
system("date");
string s;
int i;
for (i=0; i < 30000000 ; i++)
{
s="XXXX";
}
cout << "Looped " << i << " times." << endl;
cout << "LOOP END" << endl;
system("date");
cout << endl;
return s;
}
int main()
{
// This loop runs quickly
doLoop();
// Still quick
doLoop();
// Now as soon as we call ctime or localtime (uncomment any one of these to test) we see the issue
//cout << "Return value from ctime:" << ctime(NULL) << endl;
cout << "Calling localtime:" << endl; localtime(NULL);
// We also get the same performance problem using boost date/times (uncomment the boost headers and using statements above to test)
//ptime now = second_clock::local_time();
// NB) calls to gmtime do not cause a problem!
//cout << "Calling gmtime:" << endl; time_ptr=gmtime(&seconds);
// Any loop we do after a these operations takes much longer
doLoop();
doLoop();
}
This is the output we get:
LOOP START
Fri Nov 2 13:47:48 GMT 2012
Looped 30000000 times.
LOOP END
Fri Nov 2 13:47:49 GMT 2012
LOOP START
Fri Nov 2 13:47:49 GMT 2012
Looped 30000000 times.
LOOP END
Fri Nov 2 13:47:50 GMT 2012
Calling localtime:
LOOP START
Fri Nov 2 13:47:50 GMT 2012
Looped 30000000 times.
LOOP END
Fri Nov 2 13:48:14 GMT 2012
LOOP START
Fri Nov 2 13:48:14 GMT 2012
Looped 30000000 times.
LOOP END
Fri Nov 2 13:48:36 GMT 2012
Topic
SystemAdmin 110000D4XK
196 Posts
Pinned topic Performance problem after call to localtime - AIX6.1, XL C/C++ 11.1
2012-11-02T14:18:52Z |
Updated on 2012-11-08T17:58:51Z at 2012-11-08T17:58:51Z by SystemAdmin
- SystemAdmin 110000D4XK196 Posts
Re: Performance problem after call to localtime - AIX6.1, XL C/C++ 11.12012-11-08T17:58:51Z
This is the accepted answer. This is the accepted answer.Just in case anyone else comes across a similar problem and is afraid to post in case they get a similarly overwhelming response, this is what we have found out....
From AIX 6.1 onwards the default value of the TZ environment variable uses an Olson format time-zone setting (whereas previous versions use POSIX format). Additionally there is a performance issue with using the Olson database for timezone calculations on AIX 6.1
So, we resolved our performance problem by setting the TZ environment variable back to a POSIX format timezone string. An alternative solution would have been to upgrade to AIX 7.1 as apparently the problem is resolved in this OS version, even for Olson format time-zone strings.
This APAR vaguely touches on the problem.... | https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014904649&ps=10 | CC-MAIN-2017-34 | refinedweb | 544 | 70.94 |
Building the Custom Server Control Examples
This topic describes how to compile the custom control examples into an assembly and use the controls in ASP.NET Web pages. It also describes how you can use the App_Code folder of an ASP.NET Web site to test control code without compiling them.
Creating a Control Assembly
To create and compile the custom controls into an assembly.
Re-run the compilation command in Step 4 whenever you add new source files to the source code folder or change existing ones.
Creating an ASP.NET Web Site
To create the ASP.NET Web site
Create an ASP.NET Web site using Internet Information Services (IIS) or another tool.
For information about creating and configuring an IIS virtual directory, see How to: Create and Configure Virtual Directories in IIS.
Create a Bin folder under the root folder of your Web site.
Copy the assembly you created in the preceding procedure to the Web site's Bin folder.
Create a text file named Web.config in the root folder of your Web site, add the following XML to the Web.config file, and then save the file.:
Using the App_Code Folder for Testing Controls
You can use the dynamic compilation feature of ASP.NET 2.0 to test controls without compiling them into an assembly manually.
To put controls in the App_Code folder
Create an App_Code folder under the root folder of your Web site.
Copy the source files for the controls and related classes into the App_Code folder.
If you previously added an assembly for the control to the Bin folder, delete it.
Change the entry under the controls section in the Web.config file to the following highlighted entry, which maps the control's namespace to a tag prefix:
For more information, see @ Register.
Request the .aspx pages in a Web browser.
If you place the source files for the QuickContacts and ContactCollectionEditor classes from Web Control Collection Property Example .NET Framework SDK, using the following syntax:. | https://msdn.microsoft.com/EN-US/library/az5kdaz0(v=vs.85) | CC-MAIN-2017-39 | refinedweb | 334 | 58.99 |
Entwurf SetzeArbeitsEbeneProxy
Beschreibung==
Dieser Befehl platziert ein Ebenen Proxy Objekt, das auf die aktuelle Arbeitsebene ausgerichtet ist.
Dieses Proxy Objekt kann wie eine Fläche verwendet werden, um mit dem Draft SelectPlane/de Werkzeug die Bearbeitungsebene schnell zu wechseln. Die Kameraposition und Sichtbarkeit der Objekte in der 3D Ansicht kann im Proxy Objekt gespeichert und bei Verwendung des Werkzeugs Draft SelectPlane/de jederzeit wiederhergestellt werden.
Three working plane proxies showing different orientations and offsets
How to use
- Make sure the Working Plane is set as you want.
- Then go to the menu Draft → Utilities →
Create Working Plane Proxy.
Notes:
- The working plane stored in the Proxy object can be restored by double-clicking the object in the tree view, or by selecting the Proxy object and using the
Draft SelectPlane button.
- The position of the camera is stored in the Proxy object upon creation. This position can be updated anytime: zoom, pan and rotate the view as you wish, then right-click the Proxy object in the tree view, and select
Write camera position.
- The visibility state of all objects is also stored in the Proxy object upon creation. This state can be updated anytime: set the ViewVisibility property of the objects to
trueor
falseas desired, then right-click the Proxy object in the tree view, and select
Write objects state.
- Plane proxies can be moved and rotated like any other object so that they define the desired working plane. Their visual appearance can also be changed in the property editor.
Properties
Data
- DataPlacement: specifies the position of the proxy object and the corresponding working plane.
- DataPosition: specifies the coordinates of the proxy object.
- DataAngle: specifies the rotation angle of the proxy object.
- DataAxis: specifies the axis to use for the rotation angle.
View
- ViewDisplay Size: specifies both length and width of the proxy object. If the object is created in the tree view but no element is visible in the 3D view, increase this value until it is visible.
- ViewArrow Size: specifies the size of the arrows indicating the three axes of the plane proxy.
- ViewRestore View: if it is
truethe camera position will be restored to the saved position when using the proxy with
Draft SelectPlane or by double-clicking on it.
- ViewRestore State: if it is
truethe visibility state of all objects will be restored to the saved state when using the proxy with
Draft SelectPlane or by double-clicking on it.
Scripting
See also: Draft API and FreeCAD Scripting Basics.
Working plane proxy objects can be used in macros and from the Python console by using the following function:
WPProxy = makeWorkingPlaneProxy(placement)
- Creates a
WPProxyobject from the given
placementwhich is a
FreeCAD.Placement.
- A placement is defined by a base point, given by its
FreeCAD.Vector, and a
FreeCAD.Rotation.
The size of the Plane Proxy can be changed by overwriting its
ViewObject.DisplaySize and
ViewObject.ArrowSize attributes, with units in millimeters.
The Plane Proxy has a "Face" object as its
Shape attribute. This face can be used to set the current working plane by calling its
alignToFace() method.
Example:
import FreeCAD, FreeCADGui, Draft currentWP = FreeCAD.DraftWorkingPlane place = currentWP.getPlacement() WPProxy = Draft.makeWorkingPlaneProxy(place) WPProxy.ViewObject.DisplaySize = 3000 WPProxy.ViewObject.ArrowSize = 200 YAxis = FreeCAD.Vector(0, 1, 0) point2 = FreeCAD.Vector(3000, 0, 0) place2 = FreeCAD.Placement(point2, FreeCAD.Rotation(YAxis, 90)) WPProxy2 = Draft.makeWorkingPlaneProxy(place2) WPProxy2.ViewObject.DisplaySize = 3000 WPProxy2.ViewObject.ArrowSize = 200 Axis = FreeCAD.Vector(1, 1, 1) point3 = FreeCAD.Vector(-3000, 3000, 0) place3 = FreeCAD.Placement(point3, FreeCAD.Rotation(Axis, 90)) WPProxy3 = Draft.makeWorkingPlaneProxy(place3) WPProxy3.ViewObject.DisplaySize = 3000 WPProxy3.ViewObject.ArrowSize = 200 FreeCAD.ActiveDocument.recompute() currentWP.alignToFace(WPProxy3.Shape) FreeCADGui.Snapper.setGrid()
- | https://wiki.freecadweb.org/index.php?title=Draft_SetWorkingPlaneProxy/de&oldid=556106&curid=170035 | CC-MAIN-2021-04 | refinedweb | 609 | 50.53 |
Polymorphic line scaler. More...
#include <LineScalers.hh>
Polymorphic line scaler.
Abstract base class for line scalers. Can be used when one basic algorithm should work in combination with multiple line scalers (e.g. several Scale_XonY variants). A line scaler takes one line of input pixels and outputs a different line of pixels. The input and output don't necessarily have the same number of pixels. An alternative (which we used in the past) is to templatize that algorithm on the LineScaler type. In theory this results in a faster routine, but in practice this performance benefit is often not measurable while it does result in bigger code size.
Definition at line 282 of file LineScalers.hh.
Is this scale operation actually a copy? This info can be used to (in a multi-step scale operation) immediately produce the output of the previous step in this step's output buffer, so effectively skipping this step.
Implemented in openmsx::PolyScaleRef< Pixel, Scaler >, and openmsx::PolyScale< Pixel, Scaler >.
Referenced by openmsx::calcEdgesGL(), and openmsx::RGBTriplet3xScaler< Pixel >::RGBTriplet3xScaler().
Actually scale a line.
Implemented in openmsx::PolyScaleRef< Pixel, Scaler >, and openmsx::PolyScale< Pixel, Scaler >. | http://openmsx.org/doxygen/classopenmsx_1_1PolyLineScaler.html | CC-MAIN-2019-18 | refinedweb | 189 | 51.75 |
Moving average indicators are commonly used to give traders a general idea about the direction of the trend by smoothing the price series. One of the big drawbacks to most common moving averages is the lag with which they operate. A strong trend up or down may take a long time to get confirmation from the series leading to lost profit.
In 2005, Alan Hull devised the Hull Moving Average (HMA) to address this problem.
The calculation is relatively straightforward and can be done in 4 steps after choosing the number of periods, N, to use in the calculation:
- Calculate the simple moving average over the past N periods.
SMA1 = SMA(price, N)
- Calculate the simple moving average over the past N/2 periods, rounded to the nearest whole value.
SMA2 = SMA(price, int(N/2))
- Multiply the shorter moving average by 2 and then subtract the first moving average from this.
SMA_diff = 2 * SMA2 - SMA1
- Take the moving average of this value over a period length equal to the square root of N, rounded to the nearest whole number.
HMA = SMA(SMA_diff, int(sqrt(N)))
This winds up being more responsive to recent changes in price because we’re taking the most recent half of our data and multiplying it by 2. This provides an additional weighting on those values before we smooth things out again with the final moving average calculation. Confusingly, many blogs list each of these moving averages as weighted moving averages, but never specify the weights themselves. Don’t worry about that, all we have are a few simple moving averages which are weighted before being combined at the end.
For completeness, we can also write this out mathematically.
If we are calculating the SMA at time t over the last N periods, we’re going to call this SMA^N_t. For moving averages, we’re just getting a summation over the last N prices (we’ll use P for prices) and dividing by N like so:SMA_t^N = \frac{1}{N}\sum_{i=1}^{N} P_{i-N}
SMA_t^M = \frac{1}{M}\sum_{i=1}^{M} P_{i-M}
HMA_t^H = \frac{1}{H} \sum_{i=1}^{H} (2SMA^M_t - SMA^N_t)
where the symbols M and H are N/2 and the square root of N rounded to the nearest integer values.
M = \bigg\lfloor \frac{N}{2} \bigg\rceil
H = \bigg\lfloor \sqrt{N} \bigg\rceil
Hopefully, that’s all pretty straightforward. Let’s get to some examples in Python to illustrate how this works.
Hull Moving Average in Python
Like usual, let’s grab a few packages.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import yfinance as yf
From here, we can write a function to calculate the HMA in just three lines of code, corresponding to the three equations we showed above.
def calcHullMA(price: pd.Series, N=50): SMA1 = price.rolling(N).mean() SMA2 = price.rolling(int(N/2)).mean() return (2 * SMA2 - SMA1).rolling(int(np.sqrt(N))).mean()
We have our two moving averages, take the difference, and then smooth out the results with a third moving average. This function assumes we’re working with a Pandas data series and takes advantage of many of the methods that enables. Just be careful not to pass it a list or a NumPy array!
Getting Some Data
Let’s illustrate how this works on some historical data. I’m just getting a year’s worth from a common stock, DAL.
ticker = 'DAL' start = '2014-01-01' end = '2015-01-01' yfObj = yf.Ticker(ticker) data = yfObj.history(start=start, end=end) data.drop(['Open', 'High', 'Low', 'Volume', 'Dividends', 'Stock Splits'], axis=1, inplace=True) # Applying our function N = 50 data[f'HMA_{N}'] = calcHullMA(data['Close'], N)
Take a look to see how it behaves:
plt.figure(figsize=(12, 8)) plt.plot(data['Close'], label='Close') plt.plot(data[f'HMA_{N}'], label='HMA') plt.xlabel('Date') plt.ylabel('Price ($)') plt.title(f'HMA and Price for {ticker}') plt.legend() plt.show()
As you can see, the HMA follows pretty closely. Of course, there is a lag as can be seen with some of the larger peaks and valleys over this time frame. Does it smooth well and with a lower lag than other moving averages as Hull intends?
To find out, let’s compare it to a typical, simple moving average and an exponential moving average (EMA). Like the HMA, the EMA is designed to be more responsive to recent price changes.
The code for the EMA calculation below was taken from a previous post you can dive into for further details.
def _calcEMA(P, last_ema, N): return (P - last_ema) * (2 / (N + 1)) + last_ema def calcEMA(data: pd.DataFrame, N: int, key: str = 'Close'): # Initialize series sma = data[key].rolling(N).mean() ema = np.zeros(len(data)) + np.nan for i, _row in enumerate(data.iterrows()): row = _row[1] if np.isnan(ema[i-1]): ema[i] = sma[i] else: ema[i] = _calcEMA(row[key], ema[i-1], N) return ema
Plotting the results:
data[f'EMA_{N}'] = calcEMA(data, N) data[f'SMA_{N}'] = data['Close'].rolling(N).mean() plt.figure(figsize=(12, 8)) plt.plot(data['Close'], label='Close', linewidth=0.5) plt.plot(data[f'HMA_{N}'], label='HMA') plt.plot(data[f'EMA_{N}'], label='EMA') plt.plot(data[f'SMA_{N}'], label='SMA') plt.xlabel('Date') plt.ylabel('Price ($)') plt.title('Comparing 50-Day Moving Averages to Price') plt.legend() plt.show()
The plot looks pretty good. The HMA seems to track the price more closely than the other indicators while providing some good smoothing. However, we aren’t technical traders here at Raposa, so we need to do more than just look at a chart. We want to see the data!
To get an idea for the tracking error, we’re going to use the root mean square error (RMSE) to measure the difference between the indicator value and the price.
The RMSE is a common error metric that punishes deviations by squaring the error term. This means an error of 2 is 4 times greater than an error of 1! These squared errors all get summed up and then we take the square root of the values divided by the number of observations, n.RMSE = \sqrt{\frac{\sum_t \big(\hat{P}_t - P_t \big)^2}{n}}
We’ll run our errors through a quick RMSE function we’ll write and see the results.
# Calculate tracking error def calcRMSE(price, indicator): sq_error = np.power(indicator - price, 2).sum() n = len(indicator.dropna()) return np.sqrt(sq_error / n) hma_error = calcRMSE(data['Close'], data[f'HMA_{N}']) ema_error = calcRMSE(data['Close'], data[f'EMA_{N}']) sma_error = calcRMSE(data['Close'], data[f'SMA_{N}']) print('Lag Error') print(f'\tHMA = \t{hma_error:.2f}') print(f'\tEMA = \t{ema_error:.2f}') print(f'\tSMA = \t{sma_error:.2f}')
Lag Error HMA = 1.65 EMA = 1.24 SMA = 1.53
Whoa! The HMA actually has greater error vs the price it’s tracking than the EMA and the SMA. This seems to cut against the intent of the HMA.
This is a small sample size, however, so maybe it really does have less lag than the other indicators and we just chose a bad stock and/or time frame.
Let’s test this by calculating the RMSE all of the stocks in the S&P 500 over the course of a year. Additionally, we’ll do this for different values of N to see if there’s any relationship between shorter or longer term values and the error.
Below, we have a helper function to calculate these values for us.
def calcErrors(data: pd.DataFrame, N: list): hma_error, sma_error, ema_error = [], [], [] for n in N: hma = calcHullMA(data['Close'], n) ema = pd.Series(calcEMA(data, n), index=data.index) sma = data['Close'].rolling(n).mean() hma_error.append(calcRMSE(data['Close'], hma)) ema_error.append(calcRMSE(data['Close'], ema)) sma_error.append(calcRMSE(data['Close'], sma)) return hma_error, ema_error, sma_error
The
calcErrors function takes our data and a list of time periods to calculate the HMA, EMA, and SMA. From there, we calculate the RMSE for each series versus our closing price and return lists of each.
Next, we’ll loop over all the stocks in the S&P 500 and get the data for each. We’ll pass this to our error calculation function and collect the errors for each symbol.
We’re relying on the list of stocks in Wikipedia, which doesn’t necessarily correspond to how the symbols are represented in
yfinance (e.g. Berkshire Hathaway has two classes of shares A’s and B’s, which cause issues) so we need to wrap this in a try-except statement for those edge cases. We’ll still get enough that we should be able to get a decent estimate.
# Sample 10 tickers from S&P 500 url = '' table = pd.read_html(url) df = table[0] syms = df['Symbol'] start = '2019-01-01' end = '2020-01-01' N = [5, 10, 15, 20, 30, 50, 100, 150, 200] for i, s in enumerate(syms): try: yfObj = yf.Ticker(s) data = yfObj.history(start=start, end=end) except: continue he, ee, se = calcErrors(data, N) if i == 0: hma_error = np.array(he) ema_error = np.array(ee) sma_error = np.array(se) else: hma_error = np.vstack([hma_error, he]) ema_error = np.vstack([ema_error, ee]) sma_error = np.vstack([sma_error, se]) # Drop rows with missing values hma_error = hma_error[~np.isnan(hma_error).any(axis=1)] ema_error = ema_error[~np.isnan(ema_error).any(axis=1)] sma_error = sma_error[~np.isnan(sma_error).any(axis=1)]
After a few minutes, we can take a look at the mean tracking error across all of our metrics and tickers below:
Here we see that the HMA does track the price much better than other moving average measurements. There’s much less difference in short-time frames, but the values do start to diverge from one another fairly quickly and become more pronounced over time.
Trading with the Hull Moving Average
We could be more rigorous by tracking the deviation of our error measurements and getting more data, however for most purposes, it does seem as if the HMA does deliver on its promise to reducing lag. How do you trade it though?
The nice thing about the HMA, is that you can use it anywhere you’d use a moving average of any variety. You could build a whole new strategy around it, or just plug it into an existing system to see if you get any boost in your results.
We make all of that as easy as possible at Raposa, where we’re building a platform to allow you to backtest your ideas in seconds, without writing a single line of code. You can check out our free demo here!
One thought on “How To Reduce Lag In A Moving Average” | https://raposa.trade/how-o-reduce-lag-in-moving-average/ | CC-MAIN-2021-49 | refinedweb | 1,823 | 66.64 |
killroy 0 Posted April 30, 2004 Share Posted April 30, 2004 (edited) Hi all, Just started using AutoIt today, damn what a fine program this is. Many thanks for your time and efforts put into this project! I started to write a small executable which allows users to map a drive with a nice front GUI. I was wondering if someone could look over it and see how I could optimise it, see what types of errors I am doing and such likes. It is fairly simple. I am unsure of the error functions "Username is empty" etc I don't know if you can have an If Else function like this . If blah = 0 & bleh = 0 then code end if Here is the code. I look forward to your responses. expandcollapse popupGUICreate("KC Login",220,140,10,10) GuiSetControl("label", "Username:", 5, 15, 50) GuiSetControl("label", "Password:", 5, 35, 50) $username = GuiSetControl("input", "", 60, 13, 150,17) $password = GuiSetControl("input", "", 60, 33, 150,17) $submit = GuiSetControl("button", "Login", 60, 53, 150,23) $userdrive = GuiSetControl("checkbox", "Map User Drive", 60, 82, 150,23) GUISetControlEx($userdrive,1) $commondrive =GuiSetControl("checkbox", "Map Commons Drive", 60, 102, 150,23) $userdriveletter = GUISetControl("combo", "my combo", 5,80,45) GUISetControlData(-1,"M:|N:|O:","M:") $commondriveletter = GUISetControl("combo", "my combo", 5,100,45) GUISetControlData(-1,"X:|Y:|Z:","X:") GUIWaitClose() if $submit = GuiRead () then if GuiRead($username) = "" then msgbox(0,"Warning","Username is empty") run("login.exe") exit elseif GuiRead($password) = "" then msgbox(0,"Warning","Password is empty") run("login.exe") exit endif if GuiRead($userdrive) = 1 then ;Run("net use " & GuiRead($userdriveletter) & " \\192.168.2.2\c$","",@SW_HIDE); Test snippet ignore please. $i = 1 While $i <= 6 $var = "server" & $i $i = $i + 1 Run("net use " & GuiRead($userdriveletter) & " \\" & $var & "\" & GuiRead($username) & " " & GuiRead($password) & " /USER:BCSDNET\" & GuiRead($username) & "","",@SW_HIDE) WEnd sleep(500) Run("explorer " & GuiRead($userdriveletter) & "") endif if GuiRead($commondrive) = 1 then Run("net use " & GuiRead($commondriveletter) & " \\192.168.2.2\d$","",@SW_HIDE) sleep(500) Run("explorer " & GuiRead($commondriveletter) & "") endif endif Many thanks Edited April 30, 2004 by killroy Link to post Share on other sites
Recommended Posts
You need to be a member in order to leave a comment
Sign up for a new account in our community. It's easy!Register a new account
Already have an account? Sign in here.Sign In Now | https://www.autoitscript.com/forum/topic/2279-optimise-or-something/ | CC-MAIN-2021-31 | refinedweb | 391 | 52.8 |
Badger::Factory - base class factory module
This module is designed to be subclassed to create factory classes that automatically load modules and instantiate objects on demand.
package My::Widgets; use base 'Badger::Factory'; # tell the base class factory what we create our $ITEM = 'widget'; our $ITEMS = 'widgets'; # define module search path for widgets our $WIDGET_PATH = ['My::Widget', 'Your::Widget']; # lookup table for any non-standard spellings/capitalisations/paths our $WIDGETS = { url => 'My::Widget::URL', # non-standard capitalisation color => 'My::Widget::Colour', # different spelling amp => 'Nigels::Amplifier', # different path };
You can then use it like this:
use My::Widgets; # class methods (note: widget() is singular) $w = My::Widgets->widget( foo => { msg => 'Hello World' } ); # same as: use My::Widget::Foo; $w = My::Widget::Foo({ msg => 'Hello World' }); # add/update widgets lookup table (note: widgets() is plural) My::Widgets->widgets( extra => 'Another::Widget::Module', super => 'Golly::Gosh', ); # now load and instantiate new widget modules $w = My::Widgets->widget( extra => { msg => 'Hello Badger' } );
You can also create factory objects:
my $factory = My::Widgets->new( widget_path => ['His::Widget', 'Her::Widget'], widgets => { extra => 'Another::Widget::Module', super => 'Golly::Gosh', } ); $w = $factory->widget( foo => { msg => 'Hello World' } );
The Badger::Factory::Class module can be used to simplify the process of defining factory subclasses.
package My::Widgets; use Badger::Factory::Class item => 'widget', path => 'My::Widget Your::Widget'; widgets => { extra => 'Another::Widget::Module', super => 'Golly::Gosh', };
This module implements a base class factory object for loading modules and instantiating objects on demand. It originated in the Template::Plugins module, evolved over time in various directions for other projects, and was eventually pulled back into line to become
Badger::Factory.
The
Badger::Factory module isn't designed to be used by itself. Rather it should be used as a base class for your own factory modules. For example, suppose you have a project which has lots of
My::Widget::* modules. You can define a factory for them like so:
package My::Widgets; use base 'Badger::Factory'; our $ITEM = 'widget'; our $ITEMS = 'widgets'; our $WIDGET_PATH = ['My::Widget', 'Your::Widget']; our $WIDGET_DEFAULT = 'foo'; our $WIDGET_NAMES = { html => 'HTML', }; # lookup table for any non-standard spellings/capitalisations/paths our $WIDGETS = { url => 'My::Widget::URL', # non-standard capitalisation color => 'My::Widget::Colour', # different spelling amp => 'Nigels::Amplifier', # different path }; 1;
The
$ITEM and
$ITEMS package variables are used to define the singular and plural names of the items that the factory is responsible for. In this particular case, the
$ITEMS declaration isn't strictly necessary because the module would correctly "guess" the plural name
widgets from the singular
widget defined in
$ITEM. However, this is only provided as a convenience for those English words that pluralise regularly and shouldn't be relied upon to work all the time. See the pluralise() method in Badger::Utils for further information, and explicitly specify the plural in
$ITEMS if you're in any doubt.
The
$WIDGET_PATH is used to define one or more base module names under which your widgets are located. The name of this variable is derived from the upper case item name in
$ITEM with
_PATH appended. In this example, the factory will look for the
Foo::Bar module as either
My::Widget::Foo::Bar or
Your::Widget::Foo::Bar.
The
$WIDGET_DEFAULT specifies the default item name to use if a request is made for a module using an undefined or false name. If you don't specify any value for a default then it uses the literal string
default. Adding a
default entry to your
$WIDGET_NAMES or
$WIDGETS will have the same effect.
The
$WIDGET_NAMES is used to define any additional name mappings. This is usually required to handle alternate spellings or unusual capitalisations that the default name mapping algorithm would get wrong. For example, a request for an
html widget would look for
My::Widget::Html or
Your::Widget::Html. Adding a
$WIDGET_MAP entry mapping
html to
HTML will instead send it looking for
My::Widget::HTML or
Your::Widget::HTML.
If you've got any widgets that aren't located in one of these locations, or if you want to provide some aliases to particular widgets then you can define them in the
$WIDGETS package variable. The name of this variable is the upper case conversion of the value defined in the
$ITEMS package variable.
Now that you've define a factory module you can use it like this.
use My::Widgets; my $widgets = My::Widgets->new; my $foo_bar = $widgets->widget('Foo::Bar');
The
widget() method is provided to load a widget module and instantiate a widget object.
The above example is equivalent to:
use My::Widget::Foo::Bar; my $foo_bar = My::Widget::Foo::Bar->new;
Although it's not strictly equivalent because the factory could just has easily have loaded it from
Your::Widget::Foo::Bar in the case that
My::Widget::Foo::Bar doesn't exist.
You can specify additional arguments that will be forwarded to the object constructor method.
my $foo_bar = $widgets->widget('Foo::Bar', x => 10, y => 20);
If you've specified a
$WIDGET_DEFAULT for your factory then you can call the widget() method without any arguments to get the default object.
my $widget = $widgets->widget;
You can use the default() method to change the default module.
$widgets->default('bar');
The factory module can be customised using configuration parameters. For example, you can provide additional values for the
widget_path, or define additional widgets:
my $widgets = My::Widgets->new( widget_path => ['His::Widget', 'Her::Widget'], widgets => { extra => 'Another::Widget::Module', super => 'Golly::Gosh', } );
The factory module is an example of a prototype() module. This means that you can call the
widget() method as a class method to save yourself of explicitly creating a factory object.
my $widget = My::Widgets->widget('Foo::Bar');
Constructor method to create a new factory module.
my $widgets = My::Widgets->new;
Used to get or set the factory module path.
my $path = $widgets->path; $widgets->path(['My::Widgets', 'Your::Widgets', 'Our::Widgets']);
Calling the method with arguments replaces any existing list.
Used to get or set the names mapping table.
my $names = $widgets->names; $widgets->names({ html => 'HTML' });
Calling the method with arguments replaces any existing names table.
Used to get or set a name for the default item name. The default value is the literal string
default. This allows you to add a
default entry to either your names() or items() and it will be located automatically.
Used to fetch or update the lookup table for mapping names to modules.
my $items = $widgets->items; $widgets->items( foo => 'My::Plugin::Foo' );
Calling the method with arguments (named parameters or a hash reference) will add the new definitions into the existing table.
This method can also be aliased by the plural name defined in
$ITEMS in your subclass module.
$widgets->widgets;
Method to load a module and instantiate an object.
my $widget = $widgets->item('Foo');
Any additional arguments provided after the module name are forwarded to the object's
new() constructor method.
my $widget = $widgets->item( Foo => 10, 20 );
This method can also be aliased by the singular name defined in
$ITEM in your subclass module.
my $widget = $widgets->widget( Foo => 10, 20 );
The module name specified can be specified in lower case. The name is capitalised as a matter of course.
# same as Foo my $widget = $widgets->widget( foo => 10, 20 );
Multi-level names can be separated with dots rather than
::. This is in keeping with the convention used in the Template Toolkit. Each element after a dot is capitalised.
# same as Foo::Bar my $widget = $widgets->widget( 'foo.bar' => 10, 20 );
This method can be re-defined by a subclass to perform any pre-manipulation on the arguments passed to the item() method. The first argument is usually the type (i.e. name) of module requested, followed by any additional arguments for the object constructor.
my ($self, $type, @args) = @_;
The method should return them like so:
return ($type, @args);
This method is called to find and dynamically load a module if it doesn't already have an entry in the internal
items table. It iterates through each of the base paths for the factory and calls the load() method to see if the module can be found under that prefix.
This method is called to dynamically load a module. It iterates through each of the module name passed as arguments until it successfully loads one. At that point it returns the module name that was successfully loaded and ignores the remaining arguments. If none of the modules can be loaded then it returns
undef
This method is called when an item has been found, either in the internal
items lookup table, or by a call to find(). The $item argument is usually a module name that is forwarded onto found_module(). However, it can also be a reference which will be forwarded onto one of the following methods depending on its type: found_array(), found_hash(), found_scalar(), found_object() (and in theory,
found_regex(),
found_glob() and maybe others, but they're not implemented).
The result returned by the appropriate
found_XXXXX() method will then be forwarded onto the result() method. The method returns the result from the result() method.
This method is called when a requested item has been mapped to a module name. The module is loaded if necessary, then the construct() method is called to construct an object.
An entry in the
items (aka
widgets in our earlier example) table can be a reference to a list containing a module name and a separate class name.
my $widgets = My::Widgets->new( widgets => { wizbang => ['Wiz::Bang', 'Wiz::Bang::Bash'], }, );
If the
wizbang widget is requested from the
My::Widgets factory in the example above, then the found() method will call
found_array(), passing the array reference as an argument.
The module listed in the first element is loaded. The class name in the second element is then used to instantiate an object.
This method isn't implemented in the base class, but can be defined by subclasses to handle the case where a request is mapped to a hash reference.
This method isn't implemented in the base class, but can be defined by subclasses to handle the case where a request is mapped to a scalar reference.
This method isn't defined in the base class, but can be defined by subclasses to handle the case where a request is mapped to an existing object.
This method instantiates a
$class object using the arguments provided. In the base class this method simply calls:
$class->new(@$args);
This method is called at the end of a successful request after an object has been instantiated (or perhaps re-used from an internal cache). In the base class it simply returns
$result but can be redefined in a subclass to do something more interesting.
This method performs the necessary mapping from a requested module name to its canonical form.
This method is called when the requested item is not found. The method simply throws an error using the
not_found message format. The method can be redefined in subclasses to perform additional fallback handing.
This method implements the magic to ensure that the item-specific accessor methods (e.g.
widget()/
widgets()) are generated on demand.
This implements the other bit of magic to generate the item-specific accessor methods on demand.
Andy Wardley
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Badger::Factory::Class, Badger::Codecs. | http://search.cpan.org/~abw/Badger-0.09/lib/Badger/Factory.pm | CC-MAIN-2015-48 | refinedweb | 1,906 | 50.77 |
CNNs
The Vocabulary of CNNs
What is a convolution?
A convolution is an operation of "convolving" an input matrix (input image) with a filter matrix also called kernel or just filter:
We slide the filter matrix across the input matrix and sum up all the results:
convolution operation: (left) input - 5x5 matrix + filter; (right) output - 3x3 feature map
Filter
To understand what's going on in the convolution layer in depth, the idea of a filter is crucial:
A filter will normally have a matrix form and will consist of randomly (or certainly) initialized numbers. One filter detects one specific pattern, be it edges, corners, circles, etc. We can have many different filters as well depending on the complexity of shapes we want to detect, as each of these filters will have the task of detecting a particular feature. For example, we can have an edge detector filter, a corner detector filter or a circle detector filter and so on.
One of the key concepts behind CNN is that filters are parameters that can be learned over time. So, the model learns to distinguish between diverse shapes in the image as it changes the parameters of its filters in a way that it suites the ideal output.
Note: sometimes filter is called kernel or convolutional matrix. All these terms can be used interchangeably.
Types of Filters
Normally in CNNs you can always train (learn) your own filter which will suite exactly to your type of task. But you can also choose filters which are predefined. Let's look at a short introduction to some edge detection filters:
Sobel Filter
This type of filter is based on gradient calculation. From the original image the filter computes the first order derivatives for x and y axes respectively. As image data is not continuous data, those derivatives we get are only approximations. In order to be able to approximate the derivatives, we use the Sobel filter.
The Sobel filter consists of two filters: one filter detects horizontal edges and the other vertical ones.
detects horizontal edges
detects vertical edges
The "horizontal" filter finds the derivative along the x-axis and the "vertical" filter finds it for the y-axis.
Laplace Filter
Another edge detection filter which unlike the Sobel applies only one filter. The core concept of this filter is that it computes second order derivatives in one pass. It basically approximates the Laplace operator (or discrete Laplacian) which is the sum of both second order partial derivatives:
In the sense of the Laplace filter we see an edge as a curve. The gradient along this curve is always pointing in the direction of the normal. A normal is a vector which is always perpendicular to the surface.
Second order derivative filters are noise-sensitive. You should reduce noise in the input image first and then apply the Laplace filter. It is possible to reduce noise by some smoothing filter like, for example, a Gaussian filter . After applying the smoothing filter we can use the Laplace filter. It is also possible to combine the smoothing filter and Laplace filter into a single filter and use it as a whole.
Stride
The step with which we shift the filter is called stride. This is principally the number of pixels we move the filter across the input matrix. If stride = 1 then we make one step per computation (e.g. see pic "convolution operation" above), if stride = 2, we take two steps. The bigger the steps, the more quicker computation will occur and the smaller the output will be which leads to information loss.
Padding
If we look at the picture "convolutional operation" above once more, we'll notice that the output matrix (the output image) we receive at the end is smaller than the input matrix. So if we have a 5x5 input matrix and a 3x3 filter, we'll get a 3x3 output. In general, we can describe this procedure with the following formula:
input size: m x m
filter size: f x f
output size: (m-f+1) x (m-f+1)
Every time we apply a convolutional operation, the size of the image shrinks.
In the formula above 1 stays for bias.
After applying convolution without padding we always get a smaller output image. We also ignore for the most time the pixels situated in the corners of out input image staying centered. This all results in information loss.
But what if we pad the input image with extra pixels? We add pixels around the image, creating a frame around the input image consisting of pixels with the zero value. The padding pixels are normally equal 0.
Types of padding:
Valid
If we have "valid" padding, we actually apply no padding at all. We'll have a normal output as shown in the formula above: input size - filter size + bias .
Same
Let's take an example again: we firstly pad a 5x5 input image with zeros and get a 6x6 input image afterwards. Then we apply convolution by shifting the 3x3 filter and we get a 5x5 output matrix which is exactly the size of the input matrix. This type of padding where the output size is equal to the input size is called same padding.
calculate padding:
padding: p = (f-1) / 2
if same padding is applied then the size of the output = size of the input
m+2p-f+1 = m
where m is the input size
Full
Let's say the size of our filter is 3x3 (we can shorten it as 3). Then we can pad our input image of the size 6x6 according to the formula: padding = filter size - 1. So we pad our image with the maximum of 2 zeros, in order to get output for each input when performing the convolution. The output size will be: input size + filter size - 1 .
Let's present our input image as an array of pixel values:
then we pad the image with 2 zeros on both sides:
and we get a new input image size: 10x10
Afterwards we apply a filter of the size 3x3 with stride 1:
We get the value C0 by using the following formula which represents the sliding of the filter across the image:
Let's use this formula:
Now we shift the filter further and apply the formula again:
Why Use Convolutions?
Why not just use normal fully connected layers? There are some advantages CNNs give us that fully connected neural networks don't.
Parameter Sharing
Imagine that we have a fully connected layer instead of a convolution layer. The total parameters number would explode exponentially. That means, we would have to multiply all the image sizes from all the layers together and get a huge number in the end which would lead to a massively expensive computation.
In case of a convolution layer, the number of parameters is independent of the image size. The number of parameters depends on the filter size only. If we have a filter of size 3x3x3 the number of parameters for every filter will be 3*3*3 = 27. We also add a bias for each filter 27 + 1. If we have 8 filters total, we will get 28*8 = 224 parameters for each layer totally.
While convolving through the input in a convolution layer, the layer parameters are shared. What does it mean? It means that one and the same filter is convolved over the whole input. Why is it useful? A filter helpful in one image part, might be helpful in a different image part as well for detecting certain features.
Sparsity of Connections
Every layer in a convolutional network has sparse connections. That means, every value in the output is determined by a certain small number of inputs. We don't take into account all the inputs at one computational time.
As we could see one of he major advantages of a convolution layer is: it reduces the number of parameters which also helps to speed up the computations in the training phase. Also the sparse connections help us in keeping the neural network size smaller.
Going deeper
Mathematically speaking, a convolution is an operation on two functions with the goal to generate another function that shows how the first function is changed influenced by the second.
In mathematics convolution is called cross-correlation. It's basically the same as convolution in a CNN, only with one minor detail: in cross-correlation the filter (kernel) is flipped over.
A convolutional neural network (CNN) implements a rather extended version of a neural network. Every standard CNN consists of the following layers:
- Convolution Layer
- Activation
- Pooling Layer
- Flatten Layer
- Fully Connected Layer
- Output Fully Connected Layer: application of softmax
Let's analyze each of them in depth.
1. Convolution Layer
One of the main steps in the convolution layer was already mentioned above is the convolution operation. Just to recap it: we randomly initialize some filters to determine patterns and take our initial input image. Then we convolve the input image with the initialized filter (or filters) by shifting the filter over the entire image and multiplying each value from the original image with the values from the filter, then summing everything up we get one value which is a new entry in the new output matrix.
This new output matrix is the result of convolving the input image with the filter. This matrix is called a feature map. For each shape, we want to detect with the filter, we receive a unique feature map. We then can pass this feature map output to the next layer.
Suppose we have the following input matrix:
and the following filter (=kernel):
The convolution operation would look like this:
left: input matrix + filter; right: output 3x3 feature map
Take a look at a CNN model function which demonstrates a convolution operation implementation in tensorflow:
import tensorflow as tf from tensorflow import keras def cnn_1(): input = tf.keras.layers.Input(shape=(28, 28, 1)) conv1 = tf.keras.layers.Conv2D(filters=8, kernel_size=5, strides=1, padding='same', activation='relu', use_bias=True)(input) conv2 = tf.keras.layers.Conv2D(filters=8, kernel_size=3, strides=1, padding='same', activation='relu', use_bias=True)(conv1) hidden = tf.keras.layers.Flatten()(conv2) output = tf.keras.layers.Dense(10)(hidden) # our fully connected layer # softmax will be done by setting 'from_logits' as True in 'train' function (see further code below) model = tf.keras.Model(inputs=input, outputs=output) return model
You might have noticed that we're using the 2D convolution ( tf.keras.layers.Conv2D ). That means, the filter is moved in 2 dimensions - across the x- and y-axes. In a 3D convolution for example the 3rd dimension denotes the depth, so the filter is moved across the "depth-dimension" too. Then we have x-,y- and z-axes accordingly.
2. Activation
After applying convolution, we activate the output of the convolution layer with an activation function. For a CNN architecture ReLu is often used.
Read more on activation functions here.
We can either choose an activation in the parameter specification list of a convolutional layer (when working with tf.keras.layers see the code above) or we implement it as a separate layer (when working with a Sequential model from keras.models):
def cnn_2(): model = Sequential() model.add(Conv2D(kernel_size=(5,5), out_channels=8, stride=1, padding='SAME', activation="relu")) model.add(Conv2D(kernel_size=(3,3), out_channels=8, stride=1, padding='SAME', activation="relu")) model.add(Flatten()) model.add(Dense(6272)) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) return model
3. Pooling
Pooling is useful in cases we want to downsample the input image. We basically want to reduce the size of the image to reduce the number of parameters and hence to speed up computation.
In most cases we apply the so called MaxPooling .
With MaxPooling we choose the maximum value from the "window" we apply on the feature map (the output of the convolution layer). Let's say we have a 4x4 feature map and we apply a MaxPooling filter of size 2x2 and the stride 2 on it. Then we get:
Let's extend our cnn_1 model with pooling layers:
def cnn_1_with_pooling(): input = tf.keras.layers.Input(shape=(28, 28,1)) conv1 = tf.keras.layers.Conv2D(filters=8, kernel_size=5, strides=1, padding='same', activation='relu', use_bias=True)(input) pool1 = tf.keras.layers.MaxPool2D(pool_size=2, strides=2, padding = 'same')(conv1) conv2 = tf.keras.layers.Conv2D(filters=8, kernel_size=3, strides=1, padding='same', activation='relu', use_bias=True)(pool1) pool2 = tf.keras.layers.MaxPool2D(pool_size=2, strides=2, padding = 'same')(conv2) hidden = tf.keras.layers.Flatten()(pool2) output = tf.keras.layers.Dense(10)(hidden) model = tf.keras.Model(inputs=input, outputs=output) return model
But there is also another pooling type called Average Pooling, where the average of the values in the "filter-window" is selected.
In Keras code an AveragePooling layer looks like this:
tf.keras.layers.AveragePooling2D
We can repeat the Convolution + Activation + Pooling part as long as we want.
4. Flattening
In the very end we flatten the output of the previous convolution which means we lay all levels of our multi layered image down in one single vector. We then pass this vector to the first fully connected layer. After that we pass the output of the first fully connected layer to the final output fully connected layer. We can apply multiple fully connected layers. Normally we use one or two of them.
flattening example
5. Fully Connected Layer
In the fully connected layer the network looks at the output from the previous layer which is our feature map - the result of a convolution operation. Then it looks at the number of classes we want to predict for an initial image. Then a fully connected layer tires to determine what high level features correlates with what class.
The input to a fully connected layer must be flattened, otherwise the layer won't be able to process a multi layered input. The first fully connected layer assigns necessary weights to predict labels for each input.
The fully connected output layer gives final probability for each label with the help of the softmax function.
Don't forget that we need an optimizer and a loss function for the training phase of our model. Let's combine those parameters into one function called train:
def train(x, y, model, epochs=5, batch_size=128): model.compile( optimizer = tf.keras.optimizers.RMSprop(), metrics = ['accuracy'], loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) # 'from_logits=True' allows us to get rid of softmax in the output) fitting = model.fit(x, y, batch_size=batch_size, epochs=epochs, validation_split=0.2) # loss and metric (accuracy) will also be evaluated on validation data (not trained on) return fitting
CNNs' Parameters
Let's mention parameters of a CNN one more time:
The total parameters' number in a single layer is the number of values we can learn for each filter. More parameters means more computational time will be needed. The general formula for parameter calculation is the following:
number of parameters = (filter width * filter height + bias) * number of filters
CNN for text?
We previously said that CNNs are primarily used for image classification and object recognition. But what if we apply CNN to a text? It turns out, there are some tasks in NLP we can successfully apply CNNs to.
Generally speaking, if the global understanding across the entire sequence is required and the length of the sequence is also important, you'd better use an RNN architecture (specifically LSTM) instead of CNNs.
But in what cases we might use a CNN architecture to do language processing? As we learned because of the convolution layer CNN tries to detect patterns. Patterns in the case of a text might be just some n-grams (bi-grams, three-grams, etc...) as "I love", "I hate", "I admire", "very nice", etc. CNN can also find these patterns independent of their position in the text. So, for example, if you want to perform sentiment analysis or spam detection, where you are only interested in negative patterns or typical spam word detection, you might consider using CNN for these tasks as well.
In sentiment analysis CNN might find the negation pattern, e.g. "not great", "don't like", "poorly produced", etc. If such negations are somewhere in the text and we apply a filter to all the regions of the text, the output of the convolution layer will give us a large number for that region in the text where negations appear. The negation was detected.
When applying the pooling layer after the convolution layer, we will loose information about the precise place in the text where the negation is located. Nevertheless, we still preserve information whether the negative pattern (or some other patterns) appeared in the text or not.
Concluding we can say that in case you want to find patterns that are position independet, you may use CNNs. For cases where you have to consider long term dependencies, use RNNs.
Conclusion
There are many different types of Convolutional Neural Network (CNN) in the family of neural networks. CNNs are often used in image analysis. Because the parameters of a CNN are shared across the whole network, CNNs are also called space invariant artificial neural networks. CNNs find their application in image recognition/classification, medical image analysis, recommender systems and as we said above in natural language processing.
Further recommended readings:
Neural Networks - Introduction | http://siegel.work/blog/CNNs/ | CC-MAIN-2020-34 | refinedweb | 2,915 | 54.63 |
26 April 2011 06:42 [Source: ICIS news]
By Judith Wang and Dolly Wu
SHANGHAI (ICIS)--?xml:namespace>
The country imports hundreds of thousand tonnes of polymers each month, but volumes of plastics taken in notably declined in March, while exports showed sharp year-on-year increases, according to data from China Customs. Export volumes, however, are significantly lower than imports.
It took in 3% less high density polyethylene (HDPE) in March at 357,077 tonnes, while its exports of the same product more than tripled to 21,663 tonnes, according to the data.
For linear low density polyethylene (LLDPE),
Its low density PE (LDPE) imports slumped 45% year on year to 124,136 tonnes in March, while it shipped out 151% more LDPE at 7,000 tonnes.
PP import volume also slipped, down 9% at 339,240 tonnes in March, with a corresponding sharp increase in exports at 15,478 tonnes, nearly double the March 2010 levels, according to China Customs.
“Domestic producers started to export PVC from March for better gains as export prices are higher than domestic prices,” traders said.
ICIS-Chemease assessed the export prices of carbide-based PVC at $1,100-1,110/tonne (€759-766/tonne) FOB (free on board) CMP (
Meanwhile, in the polyester chain,
For most other petrochemical products, however,
The country imported 533,203 tonnes of methanol last month, representing a 20% increase compared to the same period in 2010, while its paraxylene (PX) imports jumped 29% to 440,768 tonnes. It also took in significantly higher volumes of mixed xylenes (MX) in March at 9,773 tonnes.
Base oils imports, meanwhile, were up 14% year on year to 262,244 tonnes, while its naphtha imports jumped 36% year on year to 300,764 tonnes, according to customs data.
( | http://www.icis.com/Articles/2011/04/26/9454786/china-march-polymer-imports-fall-exports-rise-on-high-prices.html | CC-MAIN-2014-41 | refinedweb | 298 | 60.58 |
Google Cloud Platform
Serving real-time scikit-learn and XGBoost predictions
We’re excited to bring support for scikit-learn and XGBoost, machine learning libraries, to Google Cloud Platform and partner with a growing community of data scientists and ML users.
If you’ve built machine learning models with scikit-learn or XGBoost, and you want to serve your models in real time for an application, perhaps managing the resulting infrastructure sounds like a nightmare. Fortunately, now there’s an alternative. Serving your trained scikit-learn and XGBoost models on Cloud Machine Learning Engine (ML Engine) is now in beta.
You can now upload a model you’ve already trained onto Google Cloud Storage and use ML Engine’s online prediction service to support scalable prediction requests against your trained model.
In this post we’ll cover how to use a trained scikit-learn or XGBoost model on ML Engine to make online predictions. You can find the complete guides in our documentation with a sample model and dataset. If this is your first time using Google Cloud Platform (GCP), or you need help training a scikit-learn or XGBoost model, we suggest you follow one of the complete guides for scikit-learn or XGBoost.
How to bring your model to ML EngineGetting your model ready for predictions can be done in 5 steps:
- Save your model to a file
- Upload the saved model to Google Cloud Storage
- Create a model resource on ML Engine
- Create a model version (linking your scikit-learn/XGBoost model)
- Make an online prediction
SetupThese environment variables will be needed for the following steps:
PROJECT_ID: Use the unique identifier that matches your GCP project
MODEL_PATH: The path to your model on Google Cloud Storage
MODEL_NAME: Use your own model name, such as ‘
census’
VERSION_NAME: Use your own version, such as ‘
v1’
REGION: Select a region here or use the default ‘
us-central1’. The region is where the model will be deployed.
INPUT_DATA_FILE: Include a JSON file that contains the data used as input to your model’s predict method.
(For more info see the complete guide.)
$ PROJECT_ID=your-project-id
$ MODEL_PATH=gs://models/census
$ MODEL_NAME=census
$ VERSION_NAME=v1
$ REGION=us-central1
$ INPUT_DATA_FILE=data.json
1. Save your modelFirst, you’ll need to save your model and put it in a format that is usable by Cloud ML Engine.
If you're using scikit-learn, you can save the model by adding the following code to the end of your file after your model is trained. This uses scikit-learn's built-in version of
joblib.
Language: Python
from sklearn import joblib
joblib.dump(model, ‘model.joblib’)
Language: Python
import xgboost as xgb
bst.save_model('./model.bst')
2. Upload the saved modelTo use your model with ML Engine, you’ll need to upload it to Google Cloud Storage. This step takes your local
model.joblibor
model.bstfile and uploads it to Cloud Storage via the Cloud SDK using
gsutil.
scikit-learn
gsutil cp ./model.joblib $MODEL_PATH/model.joblib
XGBoost
gsutil cp ./model.bst $MODEL_PATH/model.bst
3. Create a model resourceCloud ML Engine organizes your trained models using model and version resources. A Cloud ML Engine model is a container for the versions of your machine learning model. More information on model resources and model versions can be found in our documentation.
In this step you’ll create a container that can hold several different versions of your actual model.
gcloud ml-engine models create $MODEL_NAME --regions $REGION
4. Create a model versionNow it’s time to get a version of your model uploaded to your container that was created in the previous step. This will allow you to make online predictions. The model version requires a few components as specified here.
name: The name specified for the version when it was created. This will be the
VERSION_NAMEvariable you declared above.
deploymentUri: The Google Cloud Storage location of the trained model used to create the version. This is the bucket where you uploaded the model with your
MODEL_PATH.
runtimeVersion: The Cloud ML Engine runtime version to use for this deployment. This is set to 1.4.
framework: This specifies whether you’re using
SCIKIT_LEARNor
XGBOOST. This is set to
SCIKIT_LEARN.
pythonVersion- This specifies whether you’re using Python 2.7 or Python 3.5. The default value is set to “2.7”, if you are using Python 3.5, set the value to “3.5”
curl -X POST -H “Content-Type: application/json” \
-d '{"name": "‘$VERSION_NAME’", "deploymentUri": "’$MODEL_PATH/", "runtimeVersion": "1.4", "framework": "SCIKIT_LEARN", “pythonVersion”: “2.7”}' \
-H "Authorization: Bearer `gcloud auth print-access-token`" \
Note: It can take several minutes before your model becomes available.
You can check the status of your model’s deployment with:
gcloud ml-engine versions list --model $MODEL_NAME
Before you begin, you’ll need data you can send to your model in order to generate a prediction. Prepare a JSON file with the input data you want to use to make a prediction based on your model’s expected input. This file’s name should match the one you used above for the INPUT_DATA_FILE variable. (If you’re not sure what this looks like, check out the complete guide for more info.)
gcloud
gcloud ml-engine predict --model $MODEL_NAME \
--version $VERSION_NAME \
--json-instances $INPUT_DATA_FILE | https://cloud.google.com/blog/products/gcp/serving-real-time-scikit-learn-and-xgboost-predictions | CC-MAIN-2019-26 | refinedweb | 883 | 55.74 |
Hi,
I was trying to write a function to concat all the elements in a vector<string> into single string. I was trying to use the stl for_each algorithm and using its return type as the concatenated string. I was told that for_each has the same return type as the function provided to it, so why does this not compile ? and how do I get it to work ?
Thank you!Thank you!Code:#include<iostream> #include<vector> #include<algorithm> #include<string> using namespace std; string concat(string& s); int main() { vector<string> u(10, "Hello"); string v; v.reserve(1024); v = for_each(u.begin(),u.end(),concat); cout << v << endl; return 0; } string concat(string& s) { static string str; str += s; return str; } | http://cboard.cprogramming.com/cplusplus-programming/119083-stl-for_each-return-type.html | CC-MAIN-2015-06 | refinedweb | 123 | 64.81 |
blog class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__ – assign an object of the right type to the field
in question. This example updates the
blog attribute of an
Entry
instance
entry, assuming appropriate instances of
Entry and
are already saved to the database (so we can retrieve them below):
>>> from blog.models import Blog,)
To add multiple records to a
ManyToManyField in one
go, include multiple arguments in the call to
add(), like this:
>>> john = Author.objects.create(name="John") >>> paul = Author.objects.create(name="Paul") >>> george = Author.objects.create(name="George") >>> ringo = Author.objects.create(name="Ringo") >>> entry.authors.add(john, paul, george, ringo)
Django will complain if you try to assign or add an object of the wrong type.
Retrieving objects¶
To retrieve objects from your database, construct a
QuerySet via a
Manager on your model class.
A
QuerySet represents a collection of objects
from your database. It can have zero, one or many filters. Filters narrow
down the query results based on.
Retrieving specific objects with filters¶
The
QuerySet returned by
all()containing objects that match the given lookup parameters.
exclude(**kwargs)
- Returns a new
QuerySetcontaining)
With the default manager class, it is the same as:
Entry.objects.all().filter(pub_date__year=2006)
Chaining filters¶
The result of refining a
QuerySet is itself a
QuerySet, so it’s possible to chain
refinements together. For example:
>>> Entry.objects.filter( ... headline__startswith='What' ... ).exclude( ... pub_date__gte=datetime.date.today() ... ).filter( ... pub_date__gte=datetime.date(2005, 1, 30) ... )
This takes the initial
QuerySet of all entries
in the database, adds a filter, then an exclusion, then another filter. The
final result is a
QuerySet containing all
entries with a headline that starts with “What”, that were published between
January 30,.date.today()) >>> q3 = q1.filter(pub_date__gte=datetime.date.today())
These three
QuerySets are separate. The first is a base
QuerySet containing all entries that contain a
headline starting with “What”. The second is a subset of the first, with an
additional criteria that excludes records whose
pub_date is today or in the
future. The third is a subset of the first, with an additional criteria that
selects only the records whose
pub_date is today or in the future.]
Further filtering or ordering of a sliced queryset is prohibited due to the ambiguous nature of how that might work.
To retrieve a single object rather than a list
(e.g.
SELECT foo FROM bar LIMIT 1), use anlook
Django offers a powerful and intuitive way to “follow” relationships in
lookups, taking care of the SQL
JOINs for you automatically, behind the
scenes. To span a relationship, use the field name of related fields
across models, separated by double underscores, until you get to the field you
want.
This example retrieves all
Entry objects with a
Blog whose
name
is
'Beatles Blog':
>>> Entry.objects.filter(blog__name='Beatles Blog')
This spanning can be as deep as you’d like.
It works backwards, too. While it
can be customized, by default you refer to a “reverse”
relationship in a lookup using
Entry relationship
(
Blog to
Entry is a one-to-many relation). We might be interested in
finding blogs that have an entry(number_of_comments__gt=F('number(number_of_comments__gt=F('number_of_pingbacks') * 2)
To find all the entries where the rating of the entry is less than the sum of the pingback count and comment count, we would issue the query:
>>> Entry.objects.filter(rating__lt=F('number_of_comments') + F('numberxor(),
.bitrightshift(), and
.bitleftshift(). For example:
>>> F('somefield').bitand(16)
Oracle
Oracle doesn’t support bitwise XOR operation.
Expressions can reference transforms¶
Django supports using transforms in expressions.
For example, to find all
Entry objects published in the same year as they
were last modified:
>>> Entry.objects.filter(pub_date__year=F('mod_date__year'))
To find the earliest year an entry was published, we can issue the query:
>>> Entry.objects.aggregate(first_published_year=Min('pub_date__year'))
This example finds the value of the highest rated entry and the total number of comments on all entries for each year:
>>> Entry.objects.values('pub_date__year').annotate( ... top_rating=Subquery( ... Entry.objects.filter( ... pub_date__year=OuterRef('pub_date__year'), ... ).order_by('-rating').values('rating')[:1] ... ), ... total_comments=Sum('number_of_comments'), ... )
statement, the percent sign signifies a multiple-character wildcard and the
underscore signifies a single-character wildcard.)
This means things should work intuitively, so the abstraction doesn’t leak. For example, to retrieve all the entries that contain a percent sign, cache and returns the results
that have been explicitly requested (e.g., the next element, if the
QuerySet is being iterated over)., save the
QuerySet and
reuse it:
>>> querys.
Querying
JSONField¶
Lookups implementation is different in
JSONField,
mainly due to the existence of key transformations. To demonstrate, we will use
the following example model:
from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = models.JSONField(null=True) def __str__(self): return self.name
Storing and querying for
None¶
As with other fields, storing
None as the field’s value will store it as
SQL
NULL. While not recommended, it is possible to store JSON scalar
null instead of SQL
NULL by using
Value('null').
Whichever of the values is stored, when retrieved from the database, the Python
representation of the JSON scalar
null is the same as SQL
NULL, i.e.
None. Therefore, it can be hard to distinguish between them.
This only applies to
None as the top-level value of the field. If
None
is inside a
list or
dict, it will always be interpreted
as JSON
null.
When querying,
None value will always be interpreted as JSON
null. To
query for SQL
NULL, use
isnull:
>>> Dog.objects.create(name='Max', data=None) # SQL NULL. <Dog: Max> >>> Dog.objects.create(name='Archie', data=Value('null')) # JSON null. <Dog: Archie> >>> Dog.objects.filter(data=None) <QuerySet [<Dog: Archie>]> >>> Dog.objects.filter(data=Value('null')) <QuerySet [<Dog: Archie>]> >>> Dog.objects.filter(data__isnull=True) <QuerySet [<Dog: Max>]> >>> Dog.objects.filter(data__isnull=False) <QuerySet [<Dog: Archie>]>
Unless you are sure you wish to work with SQL
NULL values, consider setting
null=False and providing a suitable default for empty values, such as
default=dict.
Note
Storing JSON scalar
null does not violate
null=False.
Key, index, and path transforms¶
To query based on a given dictionary key, use that key as the lookup name:
>>> Dog.objects.create(name='Rufus', data={ ... 'breed': 'labrador', ... 'owner': { ... 'name': 'Bob', ... 'other_pets': [{ ... 'name': 'Fishy', ... }], ... }, ... }) <Dog: Rufus> >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': None}) <Dog: Meg> >>> Dog.objects.filter(data__breed='collie') <QuerySet [<Dog: Meg>]>
Multiple keys can be chained together to form a path lookup:
>>> Dog.objects.filter(data__owner__name='Bob') <QuerySet [<Dog: Rufus>]>
If the key is an integer, it will be interpreted as an index transform in an array:
>>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy') <QuerySet [<Dog: Rufus>]>
If the key you wish to query by clashes with the name of another lookup, use
the
contains lookup instead.
To query for missing keys, use the
isnull lookup:
>>> Dog.objects.create(name='Shep', data={'breed': 'collie'}) <Dog: Shep> >>> Dog.objects.filter(data__owner__isnull=True) <QuerySet [<Dog: Shep>]>
Note
The lookup examples given above implicitly use the
exact lookup.
Key, index, and path transforms can also be chained with:
icontains,
endswith,
iendswith,
iexact,
regex,
iregex,
startswith,
istartswith,
lt,
lte,
gt, and
gte, as well as with Containment and key lookups.
Note
Due to the way in which key-path queries work,
exclude() and
filter() are not guaranteed to
produce exhaustive sets. If you want to include objects that do not have
the path, add the
isnull lookup.
Warning
Since any string could be a key in a JSON object, any lookup other than those listed below will be interpreted as a key lookup. No errors are raised. Be extra careful for typing mistakes, and always check your queries work as you intend.
MariaDB and Oracle users
Using
order_by() on key, index, or
path transforms will sort the objects using the string representation of
the values. This is because MariaDB and Oracle Database do not provide a
function that converts JSON values into their equivalent SQL values.
Oracle users
On Oracle Database, using
None as the lookup value in an
exclude() query will return objects
that do not have
null as the value at the given path, including objects
that do not have the path. On other database backends, the query will
return objects that have the path and the value is not
null.
PostgreSQL users
On PostgreSQL, if only one key or index is used, the SQL operator
-> is
used. If multiple operators are used then the
#> operator is used.
Containment and key lookups¶
contains¶
The
contains lookup is overridden on
JSONField. The returned
objects are those where the given
dict of key-value pairs are all
contained in the top-level of the field. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'}) <Dog: Rufus> >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) <Dog: Meg> >>> Dog.objects.create(name='Fred', data={}) <Dog: Fred> >>> Dog.objects.filter(data__contains={'owner': 'Bob'}) <QuerySet [<Dog: Rufus>, <Dog: Meg>]> >>> Dog.objects.filter(data__contains={'breed': 'collie'}) <QuerySet [<Dog: Meg>]>
Oracle and SQLite
contains is not supported on Oracle and SQLite.
contained_by¶
This is the inverse of the
contains lookup - the
objects returned will be those where the key-value pairs on the object are a
subset of those in the value passed. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'}) <Dog: Rufus> >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) <Dog: Meg> >>> Dog.objects.create(name='Fred', data={}) <Dog: Fred> >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'}) <QuerySet [<Dog: Meg>, <Dog: Fred>]> >>> Dog.objects.filter(data__contained_by={'breed': 'collie'}) <QuerySet [<Dog: Fred>]>
Oracle and SQLite
contained_by is not supported on Oracle and SQLite.
has_key¶
Returns objects where the given key is in the top-level of the data. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'}) <Dog: Rufus> >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) <Dog: Meg> >>> Dog.objects.filter(data__has_key='owner') <QuerySet [<Dog: Meg>]>
has_keys¶
Returns objects where all of the given keys are in the top-level of the data. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'}) <Dog: Rufus> >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'}) <Dog: Meg> >>> Dog.objects.filter(data__has_keys=['breed', 'owner']) <QuerySet [<Dog: Meg>]>
has_any_keys¶
Returns objects where any of the given keys are in the top-level of the data. For example:
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'}) <Dog: Rufus> >>> Dog.objects.create(name='Meg', data={'owner': 'Bob'}) <Dog: Meg> >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed']) <QuerySet [<Dog: Rufus>, <Dog: Meg>]>:
from django.db.models import Q Django’s
unit tests show some possible uses of
Q.
Comparing objects¶
To compare two model instances, returns the number of objects deleted and a dictionary with
the number of deletions per object type. Example:
>>> e.delete() (1, {'blog()
This cascade behavior is customizable via the
on_delete argument to the
ForeignKey.()
Copying model instances¶
Although there is no built-in method for copying model instances, it is
possible to easily create new instance with all fields’ values copied. In the
simplest case, you can set
pk to
None and
_state.adding to
True. Using our
blog example:
blog = Blog(name='My blog', tagline='Blogging is easy') blog.save() # blog.pk == 1 blog.pk = None blog._state.adding = True, and
_state.adding to
True:
django_blog.pk = None django_blog.id = None django_blog._state.adding = True._state.adding = True._state.adding = True(number_of_pingbacks=F('number. | https://django.fun/docs/django/en/4.0/topics/db/queries/ | CC-MAIN-2022-05 | refinedweb | 1,946 | 50.94 |
Post your Comment
Growing Consumer Interest in GPS Product: Market Research
Growing Consumer Interest in GPS Product: Market Research... have discussed in some of our previous articles. In today’s world market GPS and GPS product occupy a considerable place with its growing number of uses
GPS
shoes.
Growing
Consumer Interest in GPS Product: Market... to the consumer market as a navigation technology.
What....
GPS in Cargo Tracking
Cargo Service is one the growing
Open Source GPS
to perform new research and create new applications.
GPS users employ practically...). The imported 'grey market' GPS usually have the USA basemap which is good if you...Open Source GPS
Open
Source GPSToolKit
The goal of the GPSTk
GPS Tracking and its Applications
GPS Tracking and its Applications
Introduction
GPS technology was originally developed for defense purposes and later brought to the consumer market as a navigation
Research on java
Research on java sir is it possible to create an new operating system for general purpose use. please inform me sir..
my id is sweeturajdani@gmail.com
interest rate
interest rate write a program to calculate the volume of a cube of side 5 units?
Here is a code that accepts the side of cube and find its volume.
public class VolumeOfCube {
static double volume(float l
interest and amount for three yeaers
interest and amount for three yeaers Mr.Shyam lal Agarwal invests certain sum at 5% per annum compound interest for 3 years .write a program in java to calculate :
a) the interest for the 1st year
b) the interest for the 2nd
Sources of GPS Error
Sources of GPS Error
Introduction
We have seen that the entire system of GPS is dependent on a network of 24 satellites orbiting the earth. While research and development
Consumer behavior in marketing management
In any marketing activity, consumer plays a significant role, as it is the consumer, which finally decides the output of all marketing strategy....
By definition, consumer are those who consume or buy the products on daily
Benefits of GPS Systems
consumer budgets.
The principle behind GPS is very simple- it works by providing...
Benefits of GPS Systems
Introduction
GPS or Global Positioning System was originally
How GPS Works?
capacities.
An Overview of Consumer GPS Devices
The consumer range of GPS... application that was launched in the market recently has GPS working in a PDA. The PDA...
How GPS Works?
GPS and it?s Competitors
GPS and it’s Competitors
Global Positioning System or GPS is developed and now... anywhere on the earth. By taking help of the Indian Space Research Organization (IS
Techniques to Improve GPS Accuracy
Techniques to Improve GPS Accuracy
Introduction
GPS is the best navigation and tracking... sectors like aviation. Research is on for improving the accuracy levels. Here
Benefits of GPS tracking in small enterprises
Benefits of GPS tracking in small enterprises
GPS tracking is mainly a technology to locate a particular object or person while on operation or on rest. A GPS unit is fitted
Free GPS Software
Free GPS Software
GPS Aprs Information
APRS is free GPS software for use with packet... mapping, GPS tracking, packet radio, etc. It is a VERY interesting facet
Academic Research Article Writing
Academic Research Writing
Writing for academic research is much in demand due... and student getting higher education often face problems writing their research... in academic research support.
As Academic research is a vast field where every subject Car
GPS Car
GPS... wondering whether you really know how to get to your destination? Fear no more. GPS... how to get to any destination. These products use the GPS, which relies on a host
GPS Mapping Software
GPS Mapping Software
GPS Mapping Software
This is the official web site for the OziExplorer GPS Mapping Software which runs on your PC or laptop and will work
The iPhone as a Business Phone
;
The Apple iPhone is a great consumer phone with unique... business-only phones and consumer phones. We think not. And the best proof... lack one essential feature that is very handy when travelling-maps and GPS assist
Please can I get the code for solution of producer consumer problem using semaphores?
Please can I get the code for solution of producer consumer problem using semaphores? Please can I get the code for solution of producer consumer...();
full.up();
}
}
}
class Consumer extends Thread
Content Writing Job
that the candidate have a genuine interest in making a career in copywriting/content writing.... Candidate should be to conduct online research, generate content for various websites
GPS Tracking Systems
GPS Tracking Systems
Global Positioning System usually called GPS is the satellite navigation system that functions with the help of 27 Earth orbiting GPS satellites. Out
Post your Comment | http://roseindia.net/discussion/19952-Growing-Consumer-Interest-in-GPS-Product:-Market-Research.html | CC-MAIN-2013-20 | refinedweb | 787 | 55.44 |
Tcl_AsyncCreate, Tcl_AsyncMark, Tcl_AsyncInvoke, Tcl_AsyncDelete,
Tcl_AsyncReady - handle asynchronous events
#include <tcl.h>
Tcl_AsyncHandler
Tcl_AsyncCreate(proc, clientData)
Tcl_AsyncMark(async)
int
Tcl_AsyncInvoke(interp, code)
Tcl_AsyncDelete(async)
int
Tcl_AsyncReady() com-
mand was being evaluated when
handler was invoked, or NULL
if handler was invoked when
there was no interpreter
active.
int code (in) Completion code from command
that just completed in
interp, or 0 if interp is
NULL.
_________________________________________________________________
These procedures provide a safe mechanism for dealing with asynchronous
events such as signals. If an event such as a signal occurs while a
Tcl script is being evaluated then it isn't safe to take any substan-
tive action to process the event. For example, it isn't safe to evalu-
ate
occurs the code that detects the event (such as a signal handler)
should call Tcl_AsyncMark with the token for the handler. Tcl_Async-
Mark com-
mand.
asynchronous event, handler, signal
Tcl 7.0 Tcl_AsyncCreate(3) | http://www.syzdek.net/~syzdek/docs/man/.shtml/man3/Tcl_AsyncReady.3.html | crawl-003 | refinedweb | 152 | 61.77 |
Serverless Computing, Hands on with AWS-Lambda
Introduction
In last few decades, we are continuously looking at the innovation happening in the area of Cloud Computing. After the launch of EC2 by AWS in 2006 more or less, Infrastructure as a code concept starts shining and it was the best thing happened at that time using which one can easily create, provision and orchestrate VMs using simple clicks via browser or via some API calls or using command line. The issue was that we still have to care about our infrastructure at the back of our head. Moving forward we got the concept of Serverless Computing. AWS introduces Lambda and it allows you to take your code and run it without any provisioning service, you don’t have to worry about the low level details regarding the computational power and such things, It also provides massive parallelization for your service to execute, So a developer just have to write the function and not to care about the handling of infrastructure related headache.
Introduction to AWS-Lambda
Introduced in the end of 2014 within the stack of AWS computing platform, Lambda is a serverless computing platform which can easily execute your function in response of any certain event and along with this, it also manages the computational resources required for the execution of that piece of code. It allows you to run your code without the provisioning or management of any machine or server. You pay only for the compute time you consume.
Writing Your First Lambda Function with Python
Here let’s write a simple Python function with AWS Lambda in order to understand its working. Well I am a student so I am using AWS student account in order to practice it. Scrolling to Lambda and click on Create function. We’ll be creating a Lambda from scratch, so select the Author from scratch option.
Setting up an application from the baseline using the configuration shown in the picture. selecting Python as runtime, name of the application and other stuff as shown.
After setting up the base line configuration, now move to setting up the test event. We will be Invoking our function via test event. First of all choosing a template that matches the service that triggers your function, or enter your event document in JSON. It is shown here as shown below.
At the next step moving to the addition of code in the AWS Portal. Here we will be adding the code for four functions (Sum, Difference, Multiply, Divide). After adding the code, we will deploy it and now we are gonna test it and check the repsonse.
import jsonprint('Loading function')def lambda_handler(event, context):
key1=event['key1']
key2=event['key2']
sum=int(key1)+int(key2)
difference=int(key1)-int(key2)
multiply=int(key1)*int(key2)
division=int(key1)/int(key2)
return sum,difference,multiply,division
Moving forward to the response, here is the response for our simple python function.
Lambda Functions Automation with Serverless Application Model (SAM) & Github Actions
Let’s have a look at using the GitHub Actions to automate serverless application deployment on AWS. we can use github actions for that, Moreover there are hundreds other options present also. One of them is using the AWS own CI/CD system.
It’s quite simple to start with, We can start with creating a basic SAM application or we can also use our pre-made configuration and then integrate it with github action in order to have an end to end automated structure.
#Step 1- Build your application
cd sam-app
sam build
#Step 2- Deploy your application
sam deploy --guided
sam deploy --guided output
To build and test the application locally one can use the command;
sam build — use-container
Run functions locally and invoke them with the sam local invoke command.
sam local invoke HelloWorldFunction — event events/event.json
sam local start-api
curl
How it will work
- As soon as a push to GitHub is detected, Action workflow will be triggered.
- The pipeline can be also triggered manually or recurrently.
- It will execute all the steps as described in the Github actions workflow yml file as shown in the figure below.
Now we will be having a look at the configuration of Github workflow action,and having a look at it. Before running it via Github action one must put AWS secret credentials inside the github secrets. Here is the github action workflow.
Seeing the Results
Here you are, completed with the deployment of an API using SAM (serverless application deployment) AWS-CLI. You can scroll to API Gateway in your AWS console and have a look by hitting the URL.
More with Serverless using AWS Lambda
Exploring the deployment of a complete Python Flask application to AWS Lambda with some external python library like Zappa. It is a library to deploy serverless web apps on AWS Lambda. In the upcoming blog post, we will be building a simple Flask web app with Python and run the web app on AWS Lambda using Zappa in only a few steps.
Happy Coding! | https://thesaadahmed.medium.com/serverless-computing-hands-on-with-aws-lambda-69480592ee9d?source=post_page-----69480592ee9d-------------------------------- | CC-MAIN-2021-25 | refinedweb | 851 | 58.92 |
I try to construct a pair from temporaries. From what I understand, std::pair provides the necessary constructors, but I cannot make it work. This is my minimal example:
#include <utility>
struct Test {
Test() : a(1.0) {}
private:
double a;
Test(Test&&) = default;
Test(const Test&) = delete;
Test& operator=(Test&&) = delete;
};
int main (int argc, char** argv) {
std::pair<Test, double> result(Test(), 0.0);
}
clang++-3.8 --std=c++14
call to deleted constructor of 'Test'
My gcc (6.1.1) gives a slightly different error message, which is more helpful:
t.C:8:3: note: declared private here Test(Test&&) = default; ^~~~
Your move constructor is private. It obviously must be public. | https://codedump.io/share/AVa5n4Lfpe11/1/creating-a-pair-from-temporaries | CC-MAIN-2016-50 | refinedweb | 113 | 68.16 |
![if gte IE 9]><![endif]>
Hi people, now I have a big problem... I need create a report with many items (thats not is the problem), on a format documents...
I want to know if exist the way to create this report on .doc o .xls...
this report isn't a 'normal' report because this report look just like a report made it with report builder, but a work with character mode...
exist this way to create this report?
Thanks a lot.
You can use Excel COM automation or Microsoft.Office.Interop.Excel namespace to generate your report.
Please, can you tell me if this COM exist inside of Progress OpenEdge character mode, and tell me how can use this COM in my report?
I'm not so sure about that. If your character client runs on Windows, you can try. I'm not seeing a documentation about COM automation only available in GUI.
hExcel, hWorkSheet are COM-HANDLE.
Here are fundamental parts;
CREATE "excel.application" hExcel NO-ERROR.
hWorkSheet = hExcel:Sheets:Item(1).
hWorkSheet:Range("A:1"):Text = "SomeText".
thanks man... I see it to, but just works with GUI system... I try with another idea, If works I comment my solution...
IF WORKS!!!!...
It seems to work on Character Client running on Windows OS.
NOTE: This process requires installing Microsoft Office.
COM certainly works in the Windows Character client as well.
Here are a few sample bits:
On other platforms you may want to look into Alon Blichs "Word and Excel Utils". He basically directly creates xlsx files from the ABL.
You can download a trial - but the Word and Excel Utils are a commercial product.
Check out ... that will work on any platform, including Unix servers.
Consulting in Model-Based Development, Transformation, and Object-Oriented Best Practice
This is promising. I have some questions.
Does it support importing xlsx document on UNIX?
Can I assume that if using OpenOffice in UNIX, I also need the X-Windows or KDE Desktop installed?
If I'm not going to view documents in UNIX just generate document, are there any other requirements aside from the r-code?
It supports only XLSX (no XLS) and requires no openoffice unless you want to convert docx to pdf or somesuch. If you're just generating documents, like we are on centOS Linux, you just need to add the libraries to your propath.
We are paid users for the libooxml, but you can definitely test for free. To give you a headstart here's my template for generating XLSX from tt:
{slibooxml/slibxlsx.i}
{slib/slibos.i}
/* {slib/sliberr.i} -- sliberr is more for GUI - I disable error handling as these are all automated routines */
def var filename# as char no-undo.
assign
filename# = "./output/xx.xlsx".
os-delete value (filename#) no-error.
/* generate your tt here */
run xlsx_createTemplate(
input "stXlsx", /* stream */
input "./excel/replace_basic.xlsx", /* blank file */
input temp-table tt:handle, /* dataset handle or temp-table handle or query handle or buffer handle */
input "", /* buffer can-do list */
input "" ). /* field can-do list */
run xlsx_replaceLongRange(
input "stXlsx",
input temp-table tt:handle,
input "",
input "" ).
run xlsx_save(
input filename# ).
Can you also use the library to load and read XLSX file for import?
no. I still use a couple of activex routines I use for that. And it's strictly windows-based.
AFAIK you cannot import XLSX or DOCX into ABL from *nix.
I do it...
I found an example... that's not my solution, but maybe can help anyone
this works only in GUI...
I work with this in the past... and works...
I will read this info... thanks a lot
I can't found the solution for this problem and the converters I can't use them... please help.
I do it... I create the report in PDF, I use text2pdf.p to create this report.
I create the report in .txt in this way.
v_dir as char.
v_dir = '/home/user_name/reports/report01.txt'.
output to value(v_dir)
find first custom_tb where custom_tb.id_cte = '58247'
and custom_tb.status_cte = 'a'
no-lock no-error.
if available custom_tb then do:
put unformatted
custom_tb.id_cte '|' skip
custom_tb.name '|' skip
custom_tb.addrs '|' skip
custom_tb '|' skip.
for each sales where sales.id_cte = custom.id_cte
and sales.date_sale >= 01/01/12
and sales.date_sale <= today
no-lock:
put unformatted
sales.date_sale '|' skip
sales.id_prod '|' skip
sales.price_sale '|' skip.
end.
end.
output close.
2nd. replace de '|' with ^ ^,later, I put this report on a format "txt", and transform this txt to .doc
3th. I use the text2pdf.p to create the report in PDF.
you need configure the way to view the report, paper size, rectangles, lines or bar, type of character, etc. an put this reprt in this way with ext. *.cfg, example doc.cfg
RUN text2pdf.p (INPUT "document.cfg",
INPUT "report", INPUT "SALES LIST", INPUT "V_DIR", INPUT "/HOME/USER_NAME/REPORT/custlist.pdf").
To download ‘ttf2pt1’ go to the following link:
I PUT THE DOC FOR TEXT2PDF
text2pdfdocumentation.pdf | https://community.progress.com/community_groups/f/27/t/79 | CC-MAIN-2018-13 | refinedweb | 833 | 70.29 |
Announcing the First Kubernetes Enterprise Training Course
July 08 2015.
Kubernetes 1.0 Launch Event at OSCON
July 02 2015
How did the Quake demo from DockerCon Work?
July 02 2015 proces.
The Distributed System ToolKit: Patterns for Composite Containers
June 29 2015
Slides: Cluster Management with Kubernetes, talk given at the University of Edinburgh
June 26 2015.
Cluster Level Logging with Kubernetes
June 11 2015
A Kubernetes cluster will typically be humming along running many system and application pods. How does the system administrator collect, manage and query the logs of the system pods? How does a user query the logs of their application which is composed of many pods which may be restarted or automatically generated by the Kubernetes system? These questions are addressed by the Kubernetes cluster level logging services.
Cluster level logging for Kubernetes allows us to collect logs which persist beyond the lifetime of the pod’s container images or the lifetime of the pod or even cluster. In this article we assume that a Kubernetes cluster has been created with cluster level logging support for sending logs to Google Cloud Logging. This is an option when creating a Google Container Engine (GKE) cluster, and is enabled by default for the open source Google Compute Engine (GCE) Kubernetes distribution. After a cluster has been created you will have a collection of system pods running that support monitoring, logging and DNS resolution for names of Kubernetes services:
$ kubectl get pods
NAME READY REASON RESTARTS AGE fluentd-cloud-logging-kubernetes-minion-0f64 1/1 Running 0 32m fluentd-cloud-logging-kubernetes-minion-27gf 1/1 Running 0 32m fluentd-cloud-logging-kubernetes-minion-pk22 1/1 Running 0 31m fluentd-cloud-logging-kubernetes-minion-20ej 1/1 Running 0 31m kube-dns-v3-pk22 3/3 Running 0 32m monitoring-heapster-v1-20ej 0/1 Running 9 32m
Here is the same information in a picture which shows how the pods might be placed on specific nodes.
Here is a close up of what is running on each node.
The first diagram shows four nodes created on a GCE cluster with the name of each VM node on a purple background. The internal and public IPs of each node are shown on gray boxes and the pods running in each node are shown in green boxes. Each pod box shows the name of the pod and the namespace it runs in, the IP address of the pod and the images which are run as part of the pod’s execution. Here we see that every node is running a fluentd-cloud-logging pod which is collecting the log output of the containers running on the same node and sending them to Google Cloud Logging. A pod which provides a cluster DNS service runs on one of the nodes and a pod which provides monitoring support runs on another node.
To help explain how cluster level logging works let’s start off with a synthetic log generator pod specification counter-pod.yaml:
apiVersion : v1 kind : Pod metadata : name : counter spec : containers : - name : count image : ubuntu:14.04 args : [bash, -c, 'for ((i = 0; ; i++)); do echo "$i: $(date)"; sleep 1; done']
This pod specification has one container which runs a bash script when the container is born. This script simply writes out the value of a counter and the date once per second and runs indefinitely. Let’s create the pod.
$ kubectl create -f counter-pod.yaml pods/counter
We can observe the running pod:
$ kubectl get pods
NAME READY REASON RESTARTS AGE counter 1/1 Running 0 5m fluentd-cloud-logging-kubernetes-minion-0f64 1/1 Running 0 55m fluentd-cloud-logging-kubernetes-minion-27gf 1/1 Running 0 55m fluentd-cloud-logging-kubernetes-minion-pk22 1/1 Running 0 55m fluentd-cloud-logging-kubernetes-minion-20ej 1/1 Running 0 55m kube-dns-v3-pk22 3/3 Running 0 55m monitoring-heapster-v1-20ej 0/1 Running 9 56m
This step may take a few minutes to download the ubuntu:14.04 image during which the pod status will be shown as Pending.
One of the nodes is now running the counter pod:
When the pod status changes to Running we can use the kubectl logs command to view the output of this counter pod.
$ kubectl logs counter 0: Tue Jun 2 21:37:31 UTC 2015 1: Tue Jun 2 21:37:32 UTC 2015 2: Tue Jun 2 21:37:33 UTC 2015 3: Tue Jun 2 21:37:34 UTC 2015 4: Tue Jun 2 21:37:35 UTC 2015 5: Tue Jun 2 21:37:36 UTC 2015
This command fetches the log text from the Docker log file for the image that is running in this container. We can connect to the running container and observe the running counter bash script.
$ kubectl exec -i counter bash ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 17976 2888 ? Ss 00:02 0:00 bash -c for ((i = 0; ; i++)); do echo "$i: $(date)"; sleep 1; done root 468 0.0 0.0 17968 2904 ? Ss 00:05 0:00 bash root 479 0.0 0.0 4348 812 ? S 00:05 0:00 sleep 1 root 480 0.0 0.0 15572 2212 ? R 00:05 0:00 ps aux
What happens if for any reason the image in this pod is killed off and then restarted by Kubernetes? Will we still see the log lines from the previous invocation of the container followed by the log lines for the started container? Or will we lose the log lines from the original container’s execution and only see the log lines for the new container? Let’s find out. First let’s stop the currently running counter.
$ kubectl stop pod counter pods/counter Now let’s restart the counter. $ kubectl create -f counter-pod.yaml pods/counter
Let’s wait for the container to restart and get the log lines again.
$ kubectl logs counter 0: Tue Jun 2 21:51:40 UTC 2015 1: Tue Jun 2 21:51:41 UTC 2015 2: Tue Jun 2 21:51:42 UTC 2015 3: Tue Jun 2 21:51:43 UTC 2015 4: Tue Jun 2 21:51:44 UTC 2015 5: Tue Jun 2 21:51:45 UTC 2015 6: Tue Jun 2 21:51:46 UTC 2015 7: Tue Jun 2 21:51:47 UTC 2015 8: Tue Jun 2 21:51:48 UTC 2015
Oh no! We’ve lost the log lines from the first invocation of the container in this pod! Ideally, we want to preserve all the log lines from each invocation of each container in the pod. Furthermore, even if the pod is restarted we would still like to preserve all the log lines that were ever emitted by the containers in the pod. But don’t fear, this is the functionality provided by cluster level logging in Kubernetes. When a cluster is created, the standard output and standard error output of each container can be ingested using a Fluentd agent running on each node into either Google Cloud Logging or into Elasticsearch and viewed with Kibana. This blog article focuses on Google Cloud Logging.
When a Kubernetes cluster is created with logging to Google Cloud Logging enabled, the system creates a pod called fluentd-cloud-logging on each node of the cluster to collect Docker container logs. These pods were shown at the start of this blog article in the response to the first get pods command.
This log collection pod has a specification which looks something like this fluentd-gcp.yaml:
apiVersion: v1 kind: Pod metadata: name: fluentd-cloud-logging spec: containers: - name: fluentd-cloud-logging image: gcr.io/google\_containers/fluentd-gcp:1.6 env: - name: FLUENTD\_ARGS value: -qq volumeMounts: - name: containers mountPath: /var/lib/docker/containers volumes: - name: containers hostPath: path: /var/lib/docker/containers
This pod specification maps the the directory on the host containing the Docker log files, /var/lib/docker/containers, to a directory inside the container which has the same path. The pod runs one image, gcr.io/google_containers/fluentd-gcp:1.6, which is configured to collect the Docker log files from the logs directory and ingest them into Google Cloud Logging. One instance of this pod runs on each node of the cluster. Kubernetes will notice if this pod fails and automatically restart it.
We can click on the Logs item under the Monitoring section of the Google Developer Console and select the logs for the counter container, which will be called kubernetes.counter_default_count. This identifies the name of the pod (counter), the namespace (default) and the name of the container (count) for which the log collection occurred. Using this name we can select just the logs for our counter container from the drop down menu:
(image-counter-new-logs.png)
When we view the logs in the Developer Console we observe the logs for both invocations of the container.
(image-screenshot-2015-06-02)
Note the first container counted to 108 and then it was terminated. When the next container image restarted the counting process resumed from 0. Similarly if we deleted the pod and restarted it we would capture the logs for all instances of the containers in the pod whenever the pod was running.
Logs ingested into Google Cloud Logging may be exported to various other destinations including Google Cloud Storage buckets and BigQuery. Use the Exports tab in the Cloud Logging console to specify where logs should be streamed to (or follow this link to the settings tab).
We could query the ingested logs from BigQuery using the SQL query which reports the counter log lines showing the newest lines first.
SELECT metadata.timestamp, structPayload.log FROM [mylogs.kubernetes_counter_default_count_20150611] ORDER BY metadata.timestamp DESC
Here is some sample output:
(image-bigquery-log-new.png)
We could also fetch the logs from Google Cloud Storage buckets to our desktop or laptop and then search them locally. The following command fetches logs for the counter pod running in a cluster which is itself in a GCE project called myproject. Only logs for the date 2015-06-11 are fetched.
$ gsutil -m cp -r gs://myproject/kubernetes.counter\_default\_count/2015/06/11 .
Now we can run queries over the ingested logs. The example below uses thejq program to extract just the log lines.
$ cat 21\:00\:00\_21\:59\:59\_S0.json | jq '.structPayload.log' "0: Thu Jun 11 21:39:38 UTC 2015\n" "1: Thu Jun 11 21:39:39 UTC 2015\n" "2: Thu Jun 11 21:39:40 UTC 2015\n" "3: Thu Jun 11 21:39:41 UTC 2015\n" "4: Thu Jun 11 21:39:42 UTC 2015\n" "5: Thu Jun 11 21:39:43 UTC 2015\n" "6: Thu Jun 11 21:39:44 UTC 2015\n" "7: Thu Jun 11 21:39:45 UTC 2015\n"
This article has touched briefly on the underlying mechanisms that support gathering cluster level logs on a Kubernetes deployment. The approach here only works for gathering the standard output and standard error output of the processes running in the pod’s containers. To gather other logs that are stored in files one can use a sidecar container to gather the required files as described at the page Collecting log files within containers with Fluentd and sending them to the Google Cloud Logging service.
Weekly Kubernetes Community Hangout Notes - May 22 2015
June 02 ‘upgrade’. | https://kubernetes.io/blog/page26/ | CC-MAIN-2018-17 | refinedweb | 1,934 | 59.33 |
To perform some tasks, we still need to trap unmanaged windows messages, even though we are developing managed code. This is a little tutorial that tries to clarify how to trap those messages using the .NET Framework.
The code is written in C#. I believe it will be quite easy for those who are reading this document, and you can use VB.NET™ instead of C#, to port the concepts.
Now, to clarify the concepts lets use something useful. Maybe some of the readers have the need to detect if a CD, or for what matters any removable volume mounted on a device which supports a software ejection method (DVD, Zip, etc…), has been inserted or removed from a device. This can be accomplished by detecting the WM_CHANGEDEVICE message.
WM_CHANGEDEVICE
There are, to my knowledge, two ways of trapping windows messages in the Microsoft .NET Framework.:
The most obvious, and I suspect the least useful, is to use the IMessageFilter interface.
IMessageFilter
The BCL defines an IMessageFilter interface, which describes a single method named PreFilterMessage, which can be used to trap Windows messages. After defining a class which implements the IMessageFilter interface, we just need to tell the Application class, that it should add it to the queue of IMessageFilter interfaces it can handle using the Application.AddMessageFilter method. We can also remove a filter using the Application.RemoveMessageFilter method from the queue. Now, this approach is only useful to trap dispatched messages, it does not handle all messages. This process is out of scope in this document, anyway, as an example example, we would have to use something like:
PreFilterMessage
Application
AddMessageFilter
RemoveMessageFilter
using System;
using System.Windows.Forms;
public class MyFilter: IMessageFilter
{
public bool PreFilterMessage(ref Message aMessage)
{
if (aMessage.Msg==WM_AMESSAGE)
{
//WM_AMESSAGE Dispatched
//Let’s do something here
//...
}
// This can be either true of false
// false enables the message to propagate to all other
// listeners
return false;
}
}
At some other point of your code you would have to register an instance of MyFilter, like:
MyFilter
// This will have to have a scope that makes it accessible to both
// AddFilter and RemoveFilter
MyFilter fFilter = new MyFilter();
(…)
Application.AddMessageFilter(fFilter);
(…)
Application.RemoveMessageFilter(fFilter);
The solution, in our example, is overriding a WndProc method of a Control or to do the same with an implementation of the NativeWindow class. The first solution is useful if we need to trap messages in a class that inherits the Control class. If we want to build a class that is not dependent on a specific Control, we will have to use the NativeWindow class. This class simply wraps a window handle, and so, it enables us to override the WndProc method which is implemented.
WndProc
Control
NativeWindow
In both cases, we will override the WndProc method like:
protected override void WndProc(ref Message aMessage)
{
if (aMessage.Msg==WM_AMESSAGE)
{
//WM_AMESSAGE Dispatched
//Let’s do something here
//...
}
}
Now, let’s look at our example. We already know that we will need to trap the WM_DEVICECHANGED message, and to filter two specific events. We will build the example based on two classes.
WM_DEVICECHANGED
The first one, _DeviceVolumeMonitor, will be private to the project, and will only serve to inherit the NativeWindow class, so that our main class won’t expose the public NativeWindow methods. This class will also serve the purpose of encapsulating all API constants and structures that we will need to make things work.
_DeviceVolumeMonitor
DeviceVolumeMonitor, will be our main class. It implements most of the logic needed to the user. Nevertheless, the main subject of this tutorial is in the other class.
DeviceVolumeMonitor
This message is broadcasted whenever something relevant occurs in a device connected to Microsoft Windows. For this matter, there are two events which we will need to trap, the DBT_DEVICEARRIVAL and the DBT_DEVICEREMOVECOMPLETE.
DBT_DEVICEARRIVAL
DBT_DEVICEREMOVECOMPLETE
Both events are handled the same way, the only difference being that DBT_DEVICEARRIVAL detects a volume being inserted, and the DBT_DEVICEREMOVECOMPLETE detects that a volume was removed. Now, we need to look at some of the Win32 API declarations to see how this works.
The WM_CHANGEDEVICE constant definition can be found in WinUser.h, all other information we will need, it can be found in DBT.h header file. Both files are part of the Microsoft Platform SDK.
When a WM_CHANGEDEVICE is broadcasted, the message structure will transport the event value in the WParam, and some additional data in a location pointed by LParam.
WParam
LParam
As I already described, we are only interested in trapping messages that have a WParam with the DBT_DEVICEARRIVAL or DBT_DEVICEREMOVALCOMPLETE values. The data pointed by LParam will have the same structure in both cases.
DBT_DEVICEREMOVALCOMPLETE
Once one of the events is detected, we must cast the pointer stored in LParam, to a _DEV_BROADCAST_HDR structure, and evaluate the dbch_devicetype field. We are only interested in proceeding if the field value is DBT_DEVTYP_VOLUME.
_DEV_BROADCAST_HDR
DBT_DEVTYP_VOLUME
If this is the case, then we will need to cast LParam again, but this time to point at a _DEV_BROADCAST_VOLUME structure. This structure has two fields which we will have to evaluate. The first one is dbcv_flags. This field will tell us the nature of the volume that was mounted (or dismounted). It can be either a media volume like a CD (the flag will have a DBTF_MEDIA flag) or a network share (DBTF_NET). In this case we will only be interested in filtering the DBTF_MEDIA value. The other field is dbcv_unitmask, which is a bit vector that tells us which drive letters were mounted.
_DEV_BROADCAST_VOLUME
dbcv_flags
DBTF_MEDIA
DBTF_NET
dbcv_unitmask
At this point, there are two facts which need to be clarified. As stated in the Platform SDK documentation, this message can tell us if more than one volume was mounted and these can be of multiple types. We will have to make an assumption that is whenever the dbcv_flags includes the DBTF_MEDIA value, we will assume that all the drives described by the dbcv_unitmask bit vector are of this type. I don’t think that it is likely that this notification will ever have a dbcv_flags that includes both types. Anyway, this would be solved if we would determine the specific type for all the drives described by dbcv_unitmask. On the other hand, as it was already implied, dbcv_unitmask can describe more than one drive at a time. I guess this is only likely if we have a jukebox device, but anyway this is a problem we will solve in the code.
This is a helper class which is internal to the project. Now as I told you before, this class is only useful to inherit the NativeWindow class and to encapsulate the API constants and structures we will use. The class constructor takes only a parameter which will be the instance of the main class that owns the _DeviceVolumeMonitor instance.
The API constants and structures were modified to become more readable and useful in the .NET context.
The WndProc is overridden according to the cascading conditions described for the WM_DEVICECHANGE message. If all conditions are fulfilled then the object uses as internal method of the main class to inform it that a valid event has occurred. This method is called TriggerEvents.
WM_DEVICECHANGE
Our main class, contains some logic, which has no relation to windows messages itself.
Now, we know that this class creates an instance of the former class, and that whenever an event is detected, it is reported back to the main class through the TriggerEvents method. This is not a clean OOP approach, but there was no point in making things more complicated.
TriggerEvents
This class has two properties defined: Enabled and AsynchronousEvents. The Enabled property is self explanatory, is handles enabling or disabling the message trapping. This is done with the helper class. When we want messages to be trapped we assign the handle to the NativeWindow descendant, and the WndProc method will be invoked whenever there is a message either broadcasted or dispatched, the handle will be released when the property is unset. This approach is better than controlling the property value in the WndProc method (the property is still evaluated on the method as a sanity check anyway), because the class won’t overload the system with unnecessary checks.
Enabled
AsynchronousEvents
AsynchronousEvents controls the way events are invoked. If it is set, then the event will be called asynchronously, and WndProc won’t stall waiting for the application to process whatever it has to. Now, the way this is done on the TriggerEvents method is not peaceful. Many of you will criticize the BeginInvoke without following the design pattern. It is an unsafe option, but still it works if it only evolves calling thread safe code. Either way, I assume that you know what you are doing if you set this property.
BeginInvoke
There is a platform invoke to an API function called QueryDosDevice. This is a function that enables the translation between the drive letter, or DOS device name, to the full device path. This is used by one of two methods which translate the bit vector that was mentioned before. MaskToLogicalPaths translates the bit vector to a comma delimited string with all the drive letters described by the bit vector, MaskToDevicePaths on the other hand returns a string which is a list of the full device paths.
QueryDosDevice
MaskToLogicalPaths
MaskToDevicePaths
Two events are defined, OnVolumeInserted and OnVolumeRemoved. Both of them take the issued bit vector as a parameter.
OnVolumeInserted
OnVolumeRemoved
Finally, I have implemented the IDisposable interface, I followed the design pattern, so there is not much to say here.
IDispos. | http://www.codeproject.com/Articles/3946/Trapping-windows-messages?fid=15152&df=90&mpp=10&sort=Position&spc=None&select=4389939&tid=2426868&noise=1&prof=True&view=Expanded | CC-MAIN-2015-35 | refinedweb | 1,595 | 61.77 |
TNX !!!;)
Uploaded with ImageShack.us
TNX !!!;)
Uploaded with ImageShack.us
weird... how come after upgrading from bt4-final to r2 i dont get the wallpaper...
Maybe you should check out the upgrade instructions on the wiki
Hi all, :) . im playing again with my USB-BK4 :) ,
but I cant find in the /usr/local/lib/python2.6/dist-packages/cpyrit/cpyrit.py :)
but I dont have this file , :confused:
for dev_idx in range(p.numDevices) to change the cors to 2 ,
must reinstall some part ? any sugestion
This howto is one of the best on the forum. Worked flawlessly for me. Only hitch was I did have to make sure to startx on the physical machine so the monitor is running in X (i have tendency to access many of my machines remotely)
Particularly this section
Code:
apt-get purge pyrit
apt-get install libboost-dev
svn checkout pyrit_svn
cd pyrit_svn/pyrit
./setup.py build
./setup.py install --record ~/pyrit.txt
I use this commands on a fresh bt4r2:
I get pyrit svn280 and enable cuda nvidia 8500gt with one CPU-coreI get pyrit svn280 and enable cuda nvidia 8500gt with one CPU-coreCode:
apt-get update
apt-get upgrade
apt-get install nvidia-driver
apt-get install cuda-toolkit
wget
chmod 755 gpucomputingsdk_3.1_linux.run
./gpucomputingsdk_3.1_linux.run
apt-get install cpyrit-cuda
apt-get update
apt-get upgrade
ufw disable
pyrit list_cores
After I write these lines:I get pyrit svn288 but I see only CPU-core without GPU.I get pyrit svn288 but I see only CPU-core without GPU.Code:
apt-get purge pyrit
apt-get install libboost-dev
svn checkout pyrit_svn
cd pyrit_svn/pyrit
./setup.py build
./setup.py install --record ~/pyrit.txt
What am I doing wrong?
Hi,
i hava ati hd5770. use it on backtrack
i have install ati driver(revision 10.12), and ati stream (version 2.3) successfully.
after installation of that, i download calpp0.87 and copy include/cal directory in my /usr/local/include/ [OK]
install pyrit 0.4-dev [OK]
now i would like to install cpyrit_calpp
and this is the result !!and this is the result !!Code:
./setup.py build
running build
running build_ext
Building modules...
building 'cpyrit._cpyrit_calpp' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/ati-stream-sdk-v2.3-lnx32/include -I/usr/include/python2.5 -c _cpyrit_calpp.cpp -o build/temp.linux-i686-2.5/_cpyrit_calpp.o -Wall -fno-strict-aliasing -DVERSION="0.4.0-dev (svn r288)"
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
In file included from _cpyrit_calpp.cpp:38:
/usr/local/include/cal/cal.hpp: In static member function 'static void cal::detail::param_traits<4, 39>::getInfo(CALuint&, CALfuncInfo&)':
/usr/local/include/cal/cal.hpp:257: error: 'struct CALfuncInfoRec' has no member named 'wavefrontPerSIMD'
error: command 'gcc' failed with exit status 1
have anyone an idea ?
after that i install cpyrit for opencl successfully and it runs with ~20 000 PMK/s
i have fix the problem
run
now your should calpp files into /usr/local/include/now your should calpp files into /usr/local/include/Code:
svn co calpp
cd calpp/trunk/
cmake .
make
make install
install pyrit
before you install cpyrit_calpp change header from _cpyrit_calpp_kernel.cppbefore you install cpyrit_calpp change header from _cpyrit_calpp_kernel.cppCode:
apt-get purge pyrit
apt-get install libboost-dev
svn checkout pyrit_svn
cd pyrit_svn/pyrit
./setup.py build
./setup.py install --record ~/pyrit.txt
cd ..
cd cpyrit_calpp
BEFORE
AFTERAFTERCode:
#include <cal/cal.hpp>
#include <cal/il/cal_il.hpp>
and now you can install cpyrit_calppand now you can install cpyrit_calppCode:
#include <cal/cal.hpp>
#include <cal/cal_il.hpp>
work !work !Code:
./setup.py build
./setup.py install --record ~/pyritcalpp.txt | http://www.backtrack-linux.org/forums/printthread.php?t=33227&pp=10&page=3 | CC-MAIN-2014-42 | refinedweb | 633 | 51.14 |
XY to display combination of a stacked area chart and line chart in one iframe (
Making XY line chart with string and double axis
Making XY line chart with string and double axis Good evening everybody
So i'm trying to make a XYLine chart with JFreechart. The data comes from 2 arraylist, so a for-loop should do the trick parsing the values
jfree - Java Beginners
= ChartFactory.createXYLineChart
("XYLine Chart using JFreeChart", "Age", "Weight... ChartFrame("XYLine Chart",chart);
frame1.setVisible(true);
frame1.setSize...*;
public class xyLine{
public static void main(String arg[]){
XYSeries
pie chart
pie chart how to create pie chart using struts2
jfree chart
jfree chart i need donut chart using jfree
Tutorial of the week
Tutorial of the week
Welcome to our Tutorials of the week section. We are publishing new great
Tutorials every Monday. Tutorials presented here are widely used and very
helpful for the programmers.
Our tutorial addresses the major
JSF Tutorial and examples
for,
Chart
Tree
Tabbed-pane
provided by SUN
documentation in JSF.
1.Chart:
The Chart can be drawn by using the tag . Three types of charts Vertical Bar Chart, Horizontal bar chart and pie chart can be drawn.
Vertical
XML Tutorial
of the tutorial.) We then outline the major features that make XML great...
XML Tutorial
XML
Tutorial:
XML stands for EXtensible Markup Language. In our XML tutorial you will learn what XML is and the difference between
Java Arrays Tutorial
Java Arrays Tutorial
... to
a great extent. Every topic improves your logic and makes you more keen to
go... to
ArrayList
Java Beginners
Tutorial
pie chart
Bar Chart
flow chart
coding for chart
draw chart in web application
draw chart in web application how to draw bar chat from the record store in database? i.e. draw the bar chart according to selected record
J2EE Tutorial - Introduction
J2EE Tutorial - Introduction
...
There is a great... is Java atall or something else. This
tutorial is a conceptual
Ajax Dojo Tutorial - Java Beginners
");
ChartUtilities.saveChartAsJPEG(image, chart, 400, 300);
pw.println(" Display Chart");
Dis.html... system with help of URL.The chart is not coming.Its
display empty page
Map | Business Software
Services India
JPA Tutorial Section
JDBC vs...-to-One Relationship |
JPA-QL Queries
Java Swing Tutorial Section... Component
Java Swing Tutorial Section - II
Limiting
Values in Number
Create pie chart
Create pie chart hi.............
In my project i want to create a pie chart to display the result.
i require a very simple code in java swings were i can edit the code and put my values...
so plz help
Questions |
Site
Map |
Business Software
Services India
PHP Tutorial... by PHP |
PHP Ajax |
PHP SimpleXML |
PHP Ajax DB
PHP Tutorial Section... Development with PHP Is Useful |
PHP Is Great for Website Creation |
PHP
Home | About-us | Contact Us
|
Advertisement |
Ask
Questions | Site
Map | Business Software
Services India
JSP Tutorial Section
Intro... Chart in JSP |
Draw
Statistical chart in jsp |
Paging Example in Datagrid JSP
XYArea Chart
XYArea Chart
... a XYArea Chart.
Description of Program
For creating a XYArea Chart we.... Then we add the data in this object that will show in our XYArea chart. After
i want to show timeline chart for three year in chart..
i want to show timeline chart for three year in chart.. I am using Jfree chart library to display chart in web pages. i want to show three year data in chart in 3 lines for three year in same chart. i am able to show
Pie Chart
Pie Chart
In this section we are providing you an example to
create a Pie Chart.
Description of Example
For creating a Pie Chart we use PieDataset
Bar Chart
Bar Chart
In this section we are providing you an example to create a
Bar Chart.
Description of Program
For creating a Bar chart we use the object
WaterFall Chart
WaterFall Chart
... Chart.
Description of Program :
For creating a WaterFall chart we use... color of chart and adjust the color the title etc.
Description of Code
Polar Chart
Polar Chart
In this section we are providing you an example to create a
Polar Chart.
Description of Program
For creating a Polar Chart we use the object of XYDataset
Jfreechart chart display problem
Jfreechart chart display problem Using JSP and Jfreechart displays the chart fine on an internal browser in eclipse but doesnt display it on Chrome...");
dataset.executeQuery(query);
JFreeChart chart = ChartFactory.createLineChart
Area Chart
Area Chart
In this section we are providing you an example to create a
Area Chart.
Description of Program
For creating a Area Chart we use the object
Logging Tutorial - Part 1
Logging Tutorial - Part 1
2000-12-14 The Java Specialists' Newsletter [Issue 003] - Logging part 1
Author:
Dr. Heinz M. Kabutz
If you are reading... being so widely accessible, we have
a great challenge because our programs might
Chart Series Class in Flex4
Chart Series Class in Flex4:
The chart series classes are used for render a data in a
chart control. The series classes are used... chart type has
a its own series class. for example, Bubble chart has
Chart Event in Flex4
Chart Event in Flex4:
Chart uses the chartEvent when you perform the operation
click and doubleclick on the chart. This event is the part of chart package... on the
chart item the ChartEvent will not triggered.
Example:
<?xml
Tutorial
how to create 3d chart in dojox charting - XML
how to create 3d chart in dojox charting Please provide some example for 3d charting in dojox chart
Draw Statistical chart in jsp
Draw Statistical chart in jsp
... chart in jsp by
getting values from database..
To draw a bar chart, we have used JFreeChart Library.
JFreeChart is a chart library used to generate different
Display data in a chart
Chart Item Event in Flex4
Chart Item Event in Flex4:
Chart uses the ChartItemEvent when you perform the
operation click on the chart Item. This event is the part of chart package... on the chart the result will display data not found.
Example:
Bar Chart
Bar Chart
This section illustrates you how to create bar chart
using html in jsp.
To draw a bar chart, we have used html tags. In this,
firstly
J2EE Tutorial - Session Tracking Example
J2EE Tutorial - Session Tracking Example... by great many Operating systems and
equally varied Programming languages...) and then
released for the Web World. Hence, there is a great need to develop a
3D Pie Chart
3D Pie Chart
In this section we are providing you an example to create a
3D Pie Chart.
Description of Program :
For creating a 3D Pie Chart we use
Beginners Java Tutorial
Beginners Java Tutorial
This tutorial will introduce you with the Java Programming language. This
tutorial is for beginners, who wants
Maven2 Tutorial
Maven2 Tutorial
... software
development organizations. This tutorial provides you introduction...-in
Plugins are great in simplifying the life of programmers; it actually
hybrid graph (jfree chart) - Swing AWT
hybrid graph (jfree chart) hello
i have a problem related... of stacked area chart and Line chart in one frame.
Plese anybody help me out... and explain in details
For more information on chart visit to :
http
Great Uses for PHP Language
all over again when another machine is being used.
These are all great uses
3D Bar Chart
3D Bar Chart
In this section we are providing you an example to
create a 3D Bar Chart.
Description of Program
For creating a 3D Bar chart we use the object
Formatting Legend in Chart in Flex4
Formatting Legend in Chart in Flex4:
In this section we will discuss the formatting of the
Legend in the Chart control. You can change the formatting... property for change
the formatting of legend in the chart control.
Example
MultipleAxes in Chart in Flex4
Multiple Axes in Chart in Flex4:
When we use different(Unmatched) data in single chart so
it will not be possible to represent multiple series in a single chart. For
solving this problem we use multiple axes in a single chart
JFreechart Stacked Bar Chart
JFreechart Stacked Bar Chart
JFreechart provides a way to create various... chart, pie chart, line chart,area chart etc. Here we are going to create a Stacked Bar Chart. This chart actually displays the result of multiple queries stacks
Chart Effect in Flex4
Chart Effect in Flex4:
Chart uses the standard Flex effect like Zoom and Fade.
There are some standard effect for chart series which is: SeriesInterpolate...
package. The base class for chart effect is SeriesEffect. You can triggered | http://www.roseindia.net/tutorialhelp/comment/84422 | CC-MAIN-2014-35 | refinedweb | 1,421 | 64.2 |
Creating your first Facebook Messenger bot
This blog post was written under the Pusher Guest Writer program.
When Facebook announced its Messenger bot platform, I am sure a lot of developers could easily see how well the platform could work for them. This article is going to be a guide on how you can easily create your own Facebook Messenger bot.
The bot will basically be a webhook that responds to queries submitted to it. Anytime someone sends your Facebook Page a message, it will respond appropriately with what you want it to respond with. This article will cover mainly how to create the bot and have it respond with a hard-coded message. How you get it to be smarter is up to you.
Getting started
We are going to be creating the bot using the popular PHP framework, Lumen which is basically a light version of Laravel. However, since Facebook communicates to your webhook using HTTP, you can use any language and any framework you wish to use, provided you can receive and send requests.
1. Setting up your code
To start a new Lumen project, you need to use
lumen new projectname, then open the code in your favorite editor.
We want to create one endpoint but two methods that respond to the endpoint depending on the HTTP request type: one for
GET and one for
POST. The
GETwould be used to verify with Facebook that you indeed own the domain and have appropriate access, while the
POST would be used to respond to the messages sent to your bot.
Open the routes definition file (
./routes/web.php) and add the following routes:
$app->get('/webhook', 'BotController@verify_token'); $app->post('/webhook', 'BotController@handle_query');
Now we need to create the
BotController where we will define the methods. Create a
./app/Http/Controllers/BotController.php file and copy in the contents:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class BotController extends Controller { /** * The verification token for Facebook * * @var string */ protected $token; public function __construct() { $this->token = env('BOT_VERIFY_TOKEN'); } /** * Verify the token from Messenger. This helps verify your bot. * * @param Request $request * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory */ public function verify_token(Request $request) { $mode = $request->get('hub_mode'); $token = $request->get('hub_verify_token'); if ($mode === "subscribe" && $this->token and $token === $this->token) { return response($request->get('hub_challenge')); } return response("Invalid token!", 400); } /** * Handle the query sent to the bot. * * @param Request $request * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory */ public function handle_query(Request $request) { $entry = $request->get('entry'); $sender = array_get($entry, '0.messaging.0.sender.id'); // $message = array_get($entry, '0.messaging.0.message.text'); $this->dispatchResponse($sender, 'Hello world. You can customise my response.'); return response('', 200); } /** * Post a message to the Facebook messenger API. * * @param integer $id * @param string $response * @return bool */ protected function dispatchResponse($id, $response) { $access_token = env('BOT_PAGE_ACCESS_TOKEN'); $url = "{$access_token}"; $data = json_encode([ 'recipient' => ['id' => $id], 'message' => ['text' => $response] ]); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); $result = curl_exec($ch); curl_close($ch); return $result; } }
Let us explain a little what is happening in the class above:
In the constructor, we have defined the token we will be using for the requests we will be making. We will set this value later in our
.env file. The
verify_token method is where we will be verifying the token sent to us by the Messenger API. Facebook will be sending us a
hub_verify_token in the payload and we will compare this to the token we have set locally. If there is a match, we will return the
hub_challenge sent from the API.
The
handle_query will be the method that receives the messages sent to the chat bot and responds. This is where most of the logic should be done. The method uses a
dispatchResponse method to send a POST request to the Messenger API.
Now you need to create an
.env file in the root of the project. This is where we will store the secret credentials.
APP_ENV=local APP_DEBUG=true APP_KEY= APP_TIMEZONE=UTC BOT_VERIFY_TOKEN="INSERT_TOKEN_HERE" BOT_PAGE_ACCESS_TOKEN="INSERT_ACCESS_TOKEN_HERE" DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret CACHE_DRIVER=file QUEUE_DRIVER=sync
You can add a random value to
BOT_VERIFY_TOKEN now but the
BOT_PAGE_ACCESS_TOKEN will be provided to you by Facebook later. Close the file. That’s all for now.
2. Exposing your application to the web
Now we have created the application but we can only access it locally, however, Facebook requires that you must have a web accessible URL and also it must have HTTPS. We therefore have to expose our current application to the web so the Facebook verifier can access the page.
To expose the application to the internet, we will be using a tool called ngrok. This tool will basically tunnel your localhost so that it is available to the world. Neat. Since we are using Lumen, we are going to be using Valet which is a light web server and it comes with ngrok installed. So, we would start our web server if not already started, then share it using Valet.
$ valet link projectname $ valet share
The
valet link command just makes it so you can access your project with the
projectname.dev locally and the
valet share command just uses ngrok to tunnel your local server to the world.
Now if we visit the URL that ngrok has provided us we should see our application running. Cool.
Note: To stop ngrok, press ctrl+c on your keyboard. However, running the
valet sharecommand will generate another random url for you by default.
3. Create a Facebook App and Page
The first step would be to create a Facebook App and page or you can use existing ones. If you are going to be creating a new page then go here and start creating a new Facebook Page.
Once you have created your page, you now need to create an application for your Page. Go to Facebook Developers. Look for a link that helps you create a new application. Then you can fill the form to create your Facebook application. Great.
Now in the pop up fill in the details of the application you want to create. You should be redirected to the ****App Dashboard**** of the application you just added. In there, go to the Product Settings, click “Add Product” and select “Messenger.”.
4. Setting up your Facebook Messenger webhooks
Now, click on “Setup Webhooks”, it should be an option available to you.
You should see a new pop up:
In the popup, enter a URL for a webhook (for example, we can use our ngrok URL as the webhook; the one provided in the screenshot was). Now, enter the verify token that you added to your
.env file earlier, then select
messages and
messaging_postbacks under Subscription Fields.
For your webhook URL, use the URL that ngrok provided (the HTTPS version). Click Verify and Save in the New Page Subscription to call your webhook with a
GET request. Your webhook should respond with the
hub_challenge provided by Facebook if the
hub_verify_token provided matches with the one stored on your server.
5. Get a Page Access Token
To get an access token, one that you will add to the
BOT_PAGE_ACCESS_TOKENvalue in your
.env file, use the Token Generation section of the Messenger settings page. Select the page you want to authorize and then follow the prompt and grant the application permission if you haven’t already. The page should now display an access token; take this and set it in the
.env file.
6. Get a Page Access Token
Now we need to subscribe to the Messenger events so that when they happen, Facebook will send us a payload with the details we need to process the event query. Click on select a page in the Webhooks section of the Messenger settings page, select the page and select the events you would like to subscribe to. You can always edit the events you are subscribed to at any time.
Testing it out
Now that you have completed the set up of your messenger bot, head on over to your page and then in the page, send the bot a message. If you have done everything correctly, you should receive a response from the bot.
Conclusion
We have been able to create the skeleton for a Facebook messenger bot using PHP. This barely scratches the surface of what your new Messenger bot can actually do. For exercise, try to use the wit.ai service to create a smarter bot for your page.
If you have any questions or feedbacks on the article, please leave them as a comment below. You can find the source code to the article on GitHub. | https://blog.pusher.com/creating-first-facebook-messenger-bot/ | CC-MAIN-2018-05 | refinedweb | 1,461 | 62.68 |
For anybody whos been following the mGui Maya GUI construction kit posts, I’ve added a few fixes and tweaks to the GitHub project in the last couple of weeks:
mGui.progress
The progress module wraps Maya’s
progressBar command for mGui style coding of progress bars.
There are two classes in the module;
ProgressBar is the generic version and
MainProgressBar always points at Maya’s main progress bar. Both classes have
start(),
update() and
end() methods instead of Maya’s clunky
cmds.progressBar(name, e=True, beginProgress=1) and so on. They also both have an
iter() method, which will loop over a generator expression and update the progress bar for each yield then pass along the value. This allows simple idioms like:
from mGui.progress import MainProgressBar import os def list_files(dir): # pretend this is as long, slow function... for item in os.listdir(dir): yield item pb = MainProgressBar() for each_file in pb.iter(list_files()): print each_file.upper() # here's where you do something with the results
So you can update the progress bar without unduly intertwining the GUI update and the program logic.
mGui.menu_loader
The menu_loader module will create menus from a YAML data file. It does a little bit of introspection to figure out how to create the items and attach their handlers to functions. This makes it easy to set up a menu with several items from a single setup routine.
The menu data is a text-based YAML file that looks like this:
!MMenu key: UndeadLabs label: Undead Labs items: - !MMenuItem key: About label: About Undead Labs... annotation: "About this UndeadLabs tool setup" command: tools.common.aboutDialog.open - !MMenuItem key: RemoteDebugger label: Remote Debugger annotation: Start / Stop remote python debugger command: tools.common.remoteDebug.remote_debugger_dialog
And loading the menu is as simple as:
import mGui.menu_loader as loader loader.load_menu('path/to/undeadlabs.YAML')
mGui.scriptJobs
The scriptJobs module adapts the event model for use with scriptJobs. A ScriptJobEvent is a derivative of Event which allows you to hook multiple handlers to a single scriptjob (in the same way that the other Event classes allow for multicast delegates):
from mGui.scriptJobs import * def print_selected (*args, **kwargs): print cmds.ls(sl=True) or [] sj = ScriptJobEvent("e", "SelectionChanged") sj += print_selected
As with all the mGui Event classes, you can add multiple handlers to single event:
sj += some_other_function()
The module also includes named subclasses to simplify setup. That way you can do things like:
closing_sj = RecentCommandChanged() closing_sj += close_handler
which is a bit nicer and less typo prone if you use an autocompleting IDE. | https://theodox.github.io/2014/mgui_updates_1 | CC-MAIN-2017-26 | refinedweb | 427 | 56.86 |
Hello All,
the appended patch changes tools-for-build/determine-endianness.c
to C standard conforming code.
Thiemo
Index: tools-for-build/determine-endianness.c
===================================================================
RCS file: /cvsroot/sbcl/sbcl/tools-for-build/determine-endianness.c,v
retrieving revision 1.1
diff -u -p -r1.1 determine-endianness.c
--- tools-for-build/determine-endianness.c 25 Nov 2002 13:24:15 -0000 1.1
+++ tools-for-build/determine-endianness.c 16 May 2005 22:20:32 -0000
@@ -19,32 +19,18 @@
#include <stdio.h>
-int main (int argc, char *argv[]) {
- int foo = 0x20212223;
- char *bar = (char *) &foo;
- switch(*bar) {
- case ' ':
- /* Do nothing */
- break;
- case '#':
- printf(" :little-endian");
- break;
- default:
- /* FIXME: How do we do sane error processing in Unix? This
- program will be called from a script, in a manner somewhat
- like:
+int main (void) {
+ union _u {
+ int foo;
+ char bar[sizeof(int)];
+ } u;
- tools-for-build/determine-endianness >> $ltf
+ /* The test string is ' !"#' for big endian, '#"! ' for little endian. */
+ u.foo = 0x20212223;
- but what if we have a too-smart C compiler that actually
- gets us down to this branch? I suppose that if we have a C
- compiler that is that smart, we're doomed to miscompile the
- runtime anyway, so we won't get here. Still, it might be
- good to have "set -e" in the various scripts so that we can
- exit with an error here and have it be caught by the build
- tools. -- CSR, 2002-11-24
- */
- exit(1);
- }
- exit(0);
+ /* Big endian is default. */
+ if (u.bar[0] == '#')
+ puts(" :little-endian");
+
+ return 0;
}
* Thiemo Seufer:
> the appended patch changes tools-for-build/determine-endianness.c
> to C standard conforming code.
Are you sure this is necessary?
> - int foo = 0x20212223;
> - char *bar = (char *) &foo;
This cast is fine because char pointers are special.
Florian Weimer wrote:
> * Thiemo Seufer:
>
> > the appended patch changes tools-for-build/determine-endianness.c
> > to C standard conforming code.
>
> Are you sure this is necessary?
Strictly speaking, it's not ...
> > - int foo = 0x20212223;
> > - char *bar = (char *) &foo;
>
> This cast is fine because char pointers are special.
... but a union is IMHO the cleaner implementation (and more likely
to survive broken compiler optimizers).
Thiemo | http://sourceforge.net/p/sbcl/mailman/sbcl-devel/thread/20050516222530.GB15052@hattusa.textio/ | CC-MAIN-2014-41 | refinedweb | 363 | 60.11 |
I'm having trouble deleting rows in text file that contains a string in one column. My code so far is not able to delete the row, but it's able to read the text file and save it as a CSV file into separate columns. But the rows are not getting deleted.
This is what the values in that column looks like:
Ship To or Bill To
------------------
3000000092-BILL_TO
3000000092-SHIP_TO
3000004000_SHIP_TO-INAC-EIM
'INAC'
'EIM'
import csv
my_file_name = "NVG.txt"
cleaned_file = "cleanNVG.csv"
remove_words = ['INAC','EIM']
with open(my_file_name, 'r', newline='') as infile, \
open(cleaned_file, 'w',newline='') as outfile:
writer = csv.writer(outfile)
for line in csv.reader(infile, delimiter='|'):
if not any(remove_word in line for remove_word in remove_words):
writer.writerow(line)
The problem here is that the
csv.reader object returns the rows of the file as lists of individual column values, so the "in" test is checking to see whether any of the individual values in that list is equal to a
remove_word.
A quick fix would be to try
if not any(remove_word in element for element in line for remove_word in remove_words):
because this will be true if any field in the line contains any of the
remove_words. | https://codedump.io/share/7NFkRJHN6ubj/1/deleting-a-row-if-it-contains-a-string-in-a-csv-file | CC-MAIN-2016-44 | refinedweb | 205 | 62.98 |
Write files. The second file will be a copy of the first file, except that all the characters will be uppercase. Have some sort of input validation. Use Notepad to create a simple file that can be used to test the program.
Ive tried and tried.Any help at this point would be great.
Heres what I have so far
import java.util.Scanner; import java.io.*; public class UppercaseFileConverter2 { public static void main(String[] args)throws IOException { String filename; String message; String filename2; //Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); //Get the filename. System.out.print("Enter the filename: "); filename = keyboard.nextLine(); //Open the file. FileWriter fwriter = new FileWriter(filename); PrintWriter outputFile = new PrintWriter(fwriter); //Get the message to be written in the file. System.out.println("Enter a message: "); message = keyboard.nextLine(); //Write the message to the file. outputFile.println(message); //Close the file. outputFile.close(); //Get the second file's name. System.out.println("Enter the name of the second file: "); filename2 = keyboard.nextLine(); //Open an input file. FileReader freader = new FileReader(filename2); BufferedReader inputFile = new BufferedReader(freader); String str; //Read the first item. str = inputFile.readLine(); //If the item was read, display it in UpperCase. while (str != null) { System.out.println(str); String upper = message.toUpperCase(); str = inputFile.readLine(upper); } //Close the file. inputFile.close(); } } | http://www.dreamincode.net/forums/topic/191758-uppercase-file-converter/ | CC-MAIN-2017-39 | refinedweb | 225 | 55 |
The author selected the Internet Archive to receive a donation as part of the Write for DOnations program.
Introduction
Gatsby is a popular framework for turning source material into static HTML files that are ready for instant deployment. Because of this, it is often called a Static Site Generator (SSG). As an SSG, it already has a positive impact on user experience (UX) by turning multiple content sources into an optimized website, but there is another layer available for UX improvement: Progressive Web App capabilities.
A Progressive Web App, or PWA, is a type of website that goes beyond the usual limits of web capabilities, using newer technology to bridge the gap between your browser and your operating system. PWAs encompass a lot of different features, such as offline browsing, installation support, and newer web APIs. By combining these features, PWAs deliver your users an improved overall browsing experience, as well as the option to use your website like any other application, complete with its own icon and app window.
Although there is a lot that goes into making an optimal PWA, Gatsby provides tools and support to streamline the process, such as a manifest file plugin (
gatsby-plugin-manifest) and an offline plugin (
gatsby-plugin-offline). This tutorial will walk you through using these plugins, as well as audit tools like Lighthouse, and by the end you will have learned how to take a Gatsby site and turn it into a fully-functional Progressive Web App.JS download page.
- Some familiarity with JavaScript, for working in Gatsby. The JavaScript language is an expansive topic, but a good starting spot is our How to Code in JavaScript series.
- An existing Gatsby project that does not yet have PWA support, but is otherwise functional. For satisfying this requirement and building a new Gatsby project from scratch, you can refer to Step 1 of the How to Set Up Your First Gatsby Website tutorial.
- (Optional) An icon file for your website. In order to be installable, your PWA will need an icon with an original resolution of at least
512 x 512pixels. If you do not have an icon in mind, this tutorial will instruct you to download a sample icon in Step 2.
This tutorial was tested on Node v14.17.2, npm v6.14.13, Gatsby v3.9.0,
gatsby-plugin-offline v4.8.0, and
gatsby-plugin-manifest v3.8.0.
Step 1 — Preparing Your Content (Optional)
As a prerequisite, you already have created a functional Gatsby site that can be built and deployed. However, you might not have any content for your site yet. In this step, you will prepare a sample smart home user guide site to demonstrate what kind of content benefits from PWA features.
As a smart home user guide is something likely to be visited multiple times by the same user, it makes a great example to showcase the main features of a PWA. The app-like qualities of a PWA, such as installation support and home screen icons, make it accessible on both mobile and desktop devices, and thanks to offline support, even when your home network fails, you or other residents can still access the guide.
Building off the starter template, you can add a new page for the smart home guide under
src/pages. Create a file named
src/pages/internet-issues.js, and add the following sample page code:
src/pages/internet-issues.js
import * as React from "react" import { Link } from "gatsby" import Layout from "../components/layout" import Seo from "../components/seo" const IndexPage = () => ( <Layout> <Seo title="Internet Issues" /> <h1>Internet Issues - Troubleshooting</h1> <p>Having issues connecting to the internet? Here are some things to try in our house.</p> <ul> <li>Your Device <ul> <li>Is airplane mode on? Is WiFi enabled?</li> <li>Is the device within range of the router or physically connected to the network via ethernet?</li> <li>Are you connected to the correct network?</li> </ul> </li> <br /> <li>The Router / Modem <ul> <li>Have you checked the ISPs status page to check for an outage? You can use your smartphone and mobile data to check this.</li> <li>Have you tried rebooting the router and/or modem?</li> <li>Have you checked to make sure that all physical connections to and from the router and modem are secure?</li> </ul> </li> </ul> <br/> <p> <Link to="/">Back to homepage</Link> <br /> </p> </Layout> ) export default IndexPage
In this page code, you’ve provided troubleshooting instructions to your housemates or guests for when they are having trouble connecting to the internet. You have done so with a bulleted list, providing a link back to the homepage for easier navigation. Since this is a Gatsby project, you’ve created the entire page as a React component, which will nest your list inside a reusable
Layout component and return the page as JSX so Gatsby can process it. For an optimized navigational experience, you’ve also used a
Link component to link back to the homepage, instead of a regular HTML
a tag.
Make sure to save the file after updating it, and you can go ahead and close it since you won’t need to update it again in this tutorial.
This page will be accessible at
your_domain/internet-issues/, but you will also add a link to it from your homepage to make it easier to get to.
Open up
src/pages/index.js, and add a direct link to the new page within the React component
IndexPage, as shown in the following highlighted code:
src/pages/index.js
import * as React from "react" import { Link } from "gatsby" import { StaticImage } from "gatsby-plugin-image" import Layout from "../components/layout" import Seo from "../components/seo" const IndexPage = () => ( <Layout> ... <p> <Link to="/internet-issues/">Internet Issues Troubleshooting Page</Link> <br /> <Link to="/page-2/">Go to page 2</Link> <br /> ... </p> </Layout> )
Save and close
index.js with the added link.
You’ve now built a brand new page for your smart home user guide and added a link to get to it from your homepage. In the next step, you will be adding a special file known as a manifest file, which instructs web browsers on the specifics of your PWA setup.
Step 2 — Adding a Manifest File
The next step is fulfilling one of the core requirements of PWAs by adding a manifest JSON file,
manifest.json. The manifest file tells the web browser details about your site and how to display it to the user if it is installed on the users’s OS, specifying details such as what icon to use and how it should be launched. You will use
gatsby-plugin-manifest to generate this file by initializing the plugin in your Gatsby config file.
First, install the Gatsby plugin by running the following command in your Gatsby project directory:
- npm install gatsby-plugin-manifest
Next, you will provide some details to the plugin that tell it how you want the PWA to appear and act. You do this by editing the main Gatsby config file that lives in the root of your project directory,
gatsby-config.js. Open this file and add the following code:
gatsby-config.js
module.exports = { plugins: [ ... { resolve: `gatsby-plugin-manifest`, options: { name: `My Smart-Home Guide`, short_name: `SH Guide`, description: `Guide for residents of the ABC123 Smart Home`, start_url: `/`, background_color: `#0a68f0`, theme_color: `#0a68f0`, display: `standalone`, icon: `src/images/pwa-icon.png`, icons: [ { src: `/favicons/pwa-icon-192x192.png`, sizes: `192x192`, type: `image/png` }, { src: `/favicons/pwa-icon-512x512.png`, sizes: `512x512`, type: `image/png` } ] }, } ... ] }
Note: If you have started with the
gatsby-starter-default template, you will already have some values for this plugin in your config file. In that case, overwrite the existing values with this code.
There are a lot of values in this file, so here is a quick explanation:
nameand
short_nameshould correspond with the name of your site and how you want the site to appear to users when installed.
short_nameappears on the home screen of the user’s device, or other places where space is limited, and
nameappears everywhere else.
descriptionshould be text that describes the purpose of your application.
start_urlis used to suggest to the browser which page should open when the user launches the PWA from their launcher. A value of
/, as used here, tells the browser you would like the user to land on your homepage when opening the PWA.
background_colorand
theme_colorare both directives to the browser on styling the PWA, and the values should correspond to CSS color strings.
background_coloris only used while waiting on the actual stylesheet to load, as a placeholder background color, whereas
theme_coloris potentially used in multiple places outside the PWA, such as surrounding the icon on an Android home screen.
displayis a special value because it dictates how your entire site acts as a PWA, and, unlike other fields which support hundreds of different combinations, can be one of four possible values:
fullscreen,
standalone,
minimal-ui, or
browser. In your config, the value of
standalonemakes the PWA act like a standalone application outside the standard web browser. In practice, this means that it acts similar to a native application—it gets its own launcher icon, application window, and the URL address bar is hidden.
iconis not one of the standard manifest fields, but is a special field within the context of
gatsby-plugin-manifest. By using this property, and providing a path to a file that meets the minimum requirements (at least
512x512pixels, square), the Gatsby plugin will automatically transform the image into a site favicon, as well as inject into the manifest as the required
iconsmanifest property. By specifying
iconswith an array of filenames, sizes, and image types, you are invoking the Hybrid Mode Configuration of the manifest plugin. This takes your single source icon file and transforms it into the filenames and sizes specified. This is not strictly necessary, but it avoids any possible issues with deployments in environments like Apache, which don’t work with the default
/iconsdirectory.
Make sure to save the config file with your changes, but keep it open for the next step, where you will be adding another Gatsby plugin and configuring offline support.
In the manifest values, the path used for
icon was
src/images/pwa-icon.png, but you still need to place an image file at that location before it will work. If you have a square image file that is at least
512 x 512 pixels, you can copy it to that path. Otherwise, you can use a pre-formatted image file selected for this tutorial. To use the tutorial icon file, either download the sample icon file for this tutorial and save it at
src/images/pwa-icon.png, or if you prefer the command line, use cURL from your project root directory:
- curl -o ./src/images/pwa-icon.png
This will download the image to the correct part of your Gatsby application. This is the only image file you’ll need; Gatsby will automatically generate the
192x192 version.
You have now configured your Gatsby project to serve a manifest JSON file with the correct values, which is a required part of enabling PWA capabilities. In the next step, you will be addressing another requirement of PWAs, offline support, by adding the feature via a service worker plugin,
gatsby-plugin-offline.
Step 3 — Adding Offline Support with Service Workers
Another key component of PWAs is offline support, which you will implement with a piece of web technology known as a service worker. A service worker is essentially a bundle of JavaScript code that runs separately from all the code tied to the UI of the page you are on. This isolated code is also granted special privileges, such as the ability to alter the behavior of network requests, which is critical for implementing offline support. In this step, you will set up a robust service worker through the
gatsby-plugin-offline plugin, configured through your Gatsby config file.
Start by installing the
gatsby-plugin-offline package and adding it to your dependencies. You can do so with:
- npm install gatsby-plugin-offline
Next, load the plugin through the Gatsby config, the same
gatsby-config.js edited in the previous step:
gatsby-config.js
module.exports = { plugins: [ ... { resolve: `gatsby-plugin-manifest`, options: { ... }, }, `gatsby-plugin-offline`, ... ] }
Make sure to save the configuration file after adding the new plugin.
Warning: Both the docs for
gatsby-plugin-manifest and for
gatsby-plugin-offline specify that
gatsby-plugin-offline should always come after
gatsby-plugin-manifest in the configuration array, as shown in this code snippet. This ensures that the manifest file itself can be cached.
At this point, you’ve both added offline support and created a manifest file for your app. Next, this tutorial will explain the third necessary part of a PWA: having a secure context.
Step 4 — Providing a Secure Context
The last of the three basic minimum requirements for any PWA is that it run in a secure context. A secure context refers to a web environment in which certain baseline standards are met for authentication and security, and most often is referring to content served over HTTPS.
A secure context can be achieved in many ways. Because of this, this tutorial will describe a few different strategies to get a secure context, then move forward with testing your Gatsby site locally.
If you are deploying your Gatsby project through a static host, such as DigitalOcean’s App Platform, then it is likely that HTTPS is supported out of the box, with no setup required. For more information on deploying your app on App Platform, check out the How To Deploy a Gatsby Application to DigitalOcean App Platform tutorial.
If you are deploying on a server that does not automatically provide HTTPS, but you have SSH access, you can use Let’s Encrypt to obtain and install a free TLS/SSL certificate. For example, if you are using Apache with Ubuntu 20.04, you can follow How To Secure Apache with Let’s Encrypt on Ubuntu 20.04 to use Certbot to handle this process. If you are deploying to a shared host, you will want to check their specific documentation pages for if, and how, SSL certificate installation might be available.
For local testing, you don’t have to deal with obtaining or installing an SSL certificate. This is because most modern browsers treat
localhost sites as a secure context, even without a TLS/SSL certificate installed or HTTPS protocol.
You now have successfully added PWA support to your Gatsby project by meeting the three baseline criteria: HTTPS (or a
localhost secure context), a manifest file, and a service worker. The next step is to test and verify that it shows up correctly, with PWA features enabled.
Step 5 — Running Local Tests
In this step, you will run some local tests to make sure your PWA functionality is working properly. This is an initial testing step before using the Lighthouse tool for a more comprehensive audit.
To locally test your Gatsby site’s functionality as a PWA, build it and then serve the generated build directory:
- npm run build
- npm run serve
Once it is ready, you will see the following:
OutputYou can now view gatsby-starter-default in the browser. ⠀
You can now visit that URL in your web browser, and if the browser supports PWAs, you will encounter some special additional UI elements. For example, on Chrome desktop, there will be a new button exposed in the address bar that, when clicked, asks if you would like to install the Gatsby site as an app, as shown in the following image:
If you want to test your site locally on a smartphone, this is possible with something like Chrome’s remote debugging tool (Android only), or a
localhost tunneling service such as ngrok. On mobile, you will encounter the same option to install your site as an app, as shown in the following:
This PWA prompt is different for each device, operating system, and browser. Additionally, certain features such as Add to Home Screen might only be available on certain devices. Certain browsers running on specific devices might not support PWAs entirely; check
caniuse.com for more information on platform support.
You have now verified that your Gatsby project can be built and served locally, with your browser successfully detecting that it offers PWA functionality. The next step will be a final check against what you have put together, and using the Lighthouse tool to check if there are areas for improvement.
Step 6 — Running an Audit with Lighthouse
At this point, you have a Gatsby site that meets all the core requirements for a PWA: it has HTTPS, a manifest, and a service worker for offline support. However, the concept of a PWA goes beyond any single requirement—it encompasses all of the facets working together, plus adhering to general guidelines. With this in mind, your last step is to use an audit tool to verify that you meet the baseline criteria, as well as gather information on how you can further optimize your Gatsby project to meet PWA best practices.
There are a few different ways to audit your site as a PWA, but at the moment the gold standard is the Lighthouse Tool. If you have desktop Chrome installed, you can run an audit against your site directly in the web browser DevTools.
First, navigate to your Gatsby site in Chrome, then open Chrome DevTools by right clicking anywhere on the webpage and selecting Inspect in the right click menu. Next, click the Lighthouse tab under DevTools. If you don’t see it, click the >> label next to the right-most tab to show tabs that are hidden due to size constraints.
Now, to actually run the report, uncheck everything on the Lighthouse tab except for Progressive Web App, and then hit Generate Report to analyze your site:
You can also generate this report programmatically, via the Lighthouse Node.js CLI. This command will run the PWA-only audit and then open the report for viewing:
- npx lighthouse --only-categories=pwa --view
However, using Lighthouse via CLI does not bypass the need to have Chrome installed; this just makes it easier to automate the process.
The report generated by Lighthouse tells you a few things, broken down into categories. Some of the most important are:
- Installable: This is the most important category, and addresses whether or not your site meets the three baseline criteria for being an installable PWA—HTTPS, manifest files, and a service worker.
- PWA Optimized: These are things that you should be doing for an optimal PWA user experience, but aren’t strictly required for your PWA to be functional. Think of these as best-practice suggestions. Some examples of these are creating a custom splash screen to display during mobile app loading, setting a theme color for the address bar, and providing fallback content for when JavaScript is unavailable. If you’d like to look at the full list, check out the official Lighthouse documentation.
By using the Lighthouse tool to audit your Gatsby PWA, you not only now have a functional PWA, but also have an idea of how it meets PWA requirements and best practices.
Conclusion
After following these steps, you now have a Gatsby site that can also function as a modern installable Progressive Web App, with strong offline support. You are now providing your users with the best of both worlds: They can browse your site as a normal web page, but they can also use it as they would a native application, with its own launcher icon, display window, and the reliable performance they expect from native applications.
If you are looking for more ways to deliver the most optimized PWA experience possible, in addition to the Lighthouse PWA audit, Google also has a published a PWA checklist that will help. If you would like to read more on Gatsby, check out the rest of the How To Create Static Web Sites with Gatsby.js series. | https://www.xpresservers.com/tag/convert/ | CC-MAIN-2021-39 | refinedweb | 3,364 | 59.23 |
Cross-platform colored terminal text.
Project description
- Download and docs:
-
- Development:
-
Description
Makes ANSI escape character sequences for producing colored terminal text work under MS Windows.
ANSI escape character sequences have long been used to produce colored terminal text on Unix and Macs. Colorama makes this work on Windows, too. It also provides some shortcuts to help generate ANSI sequences,().
A demo script in the source code repository prints some colored text using ANSI sequences. Compare its output under Gnome-terminal’s built in ANSI handling, versus on Windows Command-Prompt using Colorama:
These screengrabs make it clear that Colorama on Windows does not support ANSI ‘dim text’: it looks the same as ‘normal text’.
Dependencies
None, other than Python. Tested on Python 2.5.5, 2.6.5 & 3.1.DEFAULT + Back.DEFAULT + Style.DEFAULT, DEFAULT. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, DEFAULT. Style: DIM, NORMAL, BRIGHT, RESET_ALL
Style.RESET_ALL resets foreground, background and brightness. Colorama will perform this reset automatically on program exit.:
from colorama import init, AnsiToWin32 init(wrap=False) stream = AnsiToWin32(sys.stderr).stream print >>stream, Fore.BLUE + 'blue text on stderr'
Status & Known Problems
Feature complete as far as colored text goes, but still finding bugs and occasionally making small changes to the API (such as new keyword arguments to init()).
Only tested on WinXP (CMD, Console2) and Ubuntu (gnome-terminal, xterm). Much obliged if anyone can let me know how it fares elsewhere, in particular on Macs.
I’d like to add the ability to handle ANSI codes which position the text cursor and clear the terminal.
See outstanding issues and wishlist at:
If anything doesn’t work for you, or doesn’t do what you expected or hoped for, I’d love to hear about it on that issues list..
Development
Running tests requires:
- Michael Foord’s ‘mock’ module to be installed.
- Either to be run under Python2.7 or 3.1 stdlib unittest, or to have Michael Foord’s ‘unittest2’ module to be
Roger Binns, for many suggestions, valuable feedback, & bug reports. Tim Golden for thought and much appreciated feedback on the initial idea.
Changes
- 0.1.17
- Prevent printing of garbage ANSI codes upon installing with pip
- 0.1.16
- Re-upload to fix previous error. Make clean now removes old MANIFEST.
- 0.1.15
- Completely broken. Distribution was empty due to leftover invalid MANIFEST file from building on a different platform. Fix python3 incompatibility kindly reported by Günter Kolousek
- 0.1.14
- Fix hard-coded reset to white-on-black colors. Fore.RESET, Back.RESET and Style.RESET_ALL now revert to the colors as they were when init() was called. Some lessons hopefully learned about testing prior to release.
- 0.1.13
- Completely broken: barfed when installed using pip.
- 0.1.12
- Completely broken: contained no source code. double oops.
- 0.1.11
- Completely broken: fatal import errors on Ubuntu. oops.
-.
- 0.1.5
- Now works on Ubuntu.
- 0.1.4
- Implemented RESET_ALL on application exit
- 0.1.3
- Implemented init(wrap=False)
- 0.1.2
- Implemented init(autoreset=True)
- 0.1.1
- Minor tidy
- 0.1
- Works on Windows for foreground color, background color, bright or dim
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/colorama/0.1.17/ | CC-MAIN-2021-31 | refinedweb | 560 | 60.31 |
Sound, how is it done?
asked 2013-05-03 04:05:04 +0100
This post is a wiki. Anyone with karma >750 is welcome to improve it.
Im working on an interactive piece using an alternate form of the doppler effect and I would appreciate some help in making it play sound. Thank you
import wave class SoundFile: def __init__(self, signal,lab=''): self.file = wave.open('./test' + lab + '.wav', 'wb') self.signal = signal self.sr = 44100 def write(self): self.file.setparams((1, 2, self.sr, 44100*4, 'NONE', 'noncompressed')) self.file.writeframes(self.signal) self.file.close() mypi = float(pi) from math import sin var('x') @interact def sinsound(f = slider(16,16000,1,5120)): v = 340.29 html('$y = f*(((v)+ tan(x))/((v)+sin(x))))$') y = f*((v+tan(x))/(v+sin(x))) hz1 = y s2 = [sin(hz1*x*mypi*2) for x in srange(0,4,1/44100.0)] s2m = max(s2) s2f = [16384*x/s2m for x in s2] s2str = ''.join(wave.struct.pack('h',x) for x in s2f)</embed>')
Hi. It is not clear at all what your code shoud do !! The variable **y** seems to be a function of **x** but is used as a float number. The parameter **f** has the same name as the **SoundFile** object... Anyway, as such because you use the function **sin** from **math** I get an error because you can not evaluate it on a symbolic variable.
You may also find the discussion [here]() interesting, as well as [this ticket](). | https://ask.sagemath.org/question/10083/sound-how-is-it-done/?sort=oldest | CC-MAIN-2021-49 | refinedweb | 255 | 78.04 |
.
TENTH EDITION
CAMBRIDGEUNIVERSITY PRESS
Contents
PrefaceManual metal arc weldingThe electric arcElectrode classification (British)Electrode classification (American)Welders' accessoriesThe practice of manual metal arc weldingWelding of pipelinesWelding of carbon and carbon-manganese andlow-alloy steelsLow-alloy steel classificationsGas shielded metal arc weldingMetal inert gas (MIG), metal active gas (MAG)including CO 2 and mixed gas processesTechniquesCO 2 welding of mild steelAutomatic weldingMIG pulsed arc weldingSynergic pulse MIG weldingTungsten electrode, inert gas shielded welding processes(TIG), and the plasma arc processTechnology and equipmentWelding techniquesAutomatic weldingPlasma-arc weldingResistance welding and flash butt weldingSpot weldingElectrodesSeam weldingProjection welding
XI
11142223317378839292119129131137140147147173185189197197204208211Vll
viii
ContentsResistance butt weldingFlash butt weldingAdditional processes of weldingSubmerged arc weldingElectroslag weldingMechanized MIG welding with robots (robotics)Pressure weldingFriction weldingElectron beam weldingLaser beam weldingStud weldingCapacitor discharge stud weldingExplosive weldingGravity weldingThermit weldingUnderwater weldingOxy-acetylene weldingPrinciples and equipmentMethods of weldingCast iron weldingBraze welding and bronze weldingCopper weldingAluminium weldingWelding of nickel and nickel alloysHard surfacing and stellitingBrazingGeneral precautionsCutting processesGas cutting of iron and steelOxygen or thermic lanceFlame gouging by the oxy-acetylene processOxy-arc cutting processArc-air cutting and gouging processPlasma cuttingPowder injection cuttingUnderwater cuttingThe welding of plasticsPlasticsMachine (tractor) weldingHigh frequency spark testingHot plate (or hot iron) weldingHot plate welding by machineElectric fusion weldingUltrasonic welding
212213216216224226231234237239242245247250251253255255274286288298301306310317323326326333336338339340349353356356369370371372373374
[x
467
467480497500502507512536538
Preface
The Science and Practice of Welding was divided into two volumes for theeighth edition: Volume 1, Welding Science and Technology, Volume 2,The Practice of Welding. Volume 1 covers all the basic material on thephysics and chemistry of welding, including metallurgy, equilibriumdiagrams, testing of welds, drawing and welding symbols and an appendixwith tables and conversions. Volume 2 gives a comprehensive survey ofthe welding methods in use today and the tools involved.This tenth edition has been brought completely up to date throughout.Volume 1 has a new chapter on the inverter, which has become popularas a power unit because of its reduced weight and size compared with aconventional unit. There is also an up-to-date section on the classificationof stainless steels. Volume 2 has a new chapter on welding plastics andnew sections on welding duplex stainless steel and air plasma cutting.There are two new appendices (one illustrating the latest plant andequipment, and one on refraction). The appendix on proprietary weldinggases has been completely revised.My thanks are due to the following firms for their help and cooperationby supplying much technical information and photographs as indicated:AGA Gas Ltd: Industrial gasesAir Products Ltd, Crewe: special gases and mixtures, welding ofaluminium, stainless and heat resistant steels.Air Products Ltd, Ruabon: welding of aluminium and its alloys,stainless and 9 % nickel steels and plasma cutting.Alcan Wire Ltd: aluminium welding techniques and applications.Alpha Electronics for information on measuring instruments.Aluminium Federation: aluminium and its alloys. Welding techniquesand applications.American Welding Society: welding symbols and classifications.xi
xii
xiii
A. C. Davies
1Manual metal arc welding*
rods to the ve pole, so that they will not burn away too quickly. Heavilycoated rods are connected to the +ve pole because, due to the extra heatrequired to melt the heavy coating, they burn more slowly than the othertypes of rods when carrying the same current. The thicker the electrodeused, the more heat is required to melt it, and thus the more current isrequired. The welding current may vary from 20 to 600 A in manual metalarc welding.When alternating current is used, heat is developed equally at plate androd, since the electrode and plate are changing polarity at the frequency ofthe supply.If a bare wire is used as the electrode it is found that the arc is difficult tocontrol, the arc stream wandering hither and thither over the molten pool.The globules are being exposed to the atmosphere in their travel from therod to the pool and absorption of oxygen and nitrogen takes place evenwhen a short arc is held. The result is that the weld tends to be porous andbrittle.The arc can be rendered easy to control and the absorption ofatmospheric gases reduced to a minimum by 'shielding' the arc. This isdone by covering the electrode with one of the various types of coveringpreviously discussed, and as a result gases such as hydrogen and carbondioxide are released from the covering as it melts and form an envelopearound the arc and molten pool, excluding the atmosphere with its harmfuleffects on the weld metal. Under the heat of the arc chemical compounds inthe electrode covering also react to form a slag which is liquid and lighterthan the molten metal. It rises to the surface, cools and solidifies, forming aprotective covering over the hot metal while cooling and protecting it fromatmospheric effects, and also slows down the cooling rate of the weld. Someslags are self-removing while others have to be lightly chipped (Fig. 1.1).The electrode covering usually melts at a higher temperature than thewire core so that it extends a little beyond the core, concentrating anddirecting the arc stream, making the arc stable and easier to control. Thedifference in controllability when using lightly covered electrodes andvarious medium- and heavily covered electrodes will be quickly noticed bythe operator at a very early stage in practical manual metal arc welding.With bare wire electrodes much metal is lost by volatilization, that isturning into a vapour. The use of covered electrodes reduces this loss.An arc cannot be maintained with a voltage lower than about 14 V and isnot very satisfactory above 45 V. With d.c. sources the voltage can bevaried by a switch or regulator, but with a.c. supply by transformer theopen circuit voltage (OCV) choice is less, being 80 or 100 V on larger units,down to 50 V on small units.
The greater the volts drop across the arc the greater the energy liberatedin heat for a given current.Arc energy is usually expressed in kilojoules per millimetre length of theweld (kJ/mm) andArc energy (kJ/mm) =
The volts drop can be varied by altering the type of gas shield liberated bythe electrode covering, hydrogen giving a higher volts drop than carbondioxide for example. As the length of the arc increases so does the voltagedrop, but since there is an increased resistance in this long arc the current isdecreased. Long arcs are difficult to control and maintain and they lowerthe efficiency of the gas shield because of the greater length. As a result,absorption of oxygen and nitrogen from the atmosphere can take place,resulting in poor mechanical properties of the weld. It is essential that thewelder should keep as short an arc as possible to ensure sound welds.Transference of metal across the arc gapWhen an arc is struck between the electrode and plate, the heatgenerated forms a molten pool in the plate and the electrode begins to meltaway, the metal being transferred from the electrode to the plate. Thetransference takes place whether the electrode is positive or negative andalso when it has a changing polarity, as when used on a.c. Similarly it is
Fig. 1.1. The shielded arc. Manual arc weld on steel base plate with a coveredelectrode.
ELECTRODE COVERING
PENETRATION
BUILD-UP OF WELDMETAL DILUTED WITHPARENT PLA TE METAL
HUH
"' A1
-COVERING
CORE WIRE
m2 g, so that the increase in mass of the plate (i.e. the mass of thedeposited metal) is (m2 mx) g.The stubs have any covering remaining on them removed and areweighed, say ra4 g; thus the mass of metal to be deposited is (mz mj g.The nominal (N) electrode efficiency i?N % is given by:m
or
'2WHEN CORE WIRE ISCENTRALLY PLACED
efficiency, that is enabling more than the core wire weight of metal to bedeposited because of the extra iron powder. Efficiencies of up to 200 % arepossible, this meaning that twice the core wire weight of weld metal isbeing deposited. These electrodes can have coverings of rutile or basictype or a mixture of these. The iron powder ionizes easily, giving asmoother arc with little spatter, and the cup which forms as the core wireburns somewhat more quickly than the covering gives the arc directionalproperties and reduces loss due to metal volatilization. See also Electrodeefficiency (metal recovery and deposition coefficient).Hydrogen-controlled electrodes (basic covered)*If oxygen is present with molten iron or steel a chemical reactionoccurs and the iron combines chemically with the oxygen to form achemical compound, iron oxide. Similarly with nitrogen, iron nitride beingformed if the temperature is high enough as in metal arc welding. Whenhydrogen is present however there is no chemical reaction and thehydrogen simply goes into solution in the steel, its presence being describedas x millilitres of hydrogen in y grams of weld metal.This hydrogen can diffuse out of the iron lattice when in the solid stateresulting in a lowering of the mechanical properties of the weld andincreasing the tendency to cracking. By the use of basic hydrogencontrolled electrodes, and by keeping the electrodes very dry, theabsorption of hydrogen by the weld metal is reduced to a minimum andwelds can be produced that have great resistance to cracking even underconditions of very severe restraint.The coverings of these electrodes are of calcium or other basiccarbonates and fluorspar bonded with sodium or potassium silicate. Whenthe basic carbonate is heated carbon dioxide is given off and provides theshield of protective gas thus:calcium carbonate (limestone) heated - calcium oxide (quicklime) + carbon dioxide.
iron powder form and for welding in all positions. Low and medium alloysteels which normally would require considerable pre-heat if welded withrutile-coated electrodes can be welded with very much less pre-heating, thewelds resisting cracking under severe restraint conditions and also beingvery suitable for welding in sub-zero temperature conditions. By correctstorage and drying of these electrodes the hydrogen content can be reducedto 5 ml/100 g of weld metal for special applications. Details of these dryingmethods are given in the section on storage and drying of electrodes (q.v.).Experiment to illustrate the diffusible hydrogen content in weld metal. Makea run of weld metal about 80 mm long with the metal arc on a small squareof steel plate using an ordinary steel welding rod with a cellulose, rutile oriron oxide coating. Deslag, cool out quickly and dry off with a cloth andplace the steel plate in a beaker or glass jar of paraffin. It will be noted thatminute bubbles of gas stream out of the weld metal and continue to do soeven after some considerable time. If this gas is collected as shown inFig. 1.4 it is found to be hydrogen which has come from the flux covering and the moisture it contains. A steel weld may contain hydrogen dissolved in the weld metal and also in the molecular form in any small voidswhich may be present. Hydrogen in steel produces embrittlement and a reduction in fatigue strength. If a run of one of these hydrogen-controlledelectrodes is made on a test plate and the previous experiment repeated itwill be noted that no hydrogen diffuses out of the weld.Fig. 1.4. Collecting diffusible hydrogen from a mild steel weld.
HYDROGEN
'
PIPETTE
DIFFUSIBLEHYDROGEN'WELD
PARAFFINFUNNELMILD STEELSPECIMEN
10
Slope
Rotation
Symbol
Fig.
FlatHorizontal-verticalVertical-upVertical-downOverhead
0-50-580-9080-900-15
0-1030-900-1800-180115-180
1.51.6
HVDO
1.7a1.7b1.8
Storage of electrodesThe flux coverings on modern electrodes are somewhat porousand absorb moisture to a certain extent. The moisture content (or humidity)of the atmosphere is continually varying and hence the moisture content ofthe covering will be varying. Moisture could be excluded by providing anon-porous covering, but any moisture entrapped would be liable to cause
11
rupture of the coating when the moisture was turned to steam by theheating effect of the passage of the current through the electrode. Cellulosicelectrodes absorb quite an appreciable amount of moisture, and it does notaffect their properties since they function quite well with a moisturecontent. They should not be over-dried or the organic compounds of whichFig. 1.5. Flat position.10'10'
90
SLOPE
90t>SLOPE
180
ROTATION 0 - 1 8 0 *IN BOTH CASES
90 #
ROTATION
SLOPE#
12
they are composed tend to char, affecting the voltage and arc properties.The extruded electrodes with rutile, iron oxide and silicate coatings do notpick up so much moisture from the atmosphere and function quite wellwith a small absorbed content. If they get damp they can be satisfactorilydried out, but it should be noted that if they get excessively wet, rusting ofthe core wire may occur and the coating may break away. In this case theelectrodes should be discarded.Storage temperatures should be about 12 C above that of external airtemperature with 0-60% humidity. Cellulose covered electrodes are not socritical: but they should be protected against condensation and stored in ahumidity of 0-90%.Drying of electrodes. The best drying conditions are when the electrodes areremoved from their package and well spaced out in a drying oven which hasa good circulation of air. Longer drying times are required if the electrodesare not spaced out. The following table gives an indication of temperaturesand times required, but see also the special conditions for drying basicelectrodes (Fig. 1.9).Drying of electrodes: approximate times and temperatures with electrodesspaced apart. Times will vary with air circulation, electrode spacing and ovenloading
Electrode type
Diametermm
TemperatureC
1.6-2.53.2-5.06.0-10.02.5-6.0
110110110110
Time in minsair circulationgood poor10-3020-4530-6010-15
20-3030-6045-12015-20
13
out in the drying oven, the drying time and temperature depending uponthe permissible volume of hydrogen in the weld deposit. Suggested figuresare given in the following table.Hydrogen contentin millilitres of hydrogenper 100 grams of weld metal
TemperatureTimeCminutes
10-15 ml H 2 /100g
150
60
5-10mlH 2 /100g
200
below 5 ml H 2 /100 g
450
UseTo give resistance to HAZ crackingin thick sections of mild steel, highrestraint.High quality welds in pressurevessel and structural applications.Thick sections to avoid lamellartearing and critical applications.
Maximum time
150C250C450C
72 hours12 hours2 hours
14
Electrode classification
15
E4322RR
21
STC codeArc welding electrodeStrength 430-550 N/mm 2 (Table 1)Temperature for minimum average impact strength of 28 J, 0 C(Table 2)Temperature for minimum average impact strength of 47 J, 0 C(Table 3)Covering, rutile heavy coated (see list of coverings)Additional codeWelding position: all positions except vertical/down (see list of weldingpositions)Welding current and voltage: a.c, 50 V; d.c. electrode + / - (Table 4)
16
E5154R
12010H
STC codeArc welding electrodeStrength 510-650 N/mm 2 (Table 1)Temperature for minimum average impact strength of 28 J, 40 C(Table 2)Temperature for minimum average impact strength of 47 J, 30 C(Table 3)Covering, basic (see list of coverings)Additional codeEfficiencyWelding position: all positions (see list of welding positions)Welding current and voltage: polarity d.c. as recommended by makersNot suitable for use on a.c. (Table 4)Hydrogen controlled
Example 3Complete classification of electrode considered E 51 5 3 BB (160 3 6 H)
E5153BB
16036H
STC codeArc welding electrodeStrength 510-650 N/mm 2 (Table 1)Temperature for minimum average impact strength of 28 J, 40 C(Table 2)Temperature for minimum average impact strength of 47 J, 20 C(Table 3)Covering, basic, high efficiency (see list of coverings)Additional codeEfficiencyWelding position: flat and for fillets, horizontal/vertical (see list ofwelding positions)Welding current and voltage: a.c, 70 V; d.c. electrode + (Table 4)Hydrogen controlled
17
^1
So
Sc
'5b .22
"5b .22
W *55
C ^^
TJ J^
'^'S
^ ^
S -S
HZ
2 to
^H
330360
2018
<D
430-550510-650
E43E51
--
012345
2218
it
2420
18
EEEEEEEEF,
not specified+200-20-30-40-50-60-70
---
- 0 - 1 - 2 - 3 4 - 5 - 6 - 7 - 8 -
Alternating currentminimum open circuitvoltage, V
polarity as recommendedby the manufacturer
123
+ or +
505050
456
+ or 4-
707070
789
808080
Digit
Composition of covering
Characteristics
C cellulosic
B basic
BB basic highefficiency
These electrodes are suitable for welding in the flat and horizontal/vertical position with a greatly increased rate of metal deposition. Theirhigh efficiency covering makes them unsuitable for welding in thevertical and overhead positions. They can be used either a.c. or d.c,generally with electrode +ve. Efficiency is indicated by a three-figuredigit beginning the additional coding.
Class
R rutile
RR rutile heavycoating
Easy to use, with a smooth weld finish and medium penetration. Highlevel of hydrogen in the weld metal limits their use in thick sections orrestrained joints. Suitable for a.c. or d.c; the fast freezing of weldmetal and fluid slag makes them suitable for vertical and overheadwelding.Similar characteristics to rutile electrodes but generally unsuitable forvertical and overhead welding because of increased slag. Increased rateof metal deposition. Efficiency is indicated by a three-figure digitbeginning the additional coding.
S other types
This class includes electrodes that do not fall into any of the previousclasses. They range from little used types, such as those with acidcovering (containing oxides and carbonates of lime and manganesewith deoxidizers such as ferromanganese), to the oxide types(containing iron oxide with or without manganese oxide and silicates).This class also includes any newly developed flux systems.Manufacturer's advice should be followed when using them.
AWSclassification
Type of covering
Capable of producingsatisfactory welds inposition shown"
HighHighHighHighHighHighHigh
F, V, OH, HF, V, OH, HF, V, OH, HF, V, OH, HH-filletsFH-fillets, F
DCEPAC or DCEPAC or DCENorororor
F, V, OH, HF, V, OH, HF, V, OH, HF, V, OH, HH-fillets, FH-fillets, FH-fillets, FF, OH, H, V-down
AC orDCEPAC orAC orAC orAC orAC orAC or
cellulose sodiumcellulose potassiumtitania sodiumtitania potassiumiron oxideiron oxideiron oxide, iron powder
Type of current*
ACACACAC
DCEPDCEPDC, either polarityDCENDCEPDCEP
Note the American use of AC and DC for alternating current and direct current.aF = flat, H = horizontal, H-fillets = horizontal fillets, V-down = vertical down.V = vertical ^, . for electrodes 3/16 in and under, except 5/32 in and under for classifications E7014, E7015, E7016, E7018.^ TTvOH = overhead j''bDCEP direct current electrode positive (DC reverse polarity). DCEN direct current electrode negative (DC straight polarity).cE6022 classification electrodes are for single-pass welds.
22
Welders' accessories
23
Example 2E7018: Electrode with weld metal of tensile strength 70 ksi, with basiccovering, iron powder, low hydrogen. Bonded with potassium silicate F, V, OH,H, AC or DCEP.Core wire for all electrodes in this specification is usually of composition0.10% carbon, 0.45% manganese, 0.03% sulphur, 0.02% phosphorusand 0.01 % silicon.
24
25
12, 13, 14/EW.* The choice of the correct filter is the safeguard againsteye damage. Occasional accidental exposure to direct or reflected raysmay result in the condition known as arc flash. This causes no permanentdamage but is painful, with a feeling of sand in the eyes accompanied by* Many headshields are now fitted with light-reactant lenses, leaving both hands free. Thenormal view that the welder has before welding is quite clear. Upon the arc being struck,the lens darkens to the shade previously selected, the time lag being of the order of0.001-0.0015 sec.
26
watering. Bathing the eyes with eye lotion and wearing dark glasses reducesthe discomfort and the condition usually passes with no adverse effects infrom 12 to 24 hours. If it persists a doctor should be consulted.A lens of this type is expensive and is protected from metallic spatter onboth sides by plain glass, which should be renewed from time to time, as itbecomes opaque and uncleanable, due to spatter and fumes.The welding area must be adequately screened so that other personnelare not affected by rays from the arc.The eyes must also be protected against foreign bodies such as particlesof dust and metal, which are all potential dangers in the welding shop.Spectacles with clear or tinted lenses are available and also fit overnormal spectacles if required. For use particularly on grinding operationsthere are clear goggles and there are also face shields with plain or tintedvisors which fit on the head like a welding head mask but have the shieldhinged so that it is easily raised when required. For conditions where thereis much noise there are hearing protectors which fit snugly over the ears inthe same way as radio headphones. There are also ear plugs which are madein a soft foam and which are easily inserted, and are very effective.Protection against inhalation of polluted atmosphere is given by singlecartridge dust respirators and various types of moulded plastic masks withadjustable headbands in which the filter is replaceable. A protective cap isalso available with a hard shell, foam lining and elastic grip giving goodfitting to the head.Leather or skin aprons are excellent protection for the clothes againstsparks and molten metal. Trouser clips are worn to prevent molten metallodging in the turn-ups, and great care should be taken that no metal candrop inside the shoe, as very bad burns can result before the metal can beremoved. Leather spats are worn to prevent this. Gauntlet gloves are wornfor the same reason, especially in vertical and overhead welding. In weldingin confined spaces, the welder should be fully protected, so that his clothescannot take fire due to molten metal falling on him, otherwise he may bebadly burnt before he can be extracted from the confined space.The welding bench in the welding shop should have a flat top of steelplate, about 1.5 m x 0.75 m being a handy size. On one end a vice shouldbe fitted, while a small insulated hook on which to hang the electrodeholder when not in use is very handy.Jigs and fixturesThese are a great aid to the rapid setting up of parts and holdingthem in position for welding. In the case of repetition work they areessential equipment for economical working. Any device used in this way
27
comes under this heading, and jigs and fixtures of all types can be builteasily, quickly and economically by arc welding. They are of convenience tothe welder, reduce the cost of the operation, and standardize and increasethe accuracy of fabrication.Jigs may be regarded as specialized devices which enable the parts beingwelded to be easily and rapidly set up, held and positioned. They should berigid and strong since they have to stand contractional stresses withoutdeforming unless this is required; simple to operate, yet they must beaccurate. Their design must be such that it is not possible to put the work inthem the wrong way, and any parts of them which have to stand continualwear should be faced with wear-resistant material. In some cases, as in inertgas welding (q.v.), the jig is used as a means of directing the inert gas on tothe underside of the weld (backpurge) and jigs may also incorporate abacking strip.Fixtures are of a more general character and not so specialized as jigs.They may include rollers, clamps, wedges, etc., used for convenience inmanipulation of the work. Universal fixtures are now available, and thesegreatly reduce the amount of time of handling of the parts to be welded andcan be adapted to suit most types of work.Manipulators, positioners, columns and boomsPositioners are appliances which enable work to be moved easily,quickly and accurately into any desired position for welding - generally inthe downhand position since this speeds up production by making weldingeasier, and is safer than crane handling. Universal positioners are mountedon trunions or rockers and can vary in size from quite small bench types tovery large ones with a capacity of several tons. Manually operated types aregenerally operated through a worm gearing with safety locks to preventundesired movement after positioning. The larger types are motor-driven,and on the types fitted with a table, for example, the work can be swungthrough any angle, rotated, and moved up and down so that if required itcan be positioned under a welding head.As automatic welding has become more and more important so has thedesign of positioners and rollers improved. Welding-columns and boomsmay be fixed or wheel mounted and have the automatic welding headmounted on a horizontal boom which can slide up and down a verticalcolumn. The column can be swivel mounted to rotate through 360 and canbe locked in any position. In the positioning ram-type boom there ishorizontal and vertical movement of the boom carrying the welding headand they are used for positioning the head over work which moves beneaththem at welding speed. In the manipulating ram-type boom, the boom is
. v
30Fig. 1.12.
31
Nominal length, mm
1.6
200250200250300350250300350350450350450500600700900
2.0
2.5
Electrode diametermminch1.62.02.53.03.24.05.06.06.38.0
0.060.080.100.120.130.160.190.230.250.32
Nearest fractionalequivalent, in._5_64_2_32
32164__16
32
Protection of the skin and eyes. Welding gloves should be worn andno part of the body should be exposed to the rays from the arc otherwiseburning will result. Filter glasses (p. 23) should be chosen according to BSrecommendations. Where there are alternatives the lower shade numbersshould be used in bright light or out of doors and the higher shade numbersfor use in dark surroundings.Do not weld in positions where other personnel may receive direct orreflected radiation. Use screens. If possible do not weld in buildings withlight coloured walls (white) as this increases the reflected light andintroduces greater eye strain.Do not chip or deslag metal unless glasses are worn.Do not weld while standing on a damp floor. Use boards.Switch off apparatus when not in use.Make sure that welding return leads make good contact, thus improvingwelding conditions and reduced fire risk.Avoid having inflammable materials in the welding shop.Degreasing, using chemical compounds such as trichlorethylene, perchlorethylene, carbon tetrachloride or methyl chloride, should be carriedout away from welding operations, and the chemical allowed to evaporatecompletely from the surface of the component before beginning welding.The first-named compound gives off a poisonous gas, phosgene, whenheated or subjected to ultra-violet radiation, and should be used with care.Special precautions should be taken before entering or commencing anywelding operations on tanks which have contained inflammable orpoisonous liquids, because of the risk of explosion or suffocation. Thestudent is advised to study the following publications of the Department ofEmployment (SHW-Safety, health and welfare):SHW 386. Explosions in drums and tanks following welding andcutting. HMSO.SHW Booklet 32. Repair of drums and tanks. Explosions and firerisks. HMSO.SHW Booklet 38. Electric arc welding. HMSO.Memo No 814. Explosions - Stills and tanks. HMSO.Technical data notes No. 18. Repair and demolition of large storagetanks. No. 2. Threshold limit values. HMSO.Health and safety in welding and allied processes. The Welding
Institute.Filters for
Institution.Protection for eyes, face and neck. BS 1542. British Standards
Institution.
33
34
Min.
Max.
Average
1.62.02.53.24.05.06.06.38.0
25345060100150200215250
456590130180250310350500
405090115140200280300350
Current (amperes)
START
PLATE
35
CORRECTBEAD
HEAPED UPBEAD PROFILEPOOR PENETRA TIONCURRENT TOO LOW
FLATTENEDBEAD PROFILECURRENT TOO HIGH
36
electrode, the end of the bead and the crater must be deslagged and brushedclean and the arc struck at the forward end of the crater. The electrode isthen quickly moved to the rear end and the bead continued, so that nointerruption can be detected (Fig. 1.14&). This should be practised until nodiscontinuity in the finished bead can be observed. Since in welding longruns, the welder may have to change rods many times, the importance ofthis exercise will be appreciated, otherwise a weakness or irregularity wouldexist whenever the welding operation was stopped.Beads can now be laid welding away from the operator and also weldingfrom left to right or right to left. A figure-of-eight about 120 mm longprovides good practice in this and in changing direction of the bead whenwelding. The bead should be laid continuously around the figure.A transformer unit usually has two voltage settings, one 80 open circuitvolts and the other 100 OCV, the latter being used for thinner sheet whenthe current setting is low. Other sets may have lower OCV's, the figurerequired generally being given on the electrode packet. With an a.c. voltssetting of 80 V the current setting for a given electrode can be varied from alow value, giving poor penetration and a shallow crater, with the metalheaping up on the plate producing overlap, to a high value, giving anexcessively deep crater, too much penetration with a fierce hissing and notwell controllable arc, much spatter, and a flat bead with undercut and anoverheated electrode. Intermediate between these extreme values is acorrect value of current, say 115-125 A for a 3.2 mm electrode. There isgood penetration, the metal flows well, the arc is controllable with nospatter or undercut, and the arc sound is a steady crackle.These results are tabulated below. If a d.c. set is being used with a voltagecontrol this also can be varied for the operator to find out the effect of thiscontrol.
Fig. 1.14 (b) Arc struck in front of crater and moved back to continue the runpreserves weld profile and helps eliminate any start porosity.
DRAWDIRECTION OFWELDINGI
I I /STRIKEI
37
Welding circuit
Effect
wvwwvw(a)
NORMAL
(b)
(c)THIS PRODUCES DEEP PENETRATIONAND REINFORCEMENT ON THESE LINES
nsmmr(d)
38
resisting steels. Fig. 1.15d is a weave that is useful when running horizontalbeads on a vertical plane, since by the hesitating movement at the side of thebead, the metal may be heaped up as required. The longer the period ofhesitation at any point in a weave, the more metal will be deposited at thispoint.Weaving should be practised until the bead laid down has an evensurface with evenly spaced ripples. The width of the weave can be varied,resulting in a narrow or wide bead as required.Padding and building up shaftsThis exercise provides a good test of continued accuracy in laying aweld. A plate of 8-9.5 mm mild steel about 150 mm square is chosen and aseries of parallel beads are laid side by side across the surface of the plateand so as to almost half overlap each other. If the beads are laid side by sidewith no overlap, slag becomes entrapped in the line where the beads meet,being difficult to remove and causing blowholes (Fig. 1.16). Each bead is
Fig. 1.16SLAG TENDS TO GETENTRAPPED HERE/^^sg^>1^^NL\
Fig. 1.17
FIRST LAYERSECOND LA YER
39
deslagged before the next is laid. The result is a build-up layer of weldmetal.After thoroughly cleaning and brushing all slag and impurities from thislayer, another layer is deposited on top of this with the heads at right anglesto those of the first layer (Fig. 1.17), or they may be laid in the samedirection as those of the first layer. This can be continued for several layers,and the finished pad can then be sawn through and the section etched, whendefects such as entrapped slag and blowholes can at once be seen.Odd lengths of steel pipe, about 6 mm or more thick, may be used for thenext exercise, which again consists in building up layers as before. Thebeads should be welded on opposite diameters to prevent distortion(Fig. 1.18a). After building up two or more layers, the pipe can be turneddown on the lathe and the deposit examined for closeness of texture andabsence of slag and blowholes. Let each bead overlap the one next to it asthis greatly reduces the liability of pin-holes in the finished deposit.The same method is adopted in building up worn shafts and a weld maybe run around the ends as shown to finish the deposit. Another methodsometimes used consists of mounting the shaft on V blocks and weldingspirally (Fig. 1.18a and b).Tack welding
40
stresses set up in the welding process. The tack welds should be deslaggedand examined for cracks, which may occur because of the rapid cooling ofthe tack weld if there is no pre-heat. If any cracks are found they should begouged or ground out and the tack weld remade. Cracks left in may causecracking in the finished weld.Thicker plate may need stronger tack welds. These should be made intwo runs, the second tack weld being made after the first has been deslaggedand examined. Remember when making the first run that the tack weldmust be fused into the run so that there is no evidence of the tack weld. Thismay mean welding at a slightly increased rate at these points. Tack weldsare often made by the TIG process in fabrication of plate and pipe work forlining up and then welded by the MIG process.Plates set up for fillet welding should have the tack welds made at abouttwice the frequency of pitch used for butt welds.The operator should now be able to proceed to the making of weldedjoints, and it will be well to consider first of all the method of preparation ofplates of various thicknesses for butt welding. Although a U preparationmay prove to be more expensive than a V preparation, it requires less weldmetal and distortion will be lessened. For thicker sections the split-weave orstringer bead technique is often used (Fig. 1.21) since the stresses due tocontraction are less with this method than with a wide weave.When a weld is made on a plate inclined at not more than 5 to thehorizontal, this is termed the flat position, and wherever possible weldingshould be done in this position, since it is the easiest from the welder's pointof view.Fig. 1.19 shows some simple welding joints.Butt welding in the flat positionJoints are prepared with an included angle of 60 with root faceand root gap as required for the plate thickness. (An angle of 60 is chosenbecause it combines accessibility to the bottom of the joint with the leastamount of weld metal (Fig. 1.21).)The plates can be tack welded in position to prevent movement due toexpansion and contraction during welding and the tack welds must bestrong enough to prevent movement of the plates. Using say a 4 mmelectrode with about 125-135 A for a 3 mm gap and 160-170 A for a 1.5 mmgap the welds are kept to about 3-3.5 mm thickness. The length of the rundepends upon the size of the electrode and the width of the weld, which getsgreater as the joint is filled up. To avoid having the top deposits in thickplate too wide, the stringer or split-weave method is used. If the plates are tobe welded from one side only, the penetration must be right through to the
41
bottom of the V and the underbead must be continuous along the length ofthe joint (Fig. 1.20). If a sealing run is to be made the underside of the jointshould be back chipped (by electrically or pneumatically operated chippinghammer) so that any defects such as inclusions, porosity, etc., are removedand a sealing run is then made, using a rod about 5 mm diameter.In many cases the joint to be welded is accessible from one side only, sothat the penetration bead cannot be examined for defects and it is notpossible to employ a sealing run. In this case a backing bar can be used. Theplates are prepared to a sharp edge and the backing bar, usually about25 mm wide and 5 mm thick, is tack welded to one plate and the plates setapart to the required gap. The first run is made with a higher current thanpreviously used as there is no possibility of burn through. This ensures thatthe roots of the parent plate and the backing bar are well fused together,and the other runs are then made, as previously, with lower current.Double-V butt joint preparation is often used with thicker plate becauseFig. 1.19. Simple welding joints.
EDGE
THINNER SECTIONS
PREPARED BUTT
FILLET IN FLATPOSITION(INSIDE CORNER)
CORNER THROAT OFWELD MUST BEEQUAL TO THE PLATETHICKNESS
LAP
42
of the saving in weld metal, which in the case of a 19 mm (|") plate is abouthalf of that required for single-V preparation. The plates are prepared to asharp edge (Fig. 1.21) and the first run made with little or no weave andabsolutely continuous. The plates are turned over, the joint root deslagged,after which the next run is made on to the root of the first run, ensuring thatthere is no entrapped slag or porosity in the centre of the joint. Theremaining runs can be made on alternate sides of the joint where possible,reducing the distortional stresses.Butt welds on pipes provide good exercise in arc manipulation. The pipesare prepared in the same way as for plates by V'ing. They are then lined upin a clamp, or are lined up and tack welded in position and then placedacross two V blocks.Right angle outside corner jointsTack weld two 12.5 mm (j in.) steel plates together with a 2 mmgap between them and an angle of 90 between the plates (Fig. 1.22),making a right angled corner joint. With an electrode of 4 mm diameter andFig. 1.20PROFILE1
OVERFILL*
L^TOEOFWELD//
NOBLOWHOLES%-~POROSITY ORVINCLUSIONS\ G
V NO UNDERCUTNO OVERLAP
v'/rOOD<r c?SinMA
FUSI0N
p / 7
Qf
T LACKJ)^
Y~^~\r/^
SOUDIHCATION)\ ^ > / L A C K OF INTER-RUNBLOWHOLES (LARGE^JiPENETRATIONGAS CA VITIES)V = * LACK 0F SIDE FUSIONINCLUSIONS
LACKOFROOTPENETRATIONIMPERFECTIONS IN A WELD
(b)The BS term is ' excess weld metal' but the term ' overfill' is now used because in certaincircumstances, such as under fatigue loading, excess weld metal (or overfill) is detrimentato the weld.
43
about 160 A current make a run about 180 mm long keeping the electrodeat an angle of about 60 and ensuring that penetration is adequate but notexcessive. The speed of welding should be increased where the tack weldsoccur to ensure the uniform appearance of the upper side of the weid.Deslag upper and underside of the joint and observe that correctpenetration has been achieved. Then make the second (and subsequent)runs with an electrode angle of about 70-75 using a slight weave andavoiding any undercut. Deslagging is followed by the final run to obtain thecorrect throat thickness and profile as shown. A sealing run can be made ifrequired on the underside of the joint using a somewhat higher current.
UP TO 3 mm THICKNESS ( f )CLOSE BUTT
ROOT FACE
ROOT GAP
60-70
SPLIT WEAVE
^TACKBACKING BAR'USE OF BACKING BAR
WELDS
.GAP 3.2 mmEQUAL DOUBLE VPREPARATIONWITH GAPTHICKNESS 20-28 mm ( i - 1 f )
3 mm MAX3.2 mmSINGL EUWITH GAPTHICKNESS 25 mm AND ABO VE
44
NO UNDERCUTNO SLAG INCLUSIONS
PENETRATIONTHROA T THICKNESS EQUALS PLA TE THICKNESS
PENETRATIONINTO CORNER
45
Filletleg length (mm)
3.25 (j in.)4.06.0 (i in.)
456.0
300(12 in.)300300
46
Too long a length of run gives lack of root fusion and too small leg length.Too short a length of weld causes excessive undercut and uncontrolled slagtrouble. Root penetration (Figs. 1.26Jand 1.27) is essential, and avoid theother faults shown.A lap joint is a particular case of a fillet weld. Take care not to causebreaking away of the edges as shown (Fig. 1.25). Fig. 1.26a, b and c showsvarious types of fillet welds while Fig. 1.26e shows profiles and definitionsof leg and throat.Fig. 1.25. Lap joint.DO NOT BREAK' AWAY EDGES
LFig. 1.26. Horizontal-vertical fillet welds, (a) Double fillet, no preparation, (b)Prepared fillet, welded one side only, (c) Multi-run fillet, equal leg length, (d)Faults in horizontal-vertical fillet welds, (e) Weld profiles.
\(a)
"S
(0
LACK OF ROOTPENETRATION(d)
MITRE PROFILETHROAT
UNDERCUTUNEQUALLEG LENGTHOVERLAP(NOTCH)
CONVEX PROFILE\ROOT
CONCAVE PROFILE(e)
POORFUSION
47
48
are generally used, and special rods having light coatings to reducedifficulties with slag are available. Vertical beads should first be run on mildsteel plate, the electrode being held at 75-90 to the plate (Fig. 1.28).Downward welding produces a concave bead, and is generally used forlighter runs, since a heavy deposit cannot be laid. If it is, the metal will notfreeze immediately it is deposited on the plate, and will drop and run downthe plate. This method is, therefore, usually only used as a finishing orwashing run over an upward weld because of its neat appearance, or forthin sections.Fig. 1.28
112 mm
* PAUSEVERTICAL UP
Fig. 1.29
2.5 mm GAP
UPWARD WELDELECTRODE BISECTS ANGLEBETWEEN PL A TES ANDINCLINED 75 TO LINEOF TRA VELWEAVE AS IN FIG. 1.28
VERTICAL BUTT
ELECTRODE INCLINED75-80 TO LINE OF TRA VEL
49
ELECTRODE MAKES ANANGLE OF 10 WITHWELD LINE
50
FIRST RUN 80SUBSEQUENT RUNS 6045/ \BOTH SIDES
51
because of the short arc, the electrode persists in sticking, raise the current alittle, and avoid undercutting of the upper plate (Fig. 1.32/?).Aluminium and aluminium alloys
. , \
32mmGAP
ELECTRODE ANGLE30-35 WITH VERTICAL PLATE70 WITH LINE OF WELD
52
Preparation. Fig. 1.33 shows the preparation for various sheet thicknesses.Tack welds, jigs, or other clamps should be used to position the work andtack welding should be done at very frequent intervals, then deslagged andsmoothed before welding commences. The thermal expansion is abouttwice that of mild steel so allowance must be made accordingly. Moltenaluminium absorbs hydrogen and this results in porosity so that preheating the work and making sure that the electrodes are kept dry andheating to 130-160C prevents this.The table shows the more generally welded alloys. The electrodes usedare of the 10-12% silicon type, so that if heat treatable alloys are welded theheat treatment is lost and the alloy needs heat treatment again. TheAl-Si electrode does not have the same mechanical properties as the parentplate in every case, and it should be remembered that the higher Al-Mgalloys are not satisfactorily arc welded. Aluminium and the workhardening Al-Mg alloys are now fabricated by the TIG and MIG processes(q.v.).ElectrodesAluminium-10% Si
Material examplesPure aluminium, 5251 (N4), 6063 (H9), 6061 (H20),6082 (H30),Castings LM18, LM6, LM8, LM9, LM20.
Technique. The rod is connected to the positive pole of a d.c. supply, and thearc struck by scratching action, as explained for mild steel. It will be foundthat, as a layer of flux generally forms over the end of the rod, it has to bestruck very hard to start the arc. The rod is held at right angles to the workand a short arc must be held (Fig. 1.34), keeping the end pushed down intothe molten pool. This short arc, together with the shielding action of thecoating of the rod, reduces oxidation to a minimum. A long arc will resultin a weak, brittle weld. No weaving need be performed, and the rate ofFig. 1.33. Preparation of aluminium.
,5ly
<
r60 VPREPARATIONROOT GAP 1.6-3.2 mmROOT FACE 4 - 5 mmPRE-HEAT 100-300 cC
53
welding must be uniform. As the metal warms up, the speed of weldingmust be increased.Castings are welded in the same way after preparation, but owing to theirlarger mass, care must be taken to get good fusion right down into theparent metal, since if the arc is held for too short a time on a given portionof the weld the deposited aluminium is merely 'stuck' on the surface as abead with no fusion. This is a very common fault. Castings should be preheated to 200C to reduce the cracking tendency and to make weldingeasier.Lap joints and fillet joints should be avoided since they tend to trapcorrosive flux, where it cannot be removed by cleaning. Fillet welds areperformed with no weave and with the rod bisecting the angle between theplates.After treatment. The flux is very corrosive and the weld must be thoroughlywashed and brushed in hot water after it has cooled out. Immersion in a 5%solution of nitric acid in water is an even better method of removing theflux, this being followed by brushing and washing in hot water.Cast ironThe following types of electrode are in general use for the weldingof cast iron.(1) Mild steel, low carbon, basic coated (low hydrogen), electrode d.c.+ ve, a.c. 40 OCV.(2) Nickel cored, electrode d.c. + ve, a.c. 40 OCV.(3) MONEL nickel-copper alloy* cored electrode, d.c. + ve, a.c.40 OCV.f(4) Nickel iron cored electrode, d.c. - v e , a.c. 40 OCV.(1) When steel-based weld metal is deposited on cold cast iron, quickcooling results, due to the large mass of cold metal near the weld. This quickFig. 1.34. Aluminium welding.
90SHORT ARC. NO WEAVE,ELECTRODE ALMOST'TOUCHING POOL
* MONEL, INCOLOY, INCONEL, etc. are trademarks of the Inco family of companies.f See table, p. 71.
54
cooling results in much of the carbon in an area adjacent to the weld beingretained in the combined form (cementite) and thus a hardened zone existsnear the weld. In addition, the steel weld metal absorbs carbon and thequick cooling causes this to harden also. As a result welds made with thistype of rod have hard zones and cannot always be machined.If, however, there can be pre-heat to about 500-600 C followed by slowcooling the deposit may produce machinable welds. In many cases,however, machining is not necessary, thus this drawback is no disadvantage. The weld is strong and electrodes of about 3.2 mm diameter aregenerally used with a low current which introduces a minimum of heat intothe work.(2) The nickel cored electrode may be used on cast iron without any preheating and it gives a deposit that is easily machinable with easy deslagging.It can be used in all positions and is used for buttering layers.(3) The MONEL alloy cored electrode is easy to deposit on cold castiron and is again easily machinable. Nickel and MONEL alloy electrodeshave reduced carbon pick-up and thus a reduced hardening effect, butpre-heating should be done with castings of complicated shape, followedby slow cooling though, with care, even a complicated casting may bewelded satisfactorily without pre-heat if the welding is performed slowly.The lower the heat input the less the hardening effect in the HAZ.(4) Electrodes which deposit nickel-iron alloy are generally used wherehigh strength is required, as for example with the SG irons.In the repair of cast iron using high nickel electrodes the weld metal isstrong and ductile.. The electrode coating has a high carbon content andgives up to If % carbon, as graphite, in the weld. The carbon has a lowsolubility in the nickel and excess carbon appears in the weld, increasingweld volume and reducing shrinkage. Pre-heating may be done wheneverthe casting is of complicated shape and liable to fracture easily, though,with care, even a complicated casting may be welded satisfactorily withoutpre-heating if the welding is done slowly.Nickel alloy electrodes are also used for the welding of SG cast irons, butthe heat input will affect the pearlitic and ferritic structures in the heataffected zone, precipitating eutectic carbide and martensite in a narrowzone at the weld interface even with slow cooling. For increased strength,annealing or normalizing should be carried out after welding. The lowerthe heat input the less the hardening effect in the HAZ. See table, p. 71,for suitable electrodes.Preparation. Cracks in thin castings should be \Td or, better still, U 'd, as forexample with a bull-nosed chisel. Thicker castings should be prepared with
55
a single V below 9.5 mm thick and a double U above this. Studding (q.v.)can be recommended for thicker sections and the surrounding metal shouldbe thoroughly cleaned. The polarity of the electrode depends on theelectrode being used and the maker's instructions should be followed,though with d.c. it is generally 4 ve. With a.c. an OCV of 80 V is required.Since the heat in the work must be kept to a minimum, a small-gaugeelectrode, with the lowest current setting that will give sufficient penetration, should be used. A 3.2 mm rod with 70 to 90 A is very suitable formany classes of work. Thick rods with correspondingly heavier currentsmay be used, but are only advisable in cases where there is no danger ofcracking. Full considerations of the effect of expansion and contractionmust be given to each particular job.Technique. The rod is held as for mild steel, and a slight weave can be usedas required. Short beads of about 50 to 60 mm should be run. If longerbeads are deposited, cracking will occur unless the casting is of the simplestshape. In the case of a long weld the welding can be done by the skipmethod, since this will reduce the period of waiting for the section welded tocool. It may be found that with steel base rods, welding fairly thin sections,fine cracks often appear down the centre of the weld on cooling. This canoften be prevented, and the weld greatly improved, by peening the weldimmediately after depositing a run with quick light blows with a ball-panedhammer. If cracks do appear a further light w stitching' run will seal them.Remember that the cooler the casting is kept, the less will be the risk ofcracking, and the better the result. Therefore take time and'let each beadcool before laying another. The weld should be cool enough for the hand tobe held on it before proceeding with the next bead. In welding a deep V, laya deposit on the sides of the V first and follow up by filling in the centre ofthe V. This reduces risk of cracking. If the weld has been prepared bystudding (q.v.), take care that the studs are fused well into the parent metal.In depositing non-ferrous rods, the welding is performed in the sameway, holding a short arc and welding slowly. Too fast a welding speedresults in porosity. In many cases a nickel-copper rod may be depositedfirst on the cast iron and then a steel base rod used to complete the weld.The nickel-copper rod deposit prevents the absorption of carbon into theweld metal and makes the resulting weld softer. Where a soft deposit isrequired on the surface of the weld for machining purposes, the weld maybe made in the ordinary way with a steel base rod and the final top runs witha non-ferrous rod. The steel base rod often gives a weld which has hardspots in it that can only be ground down, hence this weld can never becompletely guaranteed machinable.
56
CD
CDCD
TOPOFPLATE
CASTING
GEAR TOOTH
BOTTOM OF V
i/\\
57
If the weld must have the same characteristics as the parent metal,as for example for electrical conductivity, great difficulty is encounteredwith the welding of copper by the MMA process because the weld is veryporous and unsatisfactory and the TIG and MIG processes should bechosen. Similarly for brass but with the use of an alloy electrode of bronze(about 80% copper, 20% tin or similar) welding can be satisfactorily carriedout on most of the copper alloys with certain exceptions. Welding isperformed with d.c. and the electrode positive.Copper, copper-tin (bronze) and copper-zinc (brass) have a muchgreater coefficient of thermal conductivity than mild steel and the thermalexpansion is also greater so that more heat is required in the weldingprocess, so that it is almost imperative to pre-heat except with the smallestsections, and since tack welds lose their strength at elevated temperatures,line up of the parts to be welded should be with clamps, jigs or fixtures, anddue allowance made for expansion and contraction during and afterwelding. In general, great care must be taken to avoid porosity due to thepresence of gas which is expelled on solidification. Stress relief (post weld)can be carried out on the work hardening alloys to about 250-300 CCopper. Tough pitch copper should not be welded as the weld is alwaysporous. Phosphorus deoxidized copper is satisfactorily welded but theweld, made with a rod of copper-tin (bronze) will not have the sameproperties as the parent plate. Pre-heating is up to 250C.Bronze. The tin bronzes up to about 9% Sn are weldable, but those withhigher tin content are not welded due to solidification cracking and any alloywith more than 0.5% Pb is usually not welded.Brasses. These are alloyed mostly with zinc and those with single-phasecomposition, as for example cartridge brass (70% Cu, 30% Zn) and thosewith up to about 37% Zn, are weldable, but yellow or Muntz metal (60%Cu, 40% Zn) and manganese bronze (58% Cu, 38% Zn, rem, Mn, Fe, Ni orSn) really need pre-heat to about 450 C.Preparation. Plates below 3 mm thickness need no preparation, but abovethis they are prepared as for mild steel with a 60 V and the surfacesthoroughly cleaned. The work must be supported during welding. Sections
58
59
The surface should be ground all over and loose or frittered metalremoved. Because of the danger of cracking, large areas should be dividedup and the welding done in skipped sections so that the heat is distributedas evenly as possible over the whole area. Sharp corners should be roundedand thick deposits should be avoided as they tend to splinter or spall. The
Type(R - rutile)(B - basic)(T - tubular)
Hardening
HV
Use
pearlitic P
Cr-Mn
air
250
martensitic R
350
martensitic Rmartensitic B
Cr-Mn-MoCr-Mo-V
airair
650700
martensitic B
800
austenitic B
Cr-Mo-Ni
work
250500
Cr-Ni-W-B
work(slight)
450500170500300480
13% Mn
austenitic T
non-ferrous B
Co-Cr-W
630
austenitic Tmatrixnon-ferrous Tmatrix
Chromium-carbide-Mntungsten-carbide
560 matrix1400 carbides600 matrix1800 carbides
Abrasion(H - high)(M - medium) ImpactM
HH
MM
61
62
VTOOL PRIOR TO DEPOSIT
READY FOR
GRINDING
63
results are also obtained with covered rods when using d.c, since thedeposit is closer grained and the arc more stable.Covered rods can be obtained or bare rods may be fluxed with a coveringof equal parts bf calcium carbonate (chalk), silica flour and either borax orsodium carbonate (baking soda), mixed with shellac as a binder. Coatedelectrodes give a gas shield which protects the molten metal from oxidationin the welding process and provides a protective slag over the metal whencooling. The deposit resists heat, abrasion, impact, corrosion, galling,oxidation, thermal shock and cavitation erosion to varying degreesdepending upon the alloy. Types of Stellite alloys available are:No. 1. 2.5% C, resistant to abrasion and solid particle erosion,slightly reduces toughness. Used for screw components and pumpsleeves. 46 C (Rockwell).No. 6. Most generally useful cobalt alloy, 1% C, 28% Cr, 4% W,rem. Co. Excellent resistance to mechanical and chemical actionover a wide temperature range. Widely used as valve seat materialas it has high temperature hardness and high resistance to cavityerosion.No. 12. Very similar to alloy No. 6 but with higher hardness. Usedfor cutting edge in carpet, plastics, paper and chemical industries.40 C.No. 21. Low carbon, Co-Cr alloy with molybdenum. Has hightemperature strength, resistant to cavitation erosion, corrosionand galling. Used for hot die material, fluid valve seat facing.No. 238. Co-Fe-Cr-Mo alloy, low carbon. Has excellent resistance to mechanical and thermal shock with good hot hardness.No. 2006. Low cobalt alternative to No. 6 to which it is similar ingalling and cavitation erosion properties, but has better abrasivewear and metal-to-metal sliding conditions. Used for hot workingdies and shears.No. 2012. Low cobalt alternative to No. 12. Has improved resistance to abrasion but is not as tough. Can be used for cutting edges.It should be noted that in some cases the nickel-based alloys, such asC 0.15%, Cr 17%, Mo 17%, Fe. 6%, Rem. Ni, available in coveredelectrode form may be superior to the cobalt-base alloys.See also the section on hard surfacing in Chapter 6.Preparation. The surface to be Stellited must be thoroughly cleaned of allrust and scale and all sharp corners removed. A portable grinder isextremely useful for this purpose. In some cases, where the shape iscomplicated, pre-heating to prevent cracking is definitely an advantage.A slightly longer arc than usual is held, with the rod nearly perpendicular tothe surface, as this helps to spread the Stellite more evenly. Care must be
64
taken not to get the penetration too deep, otherwise the Stellite will becomealloyed with the base metal and a poor deposit will result. Since Stellite hasno ductility, cooling must be at an even rate throughout to avoid danger ofcracking. The surface is finally ground to shape. Lathe centres, valve seats,rock drills and tool tips, cams, bucket lips, dies, punches, shear knives,valve tappet surfaces, thrust washers, stillson teeth, etc., are a few examplesof the many applications of hard surfacing by this method.Stainless steelsNote on BS 2926. This standard includes the chromium-nickelaustenitic steels and chromium steels and uses a code by which weld metalcontent and coating can be identified.The first figure is the % chromium content, the second figure the % nickelcontent and the third figure the % molybdenum content. The letter Lindicates the low carbon version, Nb indicates stabilization with niobium,W indicates that there is tungsten present. R indicates a rutile coating,usually either d.c. or a.c, and B a basic coating, usually d.c. electrode 4- veonly. A suffix MP indicates a mild steel core.For example: 19.12.3 .Nb.R is a nobium-stabilized 19% Cr, 12% Ni, 3%Mo, rutile-coated electrode.Stainless steel weldingMartensitic (chromium) stainless steels. These steels contain12-16% chromium and harden when welded. The carbon content is usuallyup to 0.3% but may be more. They are used for cutlery and sharp-edgedtools and for circumstances in which anti-corrosion properties areimportant. They harden when welded so that they should be pre-heated to200-300 C and then allowed to cool slowly. After welding they should thenbe post-heated to about 700 C to remove brittleness. By using an austeniticelectrode of the 25.12.Cr.Ni type with 3 % tungsten (see table, pp. 66-7)the weld is more ductile and freer from cracking. If, however, the weldmust match the parent plate as nearly as possible, electrodes of thechromium type must be chosen but are not very satisfactory. Use theaustenitic rod where possible.Ferritic stainless steel. Ferritic steels contain 16-30% Cr, do not hardenwhen welded but suffer from grain growth when heated in the 950-1100Crange, so that they are brittle at ordinary temperatures but may be tougherat red heat. Pre-heating to 200 C should be carried out and the weldcompleted, followed by post-heating to 750C. For mildly corrosiveconditions, electrodes of matching or higher chromium content should beused, e.g. 25.12.3.W, which give a tough deposit. If joint metal propertiesneed not match the parent plate, electrodes of 26.20 can be used. It shouldbe noted that the weld deposit of these electrodes contains nickel which is
65
Electrodea.c. d.c.
ocv
BritishStandard 2926Cr Ni Mo
A.W.S.equivalent
Coating
UTS(N/mm 2 )
80
19
9 -
Nb
E347-16
12 3
E316L-16
E308-16
100
20 -
E310-15
85
E308-16L
585
650610610640
650
70
E316-16
640
++
1919
12 312 3
NbNb
E318-16E318-15
RB
6085
1917
13 48 2
E317E16-8-2
630630
23 12
E309-15
587
12 2
E309-Mo-16 R
569
29
E312-16
ApplicationsFor the welding of plain or stabilized stainless steels.For welding Mo bearing stainless steels of 316 or316L type.For 18/8 Cr-Ni steels with low carbon deposit(0.03).For heat- and corrosion-resistant stainless steels ofsimilar composition. Also low alloy and mild steelto stainless steel with low restraint - non-magnetic.For unstabilized stainless steel of this composition.Also for welding and surfacing 14% Mn steels.Austenitic electrode for Nb stabilized stainless steelsof the 19/9 class. Can be used all positional.Austenitic electrode for unstabilized stainless steelsand similar types.For all plain or Ti or Nb stabilized stainless steels.Austenitic electrode for Ti or Nb stabilized stainlesssteels. Suitable for vertical and overhead welding,e.g. fixed pipe work, d.c. only.For AISI 317 steels. Carbon below 0.08%.Ferrite controlled with 2% Mn. Suitable for allsimilar types especially for long service at elevatedtemperatures, e.g. in steam pipes and gas turbines.Deposits of 22/12 Cr-Ni for welding clad steels ofCr-Ni of similar composition and for dissimilarmetals.For clad steels with a deposit of AISI 309Mo type,also for dissimilar metals and stainless steel to mildsteel.For dissimilar steels, nickel steels, hardenable steelsor steel of the same composition. Ferrite about 35%.
68
JL-JU-
Platethickness(mm)Preparation
Suggestedelectrodediameter(mm)
1.2-1.62.02.5
square edgesquare edgesquare edge
1.62.02.5
single 60single 60single 60
2.53.23.2 and 4
ROOTGAP 0-1.6/77/7?
1.5-3.2/77/77
ANGLE 10-15\ j ,RADIUS 5-8 mm
10-20over 20
single 60double 70
or double 70or double U
4 and 54 and 5
70'
DOUBLE V
69
From the lines on the diagram we see that the low-alloy steels arehardenable because they contain the martensitic phase as welded. Withincreasing alloying elements, austenite and ferrite phases become morestable and the steel is no longer quench hardenable. Thus steels with highnickel, manganese and carbon become austenitic (shown in diagram) whilethose with high chromium and molybdenum are more ferritic (also shown).In the area A+ F the weld will contain both austenite and ferrite (duplexphase) and it can be seen how this leads to the designation of stainless steelsas austenitic, martensitic and ferritic.The shaded areas on the Shaeffler diagram indicate regions in whichdefects may under certain circumstances appear in stainless steel welds.ExampleStainless steel BS 2926. 19.9.L.R. AWS equivalent E.308 L. Carbon0.03 %, manganese 0.7 %, silicon 0.8 %, chromium 19.0 %, nickel 10.0 %.Nickel equivalent = % Ni + (30 x % C) + (0.5 x % Mn).= 10 + (30 x 0.03) + (0.5 x 0.7)= 10 + 0.9 + 0.35= 11.25.Chromium equivalent = % Cr + % Mo + (1.5 x % Si) + (0.5 x % Nb)= 19 + 0 + (1.5 x 0.8)+ (0.5 x 0)= 19 + 0 + 1 . 2 + 0= 20.2Fig. 1.37. Constitution diagram for stainless steel welds (after Schaeffler) withapproximate regions of defects and phase balance, depending on composition.
CHROMIUM EQUIVALENT
(1.5
MARTENSITECRACKINGBELOW 400 "C
AUSTENITEHOTCRACKINGABOVE 1250 C
BRITTLENESS AFTERHEAT TREATMENTATbOO 900 C
FERRITEHIGH TEMPERA TUREBRITTLENESSETC.
30X % Si) + (0.5 x
By plotting the two values on the diagram we get the point marked * in theclear part of the diagram, giving the main phases present and giving someindication of how it will behave during welding.The welding of stainless steel to low alloy steel* and mild steelThe technique for welding is similar to that for stainless steel butdilution is the greatest problem with this work. If the electrode used is amild or low alloy steel, the weld will have a low nickel and chromiumenrichment and will be subject to cracking problems. Because of this thejoint between the steels should be welded with an austenitic stainless steelelectrode of much higher chromium-nickel content, say 25-12 or 23-12-2or 29-10, which will result in weld metal which will have up to 18% Cr and8% Ni after allowing for dilution. This now has a high resistance to hotcracking but the 25-20 type electrode must not be subject to high weldrestraint. See Vol. 1, p. 93, for composition of core wire and coverings forsteel electrodes.Nickel and nickel alloysThe welding of nickel and its alloys is widely practised usingsimilar techniques to those used for ferrous metals. The electrodes shouldbe dried before use by heating to 120C or, if they are really damp, byheating for 1-2 hours at about 260 C. Direct current from generator orrectifier with electrode positive gives the best results. A short arc should beheld with the electrode making an angle of 20-30 to the vertical and whenthe arc is broken it should first be reduced in length as much as possible andheld almost stationary, or the arc can be moved backwards over the weldalready laid and gradually lengthened to break it. This reduces the cratereffect and reduces the tendency to oxidation. The arc should be restruck bystriking at the end of a run and moving quickly back over the crater,afterwards moving forward with a slight weave over the crater area, thuseliminating starting porosity.Fig. 3.28 shows the most satisfactory joint preparation and it should beremembered that the molten metal of the nickel alloys is not as fluid as thatof steel so that a wider V preparation is required with a smaller root face toobtain satisfactory penetration.Each run of a multi-run weld should be deslagged by chipping and wirebrushed. Grinding should not be undertaken as it may lead to particles ofslag being driven into the weld surface with consequent loss of corrosionresistance. Stray arcing should be avoided and minimum weaving performed because it results in poorer quality of weld deposit due to increaseddilution.* British and American classifications for low alloy steel electrodes are given on pp. 83-9.
71
MaterialNickel and nickel alloys200, 201MONEL alloy 400MONEL alloy K500Copper-nickel alloysINCONEL alloy 600INCONEL alloy 601INCONEL alloy 625INCONEL alloy 617INCONEL alloy 690INCO alloy C276INCO alloy HXINCO alloy G3INCOLOY alloys800, 800H, 800HTINCOLOY alloy 825INCOLOY alloy DSNIMONIC alloy 75BRIGHT alloy seriesNILO alloy seriesCast ironsMo bearing steels
Recommended coveredMMA electrodesNickel alloy 141MONEL alloy 190MONEL alloy 190MONEL alloy 187INCONEL alloy 182,INCO-WELD alloys A, BINCONEL alloys 182, 112,INCO-WELD alloy AINCONEL alloy 112INCONEL alloy 117INCO-WELD alloy A,INCONEL alloy 112INCO alloy C276INCO alloy HX,INCONEL alloy 117INCONEL alloy 112INCO-WELD alloys A, B,INCONEL alloys 112, 117INCOLOY alloy 135INCO-WELD alloys A, BINCONEL alloys 182, 112,INCO-WELD alloys A, BINCO-WELD alloys A, BNickel alloy 141,INCO-WELD alloys A, BNI-ROD 44, 55X, 99XINCONEL alloy 112
72
Clad steelsStainless clad steel is a mild or low alloy steel backing faced withstainless steel such as 18% Cr 8% Ni or 18% Cr 10% Ni with or without Mo,Ti and Nb, or a martensitic 13% Cr steel, the thickness of the cladding being10-20% of the total plate thickness.Preparation and technique. The backing should be welded first and the mildsteel root run should not come into contact with the cladding, so thatpreparation should be either with V preparation close butted with a deeproot face, or the cladding should be cut away from the joint at the root (seeFig. 1.38). The clad side is then back grooved and the stainless side weldedwith an electrode of similar composition. Generally an austenitic stainlesssteel electrode of the 25% Cr 20% Ni type should be used for the root run onthe clad side because of dilution effects, and at least two layers or more ifpossible should be laid on the clad side to prevent dilution effects affectingthe corrosion-resistant properties. First runs should be made with lowcurrent values to reduce dilution effects. For martensitic 13o Cr cladding,pre-heating to 240 C is advisable followed by post-heating and using anaustenitic stainless steel electrode such as 22% Cr 12% Ni 3o Mo withabout 15() ferrite, which gives weld metal of approximately 18o Cr 8 o Niwith about 6o ferrite. Welding beads not adjacent to the backing plate canbe made with 18o Cr 12% Ni 3o Mo electrodes. If the heat input is kept aslow as possible welding may be carried out without heat treatment, theHAZ being tempered by the heat from successive runs.Nickel clad steelMild and low alloy steel can be clad with Nickel, MONEL orINCONEL alloys for corrosion resistance at lower cost compared tosolid nickel base material and with an increase in thermal conductivity andgreater strength, the thickness of cladding usually being not greater than6 mm. When welding clad steels it is essential to ensure the continuity ofFig. 1.38. Alternative methods of welding clad steel.0.51
mmJOINT PREPAREDAND CLAD SIDECUT OUT
JOINT PREPARED
MILD STEELSIDE WELDED
Welding of pipelines
73
the cladding, and because of this butt joints are favoured. Dilution of theweld metal with iron occurs when welding the clad side, but the electrodealloy can accept this. First runs should be made with low current valuesto reduce the dilution.Preparation of joints is similar to that for stainless clad steel.Recommended electrodes are given in the table on p. 71.
Welding of pipelinesThe following brief account will indicate to the welder the chiefmethods used in the welding of pipelines for gas, oil, water, etc. The lengthsof pipes to be welded are placed on rollers, so that they can easily berotated. The lengths are then lined up and held by clamps and tack weldedin four places around the circumference, as many lengths as can be handledconveniently, depending on the nature of the country, being tackedtogether to make a section. The tack welder is followed by the main squadof welders, and the pipes are rolled on the rollers by assistants using chainwrenches, so that the welding of the joint is entirely done in the flat position;hence the name roll welding.After careful inspection, each welded section is lifted off the rollers bytractor-driven derricks and rested on timber baulks, either over or near thetrench in which it is to be laid. The sections are then bell hole weldedtogether. The operator welds right down the pipe, the top portion beingdone downhand, the sides vertical, and the underside as an overhead weld.Electrodes of 4 and 5 mm diameter are used in this type of weld.Stove pipe welding (see also Appendix 6)This type of welding has a different technique from conventionalpositional welding methods and has enabled steel pipelines to be laid acrosslong distances at high rates. The vertically downward technique is used,welding from 12 o'clock to 6 o'clock in multiple runs.Cellulose or cellulose-iron powder coated electrodes are used. These givea high burn-off rate, forceful arc and a light, fast-freezing slag and are verysuitable for the vertical downward technique. The coating provides a gasshield which is less affected by wind than other electrodes but, generally,welding should not be carried out where the quality of the completed weldwould be impaired by prevailing weather conditions, which may includerain, blowing sand and high winds. Weather protection equipment can beused wherever practicable.Preparation is usually with 60 between weld faces, increased sometimesto 70 with a 1.5 mm root face and 1.5 mm root gap; internal alignmentclamps are used. The stringer bead is forced with no weave into the root,then the hot pass with increased current fuses the sides and fills up any
74
burn4hrough which may have occurred. Filler runs, stripper runs andcapping run complete the welding (Fig. 1.39a). A diesel driven weldinggenerator with tractor unit or mounted with the pipe laying plant is usedwith the electrode - ve (reverse polarity).The welding of pipelines is usually performed by a team of welders; thelarger the diameter of pipe, the greater the number of welders. In most casesthe welder performs the same type of weld on each successive joint. The firstteam deposits the stringer bead and then moves on to the next joint. Thesecond team carries out the hot pass, and they are followed by the thirdwith the hot fill and the three teams follow along the pipeline from one jointto another. On a 42" pipe there could be twelve welders spread over threeadjacent joints all welding simultaneously. The first group is followed byfurther groups of fillers and cappers. It is important that the first threepasses are deposited without allowing the previous one to cool.Note. The wire brushes used are of strong stainless steel wire and powerdriven. As the wire is so strong there must be adequate protection of eyesand face by using a transparent thick face mask.For clarity Fig. 1.39a and b shows the various passes and the clock face,while Fig. 1.40 shows pipe preparation including the use of backing ringsand Fig. 1.41 shows preparation for a cut and shut bend and a gusset bend.The CO 2 semi-automatic process is also used for pipeline welding. Thesupply unit is usually an engine-driven generator set and the technique usedis similar to the stove pipe method, but it is important to obtain good lineup to avoid defects in the penetration and correct manipulation to avoidcold shuts. Fully automatic orbital pipe welders are also available using theTIG process and are used on pipes from 25 to 65 mm outside diameter.For full details of the various methods of preparation and weldingstandards for pipes, the student should refer to BS 2633, class 1: Steelpipework, and BS 2971, class 2: Steel pipelines; BS 2910: Radiographicexamination of pipe joints, and BS938: Metal arc welding of structural steeltubes. See also Appendix 6, Low hydrogen electrode, downhill pipewelding.Fig. 1.39. (a)^CAPPING
75
For river crossings the pipe thickness is increased by 50-100% and thelengths are welded to the length required for the crossing. Each joint isfurther reinforced by a sleeve, and large clamps bolted to the line serve asanchor points. The line is then laid in a trench in the river bed.For water lines from 1 to Ij m diameter, bell and spigot joints are oftenused. On larger diameter pipes the usual joint is the reinforced butt. TheFig. 1.39. (b) Clock face for reference.
OFig. 1.39. (c) Electrode angles (hot fill).START
DIRECTIONOF TRA VEL
Fig. 1.4060-80
GAP 1.5-4 mmBUTT WELD PREPARATIONUP TO 16 m m THICK
Pass
Electrodediam. (mm)
Current(A)
Stringer bead
3.25
100-130
Hot pass
180-220
Hot fill
160-190
Fill andstripperpasses
150-190
Capping run
130-190
TechniquePreheat to 50-100C. Strike electrode at 12 o'clock and keep at approximately 90 to line oftravel. To control fine penetration, vary electrode angle to 6 o'clock for more to 12 o'clockfor less. Use straight touch technique. If necessary someone can control current fromgenerator according to welder's instructions. Arc should be visible on inside of pipe. Do notstop for small 'windows' or burn throughs, which will be eliminated by the hot pass. Grindbead when finished taking slightly more from sides until weld tracks are just visible.This is deposited immediately after the stringer bead and melts out any inclusions, fills in'windows' and must be deposited on a hot stringer bead which it anneals. It is a light dragweld with a backward and forward 'flicking' movement of the electrode held generally at60-70 to the line of travel but this can vary to 90 at 5 o'clock to 6 o'clock and 7 o'clock to 6o'clock. Rotary wire brushing with a heavy duty power brush completes the pass.This is deposited immediately after the hot pass, while the pipe is still warm. It cleans theweld profile and adds to the strength of the joint. The electrode is held at 60 to 70 to the lineof travel at 12 o'clock, increasing to 120 at 6 o'clock (see Fig. 1.39c).If the joint has cooled, preheat to 50 to 100 C. All runs are single passes with no weaving andeach run is well wire brushed. The electrode is held at 60-70 to line of travel at 12 o'clock,changing gradually to 90-100 at 6 o'clock.If the areas between 2 o'clock and 5 o'clock and between 10 o'clock and 7 o'clock are low,stripper passes are made until the weld is of a uniform level.The electrode is held at 60-80 at 12 o'clock, to 120 at 6 o'clock. A fast side to side weave ispermitted, covering not more than 2\ times the diameter of the rod. Lengthening the arcslightly between 5 o'clock and 7 o'clock avoids undercut. Manipulation between 4 o'clockand 8 o'clock can be by a slight 'flicking' technique.After completion the joint is power wire brushed and wrapped in a dry asbestos or similarcloth with waterproof backing and the joint is allowed to cool uniformly.
77
pipe is V'd on the inside and welded from the inside. A steel reinforcingband is then slipped over the joint and fillet welded in position.The types of joint are illustrated in Fig. 1.42.
SET ON BRANCH
BEND
SET IN BRANCH
Fig. 1.42
78
Welding of steels
79
Cu%15
Fig. 1.43
-HAZ
HAZ
CRACK-
HAZ CRACKING
(3) Rate of cooling of the welded zone. The rate of cooling depends upon (1)the heat energy put into the joint and (2) the combined thickness of themetal forming the joint. Arc energy is measured in kilojoules per mm lengthof weld and can be found from the formulaArc energy (kJ/mm) =
The greater the heat input into the joint the slower the rate of cooling sothat the use of a large-diameter electrode with high current reduces thequenching effect and thus the cracking tendency. Similarly, smallerdiameter electrodes with lower currents reduce the heat input and give aquicker cooling rate, increasing the tendency to crack due to the formationof hardened zones. Subsequent runs made immediately afterwards are notquenched as is the first run, but if the first or subsequent runs are allowed tocool, conditions then return to those of the first run. For this reasoninterpass temperature is often stipulated so as to ensure that the weld is notallowed to cool too much before the next run or pass is made. The use oflarge electrodes with high currents, however, does not necessarily give goodimpact properties at low temperatures. For cryogenic work it is essential toobtain the greatest possible refining of each layer of weld metal by usingsmaller-diameter electrodes with stringer or split-weave technique. As the'combined thickness', that is the total thickness of the sections at the joint,increases, so the cooling rate increases, since there is increased sectionthrough which the heat can be conducted away from the joint. The coolingrate of a fillet joint is greater than that for a butt weld of the same sectionplate since the combined thickness is greater (Fig. 1.44).(4) Restraint. When a joint is being welded the heat causesexpansion, which is followed by rapid cooling. If the joint is part of a veryFig. 1.44
81
rigid structure the welded zone has to accommodate the stresses due tothese effects and if the weld is not ductile enough, cracking may occur. Thedegree of restraint is a variable factor and is important when estimating thetendency to crack.Controlled Thermal Severity (CTS) tests in which degrees of restraint areplaced upon the joint to be welded and on which pre- and post-heat can beapplied are used to establish the liability to crack. (See Reeve test, Volume 1.)Hydrogen cracking can be avoided by (1) using basic hydrogencontrolled electrodes, correctly dried and (2) pre-heating.The temperature of pre-heat depends upon (1) the CE of the steel, (2) theprocess used and in the MMA process, the type of electrode (rutile orbasic), (3) the type of weld, whether butt or fillet and the run out length(x mm electrode giving y mm weld), (4) the combined thickness of the jointand (5) arc energy.Reference tables are given in BS 5135 from which the pre-heattemperature can be ascertained from the above variables. Pre-heattemperatures may vary from 0 to 150C for carbon and carbon-manganesesteels and be up to 300 C for higher-carbon low-alloy steels containingchromium and molybdenum. The pre-heating temperature is specified asthe temperature of the plate immediately before welding begins andmeasured for a distance of at least 75 mm on each side of the joint,preferably on the opposite face from that which was heated. The combinedthickness is the sum of the plate thickness up to a distance of 75 mm fromthe joint. If the thickness increases greatly near the 75 mm zone highercombined thickness values should be used and it should be noted that if thewhole unit being welded (or up to twice the distance given above) can bepre-heated, pre-heat temperatures can be reduced by about 50 C. Austenitic electrodes can generally be used without pre-heat.Steels used for cryogenic (low temperature) applications can becarbon-manganese types which have good impact properties down to 30C and should be welded with electrodes containing nickel; 3% nickelsteels are used for temperatures down to 100C and are welded withmatching electrodes whilst 9% nickel steels, used down to 196C (liquidnitrogen), are welded with nickel-chromium-iron electrodes since the 3 %nickel electrodes are subject to solidification cracking.Creep-resistant steels usually contain chromium and molybdenum andoccasionally vanadium and are welded with basic-coated low-alloy electrodes with similar chromium and molybdenum content. Two types ofcracking are encountered: (1) transverse cracks in the weld metal, (2) HAZcracking in the parent plate. Pre-heating and interpass temperatures of200-300C with post-heat stress relief to about 700C is usually advisable.
82
CRACKS
83
Nearest AWS Crequivalentmin
max
Momin
Mnmin
0.40.4
0.70.7
0.750.35
1.21.2
0.30.30.50.50.50.50.50.5
1.11.11.11.81.21.21.21.2
Manganese-molybdenum electrodesMnMoBE90XX-D12MnMoBE100XX-D2
0.250.25
0.450.45
1.21.6
1.82.0
0.20.20.20.2
0.50.50.50.0
0.60.80.51.31.3
1.21.61.21.82.2
1.5
Nimin
0.3
0.8
0.82.02.80.82.02.80.82.0
1.22.753.751.12.753.751.22.75
1.01.2
1.21.51.5
1.81.91.92.52.5
Simax
Wmin
Cmax
0.60.8
0.10.1
0.50.50.30.50.50.30.50.80.80.80.80.8
0.050.10.1
Vmax
0.7
1.0
0.10.10.10.230.230.280.070.050.050.10.1
0.60.60.60.80.80.80.80.8
0.150.15
0.80.8
0.80.80.80.80.8
0.1
0.10.180.10.1
0.30.50.5
Table 9. American Welding Society (A WS) abridged classification for low-alloy steel covered arc welding electrodes.A5.5-81 {reprinted 1985)The higher tensile strength electrodes, such as E8010, which do not have low hydrogen coverings are used for pipe welding and areusually matched to the pipe.
Capable of producingsatisfactory weldsin position shown
Type of current
E70 series: minimum tensile strength of deposited metal 70000 psi (480 MPa)F, V, OH, HE7010-X*High cellulose sodiumF, V, OH, HE7011-XHigh cellulose potassiumLow hydrogen sodiumF, V, OH, HE7015-XLow hydrogen potassiumF, V, OH, HE7016-XIron powder low hydrogenF, V, OH, HE7018-XHigh iron oxideE7020-XH-filletsFH-filletsE7027-XIron powder iron oxideF
DCEPAC orDCEPAC orAC orAC orAC orAC orAC or
E80 series. minimum tensile strength of deposited metal 80000 psi (550 MPa)High cellulose sodiumF, V, OH, HE8010-XE8011-XHigh cellulose potassiumF, V, OH, HE8O13-XHigh titania potassiumF, V, OH, HE8015-XLow hydrogen sodiumF, V, OH, HLow hydrogen potassiumF, V, OH, HE8016-XIron powder low hydrogenF, V, OH, HE8018-X
DCEPAC orAC orDCEPAC orAC or
E90 series: minimum tensile strength of deposited weld metal 90000 psi (620 MPa)High cellulose sodiumF, V, OH, HE9010-XHigh cellulose potassiumF, V, OH, HE9011-XHigh titania potassiumF, V, OH, HE9013-XHigh hydrogen sodiumF, V, OH, HE9015-XLow hydrogen potassiumF, V, OH, HE9016-XIron powder low hydrogenF, V, OH, HE9018-X
E100 series: minimum tensile strength of deposited metal 100000 psi (690 MPa)E10010-XHigh cellulose sodiumF, V, OH,El0011-XHigh cellulose potassiumF, V, OH,E10013-XHigh titania potassiumF, V, OH,E10015-XLow hydrogen sodiumF, V, OH,E10016-XLow hydrogen potassiumF, V, OH,E10018-XIron powder, low hydrogenF, V, OH,
HHHHHH
DCEPDCEPDCEPDCENDC, either polarityDCENDC, either polarity
DCEPDC, either polarityDCEPDCEP
El 10 series: minimum tensile strength of deposited weld metal 110000 psi (760 MPa)E11015-XLow hydrogen sodiumF, V, OH, HE11016-XLow hydrogen potassiumF, V, OH, HE11018-XIron powder, low hydrogenF, V, OH, H
DCEPAC or DCEPAC or DCEP
El 20 series: minimum tensile strength of deposited weld metal 120000 psi (830 MPa)E12015-XLow hydrogen sodiumF, V, OH, HE12016-XLow hydrogen potassiumF, V, OH, HE12018-XIron powder, low hydrogenF, V, OH, H
X stands for the various suffixes Al, Bl, Cl, etc., which denote the types of chemical composition of the electrodes (see Table 10).
Type of steel
Example
Suffix
AlBlB2B2LB3B3LB4LB5ClC1LC2
Carbon-molybdenumChromium-molybdenumChromium-molybdenumChromium-molybdenumChromium-molybdenumChromium-molybdenumChromium-molybdenumChromium-molybdenumNickel steelNickel steelNickel steel
E7011-A1E8016-B1E8018-B2E8015-B2LE9016-B3E9018-B3LE8015-B4LE8016-B5E8016-C1E7018-C1LE8018-C2
C2LC3CNM<*DlD3D2G
Nickel steelNickel steelNickel-molybdenumManganese-molybdenumManganese-molybdenumManganese-molybdenumAll other low alloy steelelectrodesMilitary specificationContaining small % copper
E7016-C2LE8018-C3 cE8018-NM dE9018-D1E8016-D3E10015-D2E7020-G
MW
cd
E11018-ME7018-W
89
necessary drying conditions for the electrodes that will give the necessaryhydrogen levels per 100 g of weld metal (see pp. 8 and 12-13). Electrodediameters are 2, 2.5, 3.2, 4, 5, 6 and 6.3 mm.Details of the full chemical composition, mechanical and radiographictests, all weld metal tension test and impact (Charpy) test are given inBS 2493 (1985).Example. 2NiB. A 2% nickel steel electrode (Ni 2.0-2.75%)with basic covering (AWS E80XX-C1)Most low-alloy steel electrodes have a core wire of rimming steel (steelthat has not been fully deoxidized before casting) with the alloyingelements added to the covering. Under certain conditions, such as in pipewelding, the thickness of the covering makes positional welding difficultso the cellulosic covered electrodes have a core wire of the correct alloysteel e.g. chromium-molybdenum type as given in Table 8 (lCrMo,2CrMo and 5CrMo).
Table giving some of the chief types of metal arc welding electrodesavailable for welding alloy steelsElectrode
Rutile or basic coated for medium and heavy duty fabrications. The latter suitable for carbon and alloy steels and mildsteel under restraint and for thick sections and root runs inthick plate.Austenitic rutile or basic coated for high-tensile steels including armour plate and joints between low-alloy and stainlesssteel and in conditions where pre-heat is not possible to avoidcracking.Basic coated for high-strength structural steels 300-425N/mm 2 tensile strength and for copper bearing weatheringquality steels.Basic coated for steels containing 2-5% Ni, 3% Ni andcarbon-manganese steels.Also austenitic high nickel electrodes for 9% Ni steel forservice to 196C and for dissimilar metal welding and forhigh Ni-Cr alloys for use at elevated temperatures.Ferritic, basic coating for (1) 1.25% Cr, 0.5% Mo, (2) 2.5% Cr,1.0% Mo, (3) 4-6% Cr, 0.5% Mo, steels with pre- and postheat.Austenitic ferrite controlled for creep-resistant steels and forthick stainless steel sections requiring prolonged heat treatment after welding.(1) Rutile or basic coating 19% Cr 9% Ni for extra low carbonstainless steels.(2) Basic coating Nb stabilized for plain or Ti or Nb stabilized18/8 stainless steels and for a wide range of corrosive- andheat-resisting applications. Variations of these electrodesare for positional welding, smooth finish, and for highdeposition rates.(3) Rutile or basic coating Mo bearing for 18/10 Mo steels.(4) Rutile or basic coating, low-carbon austenitic electtodesfor low-carbon Mo bearing stainless steels and for weldingmild to stainless steel.(5) Basic coating austenitic for heat-resisting 25% Cr, 12% Nisteels, for welding mild and low-alloy steels to stainlesssteel and for joints in stainless-clad mild steel.(6) Rutile coating austenitic for 23% Cr, 11% Ni heat-resistantsteels containing tungsten.(7) Basic coating 25% Cr, 20% Ni (non-magnetic) for weldingaustenitic 25/20 steels and for mild and low-alloy steels tostainless steel under mild restraint.
High-tensilealloy steelsStructural steelsNotch ductilesteels for lowtemperatureserviceCreep-resistingsteels
Heat- andcorrosionresisting steels
Electrode
Hard-surfacingand abrasionresisting alloys
12-14%Manganesesteels
91
2Gas shielded metal arc welding^
92
93
With the tungsten inert gas shielded arc welding process, inclusions oftungsten become troublesome with currents above 300 A. The MIGprocess does not suffer from these disadvantages and larger weldingcurrents giving greater deposition rates can be achieved. The process issuitable for welding aluminium, magnesium alloys, plain and low-alloysteels, stainless and heat-resistant steels, copper and bronze, the variationbeing filler wire and type of gas shielding the arc.The consumable electrode of bare wire is carried on a spool and is fed to amanually operated or fully automatic gun through an outer flexible cableby motor-driven rollers of an adjustable speed, and rate of burn-off of theelectrode wire must be balanced by the rate of wire feed. Wire feed ratedetermines the current used.In addition, a shielding gas or gas mixture is fed to the gun together withwelding current supply, cooling water flow and return (if the gun is watercooled) and a control cable from gun switch to control contractors. A d.c.power supply is required with the wire electrode connected to the positivepole (Fig. 2.1).Fig. 2.1. Components of gas shielded metal arc welding process.REGULATOR^,A
F(LLR
W/R
SPOOLWIRE FEEDAND CONTROLUNITWIRE FEEDSPEED CONTROL
CONTROL CABLE,FILLER WIRE CONDUIT,POWER CABLE,GAS HOSE
WORKCLAMP
WORKWIREELECTRODE
94
Spray transferIn manual metal arc welding, metal is transferred in globules ordroplets from electrode to work. If the current is increased to the continuously fed, gas-shielded wire, the rate at which the droplets are projectedacross the arc increases and they become smaller in volume, the transferoccurring in the form of a fine spray.The type of gas being used as a shield greatly affects the values of currentat which spray transfer occurs. Much greater current densities are requiredwith CO 2 than with argon to obtain the same droplet rate. The arc is notextinguished during the operation period so that arc energy output is high,rate of deposition of metal is high, penetration is deep and there isconsiderable dilution. If currents become excessively high, oxide may beentrapped in the weld metal, producing oxide enfoldment or puckering (inAl). For spray transfer therefore there is a high voltage drop across the arc(30-45 V) and a high current density in the wire electrode, making theprocess suitable for thicker sections, mostly in the flat position.The high currents used produce strong magnetic fields and a verydirectional arc. With argon shielding the forces on the droplets are wellbalanced during transfer so that they move smoothly from wire to workwith little spatter. With CO 2 shielding the forces on the droplet are lessbalanced so that the arc is less smooth and spatter tendency is greater(Fig. 2.2). The power source required for this type of transfer is of theFig. 2.2. Types of arc transfer, (a) Spray transfer: arc volts 27-45 V. Shieldinggases: argon, argon-1 or 2% oxygen, argon-20% CO 2 , argon-2% oxygen-5%CO 2 . High current and deposition rate, used for flat welding of thickersections, (b) Short-circuit or dip transfer: arc volts 15-22 V. Shielding gases asfor spray transfer. Lower heat output and lower deposition rate than spraytransfer. Minimizes distortion, low dilution. Used for thinner sections andpositional welding of thicker sections.WIRE-NOZZLE
WIRENOZZLE-
CONTACT TUBE
SHIELDING
SHIELDINGGAS
95
constant voltage type described later. Spray transfer is also termed freeflight transfer.Short circuit or dip transfer and controlled dip transfer
With lower arc volts and currents transfer takes place in globularform but with intermittent short-circuiting of the arc. The wire feed ratemust just exceed the burn-off rate so that the intermittent short-circuitingwill occur. When the wire touches the pool and short-circuits the arc there isa momentary rise of current, which must be sufficient to make the wire tipmolten, a neck is then formed in it due to magnetic pinch effect and it meltsoff in the form of a droplet being sucked into the molten pool aided bysurface tension. The arc is then re-established, gradually reducing in lengthas the wire feed rate gains on the burn-off until short-circuiting againoccurs (Fig. 2.2). The power source must supply sufficient current on shortcircuit to ensure melt-off or otherwise the wire will stick into the pool, and itmust also be able to provide sufficient voltage immediately after shortcircuit to establish the arc. The short-circuit frequency depends upon arcvoltage and current, type of shielding gas, diameter of wire, and the powersource characteristic. The heat output of this type of arc is much less thanthat of the spray transfer type and makes the process very suitable for thewelding of thinner sections and for positional welding, in addition to multirun thicker sections, and it gives much greater welding speed than manualarc on light gauge steel, for example. Dip transfer has the lowest weld metaldilution value of all the arc processes and this method is also pulsed.Semi-short-circuiting arc
In between the spray transfer and dip transfer ranges is an intermediate range in which the frequency of droplet transfer is approachingthat of spray yet at the same time short-circuiting is taking place, but is ofvery short duration. This semi-short-circuiting arc has certain applications,as for example the automatic welding of medium-thickness steel plate withCO2 as the shielding gas.Power supply d.c. and arc control*
96
-J~~M
r-
CONSTANTVOLTAGE SLOPE
h(a)
fM
Is
CURRENT
DROOPING.CHARACTERISTIC
97
indicated in Fig. 2.3# at M and the current for this length is IM amperes. Ifthe arc shortens (manually or due to slight variation in motor speed) to S(the volts drop is now Vs) the current now increases to Is, increasing theburn-off rate, and the arc is lengthened to M. Similarly if the arc lengthensto L, current decreases to IL and burn-off rate decreases, and the arcshortens to M.Evidently the gradient of slope of the output curve affects the weldingcharacteristics and slope-controlled units are produced in which thegradient or steepness of the slope can be varied as required and the correctslope selected for given welding conditions.Drooping characteristic d.c. supplyWith this system the d.c. supply is obtained from a weldinggenerator with a drooping characteristic or more usually from atransformer-rectifier unit. If a.c. is required it is supplied at the correctvoltages from a transformer.The characteristic curve of this type of supply (Fig. 2.3/?) shows that thevoltage falls considerably as the current increases, hence the name. Ifnormal arc length M has volts drop VM and if the arc length increases to L,the volts drop increases substantially to Vi. If the arc is shortened the voltsdrop falls to V$ while the current does not vary greatly, hence the nameconstant current which is often given to this type of supply. The variationsin voltage due to changing arc length are fed through control gear to thewire feed motor, the speed of which is thus varied so as to keep a constantarc length, the motor speeding up as the arc lengthens and slowing down asthe arc shortens. With this system, therefore, the welding current must beselected for given welding conditions and the control circuits are morecomplicated than those for the constant voltage method.Power source-dip transfer (or short-circuit transfer)In order to keep stable welding conditions with a low voltage arc(17-20 V) which is being rapidly short-circuited, the power source musthave the right characteristics. If the short-circuit current is low theelectrode will freeze to the plate when welding with low currents andvoltages. If the short-circuit current is too high a hole may be formed in theplate or excessive spatter may occur due to scattering of the arc pool whenthe arc is re-established. The power supply must fulfil the followingconditions:(1) During short-circuit the current must increase enough to melt thewire tip but not so much that it causes spatter when the arc is reestablished.
98
(2) The inductance in the circuit must store enough energy duringshort-circuit to help to start the arc again and assist in maintainingit during the decay of voltage and current. If an inductive reactoror choke connected in the arc circuit when the arc is short-circuitedthe current does not rise to a maximum immediately, so the effectof the choke is to limit the rate of rise of current, and the amountby which it limits it depends upon the inductance of the choke.This limitation is used to prevent spatter in CO2 welding. Whenthe current reaches its maximum value there is maximum energystored in the magnetic field of the choke. When the droplet necksoff in dip transfer and the arc is re-struck, the current is reducedand hence the magnetic field of the choke is reduced in strength,the reduction in energy being fed into the circuit helping to reestablish the arc. If the circuit is to have variable inductance so thatthe choke can be adjusted to given conditions the coil is usuallytapped to a selector switch and by varying the number of turns incircuit the inductive effect is varied. The inductance can also bevaried by using a variable air gap in the magnetic circuit of thechoke.To summarize: the voltage of a constant voltage power source remainssubstantially constant as the current increases. In the case of a weldingpower unit the voltage drop may be one or two volts per hundred amperesof welding current, and in these circumstances the short-circuit current willbe high. This presents no problem with spray transfer where the currentadjusts to arc length and thus prevents short-circuiting, but in the case ofshort-circuiting (dip) transfer, excessive short-circuit currents would causemuch spatter.The steeper the slope of the power unit volt-ampere characteristic curvethe less the short-circuit current and the less the 'pinch effect' (which is theresultant inward magnetic force acting on the molten metal in transfer) sothat spatter is reduced. Too much reduction of the short-circuit current,however, may lead to difficulty in arc initiation and stubbing. Power unitsare available having slope control so that the slope can be varied to suitwelding conditions, and the control can be by tapped reactor or byinfinitely variable reactor, the power factor of the latter being better thanthat of the former.Three variables can thus be provided on the power unit - slope control,voltage and inductance. Machines with all three controls give the mostaccurate control of welding conditions but are more expensive and requiremore setting than those with only two variables, slope-voltage orvoltage-inductance. In general, units with voltage-inductance control offer
99
FAULT LAMPINDICATES UNITOVERLOADED
ON/OFF SWITCHIN THE ON POSITION POWERIS APPLIED TO THE FAN ANDCONTROL CIRCUITS
FaultO
- TORCH CONNECTOR
TradesmigWORK RETURN LEAD(TM 165, 235 & 245,1
- VOLTAGE SELECTORSWITCH - FINE
SOCKET-
INDUCTANCE SOCKET-HIGH(TM 285 ONLY)
* VOLTAGE SELECTORSWITCH - COARSE(TM 285 ONLY)
NOZZLE FORSPOT WELDING
For spot welding the nozzle is changed for one that has a cut-away end, sothat the contact tip is distanced from the work. Upon pressing the torchswitch the wire moves down to the work to make the spot weld. The size ofspot weld depends upon the thickness of plate being spot welded and isdetermined by the time setting on switch 1.
101
CONTINUOUSTIME--
nVARIABLE
SPOT^7"1 CONTROL SWITCH ON^
8STITCHg7"1 >A/VD 7"2 SWITCHES^ON5
TIME-*
72 VARIABLE
7"1VARIABLE *~
TIME +WELDING CURRENT MODESFig. 2.4. (Z?) Mega-arcdiesel engine driven, 1800rpm. Water-cooled Perkinsengine. Models for 400 A,450 A and 500 A at 60%duty cycle. High and lowcurrent ranges, OCV 75.Auxiliary power 115/230receptacle. For d.c. MMA,TIG, flux core with orwithout gas, solid wirespray transfer, and somedip transfer applicationsusing 75 % Ar, 25 % CO 2.Arc force control. Optionalremote control.
102
COARSE TAP R
COARSE TAP Y
FINE TAP Y
\YELLOW PHASEMAINTRANSFORMER
2COARSECOA RSE TAP B
5FINE
VOLTAGE TAPPINGSWITCHES
- RECTIFIER (6 DIODES)
INDUCTANCE
Sets are now also available with programmable power sources. Usingknown quantities such as amperes, seconds, metres per minute feed, thewelding program is divided into a chosen number of sections and thewelding parameters as indicated previously are used to program thecomputer which controls the welding source. The program can be stored inthe computer memory of up to say 50 numbered welding programs or it canbe stored on a separate magnetic data card for external storage or use onanother unit. By pressing the correct numbers on the keyboard of the unitany programs can be selected and the chosen program begins, controllingwelding current, shielding and backing gas, gas pre-flow, wire feed speed,arc length, pulsed welding current and slope control, etc. All safety controlsare fitted and changes in the welding program can be made withoutaffecting other data.
Fig. 2.6. (a) Transmig 400 inverter for MIG/MAG, MMA (stick), d.c. TIG, with pulsed MIG. Input 380-415 V, 50-60 Hz, 3-phase withwire feed. Remote control optional. 60-70 OCV MIG/MAG, and 65-75 OCV with MMA and TIG. At 60% duty cycle 315 A with 50 arcvolts. At 40 % duty cycle 400 A at 36 V. Stable arc, low spatter, HF start. Good positional capability. Remote control, pulse unit and wateradapter. Weight 48 kg, the inverter giving weight reduction. (See Appendix 10, p. 430, for photograph, and Chapter 5 of Volume 1 forcomplete description of the inverter.)
murexTransmatic4x4R
LOCAL/REMOTE SWITCH/UP -CURRENT OR VOLTAGE CONTROLLED BYPANEL-MOUNTED OUTPUT CONTROLDOWN - CURRENT OR VOLTAGE CONTROLLEDBY A REMOTE CONTROL DEVICE
fRANSMIG
4000i
104
CIRCUIT BREAKERSAMPERE/VOLT CONTROL
MODE SWITCH
, POWER ON14/17 PANEL SWITCH-
STANDARD/REMOTECONTACTOR SWITCH
-PILOT LIGHT-POWER OFF
Maxtron 400CC/CV DC INVERTERARC WELDING POWER SOURCE
POSITIVE TERMINALREMOTE 14 RECEPTACLE
NEGATIVE TERMINALFlEMOTE 17 RECEPTACLE
10 5
The inverter
106
107
108
109
1. Contact tip for 1.0, 1.2 and 1.6 mm hard and soft wire; 1.6, 2.0 and 2.4 mm tubularwire.2. Nozzle.3. Nozzle insulator.4. Nozzle spring clip.5. Torch head.6. Head insulator and O clip.7. Neck.8. Self-tapping screw.9. Spider.10. Handle mounting.11. Microswitch.12. Switch lever.13. Switch housing.14. Screw.15. Heat shield.16. Integrated cable.17. Plug: 7 pin.18. Basic liner.19. Liner; 1.2, 1.6 mm soft wire, 1.2, 1.6 mm hard wire, 1.6, 2.0 mm tubular wire.20. Outlet guide; 1.2, 1.6 mm soft wire, 1.2, 1.6 mm hard wire, 1.6, 2.0, 2.4 mm tubularwire.21. Collet (for soft wire outlet guides).
110
GasesSince CO2 and oxygen are not inert gases, the title metallic inertgas is not true when either of these gases is mixed with argon or CO 2 is usedon its own. The title metallic active gas (MAG) is sometimes used in thesecases.Argon, Ar. Commercial grade purity argon (99.996%) is obtained byfractional distillation of liquid air from the atmosphere, in which it ispresent to about 1% (0.932%) by volume. It is supplied in blue-paintedcylinders containing 1.7, 2.0, 8.48 and 9.66 m 3 of gas at 175 or 200 barmaximum pressure or from bulk supply. It is used as a shielding gasbecause it is chemically inert and forms no compounds.Carbon dioxide, CO2. This is produced as a by-product of industrialprocesses such as the manufacture of ammonia, from the burning of fuels inan oxygen-rich atmosphere or from the fermentation processes in alcoholproduction, and is supplied in black-painted steel cylinders containing upto 35 kg of liquid CO 2 .* To avoid increase of water vapour above the limitof 0.015% in the gas as the cylinder is emptied, a dip tube or syphon is fittedso that the liquid CO 2 is drawn from the cylinder, producing little fall intemperature. Fig. 2.8 shows a CO 2 vaporizer or heater with pressurereducing regulator and ball type flowmeter. A cartridge type electricheating element at 110 V is in direct contact with the liquid CO 2 to vaporizeit. The 150 W version gives a flow rate of 21 litres/min while the 200 Wversion gives 28 litres/min. A neon warning light connected via athermostat indicates when the element is heating and is extinguished whenthe heater has warmed up sufficiently. The syphon cylinder has a whitelongitudinal stripe down the black cylinder while the non-syphon cylinder,used when the volume of CO 2 to be taken from it is less than 15 litres/min, isall black. Manifold cylinders can be fed into a single vaporizer, and if thesupply is in a bulk storage tank, this is fed into an evaporator, and then fedto the welding points at correct pressure as with bulk argon and oxygensupplies.Helium, He. Atomic weight 4, liquifying point -268C, is thus muchlighter than argon, atomic weight 40. It is present in the atmosphere inextremely small quantities but is found in association with natural gas in* The cylinder pressure depends upon the temperature being approximately 33 bar at 0 C and 50bar at 15 C.
111
Texas, Oklahoma, Kansas, Alberta, etc., which are the main sources ofsupply. There is little associated with North Sea gas. Being lighter itrequires a greater flow rate than argon and has a 'hotter' arc which maygive rise to certain health hazards. Cylinder identifying colour is brown.Oxygen, O2. Atomic weight 16, boiling point 183C. Obtained bydistillation from liquid air. Used in connection with the inert gas in smallpercentages to assist in wetting and stabilizing the arc. Wetting is discussedon pp. 318-19 under the heading Surface tension.Application of gases(1) Argon. Although argon is a very suitable shielding gas for thenon-ferrous metals and alloys, if it is used for the welding of steel thereexists an unstable negative pole in the work-piece (the wire being positive)which produces an uneven weld profile. Mixtures of argon and oxygen areselected to give optimum welding conditions for various metals.
Fig. 2.8
112
113
He/Ar
HELIUM(He)
s7//
He/Ar/CO2
114
Filler wires*Note. BS 2901 gives specifications for Filler rods and wiresfor inert gas welding. Part 1, Ferritic steels; Part 2, Austenitic stainless steels;Part 3, Copper and copper alloys; Part 4, Aluminium and aluminium alloysand magnesium alloys; Part 5, Nickel and nickel alloys.Filler wires are supplied on convenient reels of 300 mm or more diameterand of varying capacities with wire diameters of 0.6, 0.8, 1.0, 1.2, 1.6, and2.4 mm. The bare steel wire is usually copper coated to improveconductivity, reduce friction at high feed speeds and minimize corrosionwhile in stock. Manganese and silicon are used as deoxidizers in many casesbut triple deoxidized wire using aluminium, titanium and zirconium giveshigh-quality welds and is especially suitable for use with CO 2 . Thefollowing are examples of available steel wires and can be used withargon-5% CO 2 argon-20% CO 2 and CO 2 , the designation being to BS2901 Part 1 (1970).A 18. General purpose mild steel used for mild and certain lowalloy steels. Analysis: 0.12% C; 0.9-1.6% Mn; 0.7-1.2% Si. 0.04%max S and P.
ARGON
STEEL
ALUMINIUM
ARGON/CO 2
HELIUM/ARGON
COPPER
American classification of mild steel welding wires AWS A5 18-69. Example E 70S-3E = electrode, S = bare solid electrode, 3 is a particular classification based on the asmanufactured chemical composition.
115
Metal arc gas shielded process. Recommended gases and gas mixtures forvarious metals and alloys
Metal type
Gas shield
Remarks
Carbon andlow-alloysteels
CO 2
Ar-15/20% CO 2Ar-5% CO 2Ar-5% O 2
Stainlesssteels
Aluminiumand itsalloys
Ar-5% CO 2 -O 2 2%Ar-1/2% O 275 He 23.5% Ar 1.5% CO 2He 75%-Ar 24%-O 2 1%ArgonHeliumHe 75% Ar 25%
Magnesiumand itsalloysCopperand itsalloys
ArgonHe 75% Ar 25%ArgonHeliumHe 75% Ar 25%
Nickeland itsalloys
Argon
CupronickelTitanium,zirconiumand alloys
ArgonAr 70% He 30%High purity argon
Ar 70% He 30%Ar 25% He 75%
116
The following colour codes are used for cylinders (BS 349, BS 381 C)Gas or mixture
Colour code
Acetylene, dissolvedArgon
Argon-CO 2Argon-hydrogenArgon-nitrogenArgon-oxygenCO 2 , commercial vapourwithdrawal
Black.
Helium
Brown.
Hydrogen
Signal red.
Hydrogen-high purity
Hydrogen-nitrogen
Nitrogen
Oxygen, commercial
Propane
Air
French grey.French grey. Light brunswick green band roundmiddle of cylinder.
Nitrogen-CO 2Nitrogen-oxygen
Air-CO 9
117
MOLTEN POOL
ys
WITH OR WITHOUTyGAS SHIELD
%f
SOLIDIFIED SLAG
MOLTEN SLAG
American classification of mild steel tubular welding wires; flux cored arc welding (FCAW),with and without external gas shield. Example E 70 T-l: E = electrode; 70 = tensile strength ofweld metal in 1 OOOlb/sq in. (ksi); T = tubular continuous electrode with powdered flux in core;1 = gas type and current. ( 1 , 2 - CO 2 deep; 3,4, 6, 8 - none, deep: 5 - CO 2 or none, deep; 7 none, deep; 9 - miscellaneous).
118
fed to the feed rollers of a MIG type unit. The welding gun can be straightor swan-necked and should be water cooled for currents above 400 A, andthe power unit is the same as for MIG welding.There is deep penetration with smooth weld finish and minimum spatter,and deposition rate is of the order of 10 kg/h using 2.4 mm diameter wire.The deep penetration characteristics enable a narrower V preparation to befound for butt joints resulting in a saving of filler metal, and fillet size can bereduced by 15-20%.Some of the filler wires available are:(1) Rutile type, steel, giving a smooth arc and good weld appearancewith easy slag removal. Its uses are for butt and fillet welds in mildand medium-tensile steel in the flat and horizontal-verticalposition.(2) Basic hydrogen-controlled type, steel. This is an all-positional typeand gives welds having good low-temperature impact values.(3) Basic hydrogen-controlled type, steel, with 2j% Ni for applications at - 50 C.(4) Basic hydrogen-controlled type for welding 1% Cr, 0.5% Mosteels.(5) Basic hydrogen-controlled type for welding 2.25% Cr, 1% Mosteels.Self-shielded flux cored wireSelf-shielded flux cored wires are used without an additional gasshield and can be usefully employed in outdoor or other on site draughtysituations where a cylinder-supplied gas shield would be difficult toestablish.The core of these wires contains powdered metal together with gasforming compounds and deoxidizers and cleaners. The gas shield formedprotects the molten metal through the arc and slag-forming compoundsform a slag over the metal during cooling, protecting it during solidification. To help prevent absorption of nitrogen from the atmosphere by theweld pool, additions of elements are made to the flux and electrode wire toeffectively reduce the soluble nitrogen.This process can be used semi- or fully automatically and is particularlyuseful for on-site work (Fig. 2.106).Metal cored filler wireThe wire has a core containing metallic powders with minimalslag-forming constituents and there is good recovery rate (95%) with nointerpass deslagging. It is used with CO 2 or argon-CO 2 gas shield to give
Techniques
119
welds with low hydrogen level (less than 5 ml/100 g weld metal). Theequipment is similar to that used for MIG welding, and deposition rates arehigher than with stick electrodes especially on root runs.Safety precautionsThe precautions to be taken are similar to those when metal arcwelding, given on pp. 29-30. The BS 679 recommended welding filters are upto200 A, 10or 11 EW(electricwelding); over200 A, 12,13, or HEW. Whenwelding in dark surroundings choose the higher shade number, and inbright light the lower shade number. Because there is greater emission ofinfra-red energy in this process a heat absorbing filter should be used. Thestudent should consult the following publications for further information:BS 679, Filtersfor use during welding, British Standards Institution; Electricarc welding, new series no. 38, Safety, health and welfare. Published for theDepartment of Employment by HMSO.
TechniquesThere are three methods of initiating the arc. (1) The gun switchoperates the gas and water solenoids and when released the wire drive isswitched on together with the welding current. (2) The gun switch operatesthe gas and water solenoids and striking the wire end on the plate operatesthe wire drive and welding current (known as 'scratch start'). (3) The gunswitch operates gas and water solenoids and wire feed with welding current,known as 'punch start'.The table on p. 115 indicates the various gases and mixtures at present inuse. As a general rule dip transfer is used for thinner sections up to 6.4 mm
FLUX CORE
SHIELDING GAS(ft SUPPLIED BY FLUX CORE^-SOLIDIFIED SLAG
PARENT PLATE
120
and for positional welding, whilst spray transfer is used for thicker sections.The gun is held at an angle of 80 or slightly less to the line of the weld toobtain a good view of the weld pool, and welding proceeds with the nozzleheld 6-12 mm from the work (see Fig. 2.11a). Except under specialconditions welding takes place from right to left. If welding takes place forspecial reasons from left to right the torch has to be held at almost 90 to theline of travel and care must be taken that the gas shield is covering the work.The further the nozzle is held from the work the less the efficiency of thegas shield, leading to porosity. If the nozzle is held too close to the workspatter may build up, necessitating frequent cleaning of the nozzle, whilearcing between nozzle and work can be caused by a bent wire guide tubeallowing the wire to touch the nozzle, or by spatter build-up shortcircuiting wire and nozzle. If the wire burns back to the guide tube this maybe caused by a late start of the wire feed, fouling of the wire in the feedconduit or the feed rolls being too tight. Intermittent wire feed is generallydue to insufficient feed roll pressure or looseness due to wear in the rolls.Excessively sharp bends in the flexible guide tubes can also lead to thistrouble.Root runs are performed with no weave and filler runs with as littleweave as possible consistent with good fusion since excessive weaving tendsto promote porosity. The amount of wire projecting beyond the contacttube is important because the greater the projection, the greater the PReffect and the greater the voltage drop, which may reduce the weldingcurrent and affect penetration. The least projection commensurate withFig. 2.11. (a) Angle of torch (flat position), (b) Stubbing, (c) Dip transfer onthin sheet.
CONTACTTUBE
VISIBLESTICKOUT
121
accessibility to the joint being welded should be aimed at. Backing stripswhich are welded permanently on to the reverse side of the plate by the rootrun are often used to ensure sound root fusion. Backing bars of copper orceramics with grooves of the required penetration bead profile can be usedand are removed after welding. It is not necessary to back-chip the roof runof the light alloys but with stainless steel this is often done and a sealing runput down. This is a more expensive way compared with efficient backpurging. The importance of fit-up in securing continuity and evenness ofthe penetration bead cannot be over-emphasized.Flat welds may be slightly tilted to allow the molten metal to flow againstthe deposited metal and thus give a better profile. If the first run has a veryconvex profile poor manipulation of the gun may cause cold laps in thesubsequent run.Run-on and run-off plates can be used as in TIG welding to obviate coldstart and crater finishing leading to cracks. Slope in and out controlsobviate much of this.Stubbing
If the wire speed is too high the rate of feed of the wire is greaterthan the burn-off rate and the wire stubs. If a reduction in the wire speedfeed rate does not cure the stubbing, check the contact tube for poorcurrent pick-up and replace if necessary (Fig. 2. Mb).Burn back control
This operates a variable delay so that the wire burns back to thecorrect 'stick-out' beyond the nozzle before being switched off. It is thenready for the next welding sequence. Excessive burn back would cause thewire to burn to the contact tip. Varying the stick-out length (Fig. 2. Ma)varies the temperature of the molten pool. Increasing the length gives asomewhat 'cooler' pool and is useful in cases of poor fit-up, for example.The nearer that the contact tube end is to the outer end of the torchnozzle, the greater the likelihood of the contact tube being contaminatedwith spatter. With dip transfer, in which the spatter is least, the distance isabout 2-3 mm, but for spray transfer it should be in the region of 5-12 mm.The contact tube may even be used slightly projecting from the gas nozzlewhen being used on thin sheet (e.g. body panels) using dip transfer. Thisgives a very clear view of the arc but is not recommended as the contact tubebecomes rapidly contaminated even when treated with anti-spatter paint orpaste and must be cleaned frequently (Fig. 2.1 \c.) Whatever the stick-out,the flow of shielding gas should be such that molten pool and immediatesurrounding areas are covered.
122
Positional weldingThis is best performed by the dip transfer method since the lowerarc energy enables the molten metal to solidify more quickly afterdeposition. Vertical welds in thin sections are usually made downwardswith no weave. Thicker sections are welded upwards or with the root rundownwards and subsequent runs upwards, weaving as required. Overheadwelding, which is performed only when absolutely necessary, is performedwith no weave.Fillet welds are perf' rmed with the gun held backwards to the line ofwelding, as near as possible to the vertical consistent with a good view ofthe molten pool, bisecting the angle between the plates and with a contacttip-to-work distance of 16-20 mm (Fig. 2.12). On unequal sections the arcis held more towards the thicker section. The root run is performed with noweave and subsequent runs with enough weave to ensure equal fusion onthe legs. Tilted fillets give better weld profile and equal leg length moreeasily.Some of the filler wires available are:Note. Except where indicated they can be used with CO 2 , argon-5% CO 2and argon-20% CO 2 . CO 2 gives good results with dip transfer whereas theargon mixtures give better weld profile. L indicates 0.08% C or lower.(1) 1.5% Mn, L. Smooth arc, little slag, so no deslagging, Argon-20%CO 2 , cored wire ve.(2) 1.8% Mn, 0.5% Mo, 0.14% C. High strength mild steels and forhighet tensile steels, solid wire -f ve.(3) 1.4% Mn, 0.5% Mo, L. Similar wire to (1) but molybdenum givesextra strength. Argon-20% CO 2 , cored wire - v e .(4) 1.4% Mn, 0.45% Cu, L. A similar wire to (1) but with copper addedfor weathering steels such as Corten. Use argon-5% or argon-20%CO 2 , cored wire - v e .Fig. 2.12. Angle of torch: horizontal-vertical fillet.
(5) 1.3% Cr, 1.1% Mn, 0.2% Mo, 1.0% Ni, L. High strength welds,tensile strengths of 750 N/mm 2 . Rutile basic flux cored wire + ve.(6) 2.0% Mn, 1.0% Mo, L. Basic flux core with iron powder, creepresistant steels, cored wire ve.(7) 2.2% Cr, 1.0% Mo, 0.12% C. Basic flux core for creep-resistantsteels to temperatures of 580C, solid wire ve.(8) 2.2% Ni, L. For low temperatures to - 5 0 C . Good resistance tocracking cored wire - v e , use argon-CO 2 mixtures.Stainless steelsPreparation angle is usually similar for semi-automatic andautomatic welding for butt welds in stainless steel, being 70-80 with a0-1.5 mm gap (Fig. 3.22). Torch angle should be 80-90 with an arc lengthlong enough to prevent spatter but not long enough to introduceinstability. All oxides should be removed by stainless steel wire-brushing.Back chipping is usually performed by grinding. With spray transfer usinghigh currents there is considerable dilution effect and welds can only bemade flat, but excessive weaving should be avoided as this increasesdilution. Direct current with the torch (electrode) positive is used with ashield of argon + 1% oxygen.When welding stainless steel of any thickness it is imperative to obtaingood penetration and this is only possible if there is a good back purge.Without this the penetration has to be back chipped and a sealing run madewhich adds considerably to the cost of the joint.Back purging can be obtained simply by tack welding a strip on theunderside of the weld and removing after welding (Fig. 2.13). This usesargon from the torch and reduces oxide formation on the penetration bead.Back purging of tubes can often be done using soluble paper dams or pipedbladders which are blown up in position inside the pipe and serve to containthe inert gas on the underside of the weld, thus effecting considerablesaving.Fig. 2.13. Butt welding stainless steel MIG, 99% A - 1 % O 2 , d.c. wire positive.Automatic or semi-automatic.
70-75
0-0.8 mm GAP^TACK WELDSTRIP FORBACK PURGE
124
AISI
308S92
AWS
321, 347316S92
A59 ER 316L
316,316L318
316S96
316,318
347S96
347,321,304
309S94
347
Nickel alloysThe welding of nickel and nickel alloys can be done using spraytransfer and short circuit (dip transfer) arc methods.Spray transfer with its higher heat input gives high welding speeds anddeposition rate and is used for thicker sections, usually downhand becauseof the large molten pool. Argon is used as the shielding gas but 10-20%
125
helium can be added for welding Nickel 200 and INCONEL alloy 600,giving a wider and flatter bead with reduced penetration. The gun shouldbe held as near to 90 to the work as possible, to preserve the efficiency ofthe gas shield, and the arc should be kept just long enough to preventspatter yet not long enough to affect arc control.Short circuiting arc conditions are used for thinner sections andpositional welding, the lower heat input giving a more controllable moltenpool and minimum dilution. The shielding gas is pure argon but theaddition of helium gives a hotter arc and more wetting action so that thedanger of cold laps is reduced. To further reduce this danger the gun shouldbe held as near as possible to 90 to the work and moved so as to keep thearc on the plate and not on the pool. High-crowned profile welds increasethe danger of cold laps.The table in chapter 3 (p. 181) on TIG welding of nickel alloys indicatesmaterials and filler metal suitable for welding by the MIG process andFig. 3.28 the recommended methods of preparation.Aluminium alloysWhen fabricating aluminium alloy sections and vessels, the platesand sections are cut and profiled using shears, cold saw, band saw or arcplasma and are bent and rolled as required and the edges cut to thenecessary angle for welding where required. {Note. As the welding currentsemployed in the welding of aluminium are high, welding lenses of a deeperthan normal shade should be used to ensure eye protection.)The sections are degreased using a degreaser such as methyl chloride andare tack welded on the reverse side using either TIG or MIG so as to give asfar as possible a penetration gap of close tolerance. Where this is excessive itcan be filled using the TIG process, and pre-heating may be performed fordrying. The areas to be welded are stainless steel wire brushed to remove alloxide and the root run is made. Each successive run is similarly wirebrushed and any stop-start irregularities should be removed. It isimportant that the tack welds should be incorporated into the overheadcompletely so that there is no variation in it. Back-chipping of the root run,where required for a sealing run, should be performed with chisels, routersor saws and not ground, as this can introduce impurities into the weld.Back-chipping and a sealing run add substantially to the cost of a weldedseam. In many cases it can be avoided by correctly backpurging the seamand welding from one side only. Fig. 2.14 and table indicate typical buttweld preparation in the flat position using 1.6 mm filler wire. Fig. 2.15ashows the section of a MIG weld in aluminium and Fig. 2. \5b a TIG weldon the preparation bead of Fig. 2.15a.
126
Plate(mm)
l^iitnHerof runs
Root
Subsequent
(mm)
6 and 89.5 and 1112.7 and 161922 and 25
23456
220230230-240240-250240-260
250-280260-280270-290280-310280-330
1.61.63.23.24.8
R n o t f*nr*p
Refer also to BS 3571 General recommendations for manual inert gas metal arcwelding of aluminium and aluminium alloys.Suitable filler wires are given on p. 175.Fig. 2.14. Flat butt weld preparation, aluminium plate MIG, semi-automaticprocess argon shield. Work negative.60-70
GAP 0 - 1 . 6 mm
Fig. 2.15. (a) MIG weld in aluminium 5083 (NS8) plate 8 mm thick with5556 A (NG61) wire. Stainless steel backing bar.1st run: 250-270 A, 26-27 V, speed 9-10 mm/second.2nd run: 260-280 A, 28-29 V, speed 8-10 mm/second.Preparation: 90 V, 0-1 mm root gap, 3-4 mm root face.
127
Fig. 2.15. (b) TIG weld on penetration bead of the above weld. No backchipping, no filler wire (can be added if required). 350 A, 32 V, speed3-4 mm/second. Section etched with cupric chloride CuCl2 followed by a 50%nitric acid wash.
128
GradePhosphorus deoxidized,non-arsenicalPhosphorus deoxidized,arsenicalElectrolytic tough pitch,high conductivityFire refined tough pitch,high conductivityOxygen-free, highconductivity
C107C101C102C103
Argon orhelium shield
Nitrogenshield
Notrecommended
C7, C21
Fig. 2.16. Edge preparation for TIG and MIG butt welds in copper.EDGE
THICKNESS(mm)
PREPARATION
NUMBEROF RUNS1
1.5FLANGE BUTT
0-1.5 mmROOT GAPSQUARE BUTT60-90
60-901-2
0-1.5
mm ROOT GAP
SINGLE V BUTT
0 - 1 . 5 mm ROOT GAP1.5 m m ROOT FACESINGLE
V BUTT
2-4
120-1.5
1 . 5 - 3 mm ROOT FACESINGLE U BUTT
60-90
XT74-8
180-1.5
DOUBLE V BUTT
1 . 5 - 3 mm ROOT FACEDOUBLE U BUTT
129
130
Gap(mm)
Wire feed(m/minute)
Arc(volts)
11.21.62.02.53.0
000.50.80.81.5
2.8-3.83.2-4.04.0-4.85.8-7.07.0-8.47.0-8.4
16-1718-1919-2019-2020-2120-21
65-8070-8585-95110-125125-140125-140
Economic considerationsAlthough filler wire for the CO 2 process, together with the cost ofthe shielding gas, is more expensive than conventional electrodes, otherfactors greatly affect the economic viability of the process. The depositionrate governs the welding speed which in turn governs the labour charge on agiven fabrication.The deposition rate of the filler metal is a direct function of the weldingcurrent. With metal arc welding the upper limit is governed by the
131
THICKNESS (mm)
6.4
11 0.8 mm GAPBACKING STRIP60
9.5-12.5
/ O.Qmm GAP
30-40
VBACKING STRIP0.8 mm GAP
50-60
OVER 12.5
1 - 2 mm GAP J (
3 mm ROOT FACE
132
When welding thin steel sections with a dip transfer arc, argon-CO 2mixtures are often preferred because there is a lower voltage drop across thearc which thus gives a cooler molten pool and prevents burn-through,especially if the fit-up is poor.Details of plate preparation are given as a guide only, since there are toomany variables to give generalized recommendations (see Figs. 2.18 and2.19).
Automatic weldingAutomatic welding, by MIG, pulse and CO 2 processes, now playsan important part in welding fabrication practice. It enables welds ofconsistently high quality and accuracy to radiographic standard to beperformed at high welding speeds because of the close degree of controlover the rate of travel and nozzle-to-work distance. It is less tolerant thansemi-automatic welding to variations of root gap and fit-up but reduces thenumber of start-stop breaks in long sequences. The choice between semiautomatic and automatic process becomes a question of economics,involving the length of runs, number involved, volume of deposited metal ifthe sections are thick, method of mechanization and set-up time. Thetorches are now usually air cooled even for currents up to 450 A and arecarried on welding heads fitted with controls similar to those used for semiautomatic welding, and may be remote controlled (Fig, 2.20).The head may be: (1) fixed, with the work arranged to move or be rotatedbeneath it, (2) mounted on a boom and column which can either be of theFig. 2.19. (a) Unprepared fillets, (b) multi-run prepared fillets in thick plate, (c)deep preparation fillets, (d) multi-run unprepared fillet. CO2 welding.
Automatic welding
133
positioning type in which the work moves, or the boom can traverse overthe work (Figs. 2.21a and b), (3) gantry mounted so as to traverse over thestationary work, (4) tractor mounted, running on guide rails to move overthe fixed work, (5) mounted on a special machine or fixture designed for aspecific production. A head may carry two torches arranged to weldsimultaneously, thus greatly reducing the welding time.For the CO 2 process in steel a typical example would be with wire of1.2 mm diameter using 150-170 A on thinner sections and multiple passesup to 30 on thicknesses up to 75 mm with current in the 400-500 A rangeand 2.4 mm wire. With automatic surge (pulse) arc welding on stainless
134
135
Fig. 2.21. (b) Extra heavy duty column and boom and roller bed.
(a)
OPoweron
CyclomaticFrequency
Amplitude
Arc position
QProbeTemperature
Stabilize O s c i l l a t e(b)
Dwell
136
The arc can be stabilized or oscillated by the applied magnetic field andmagnetic and non-magnetic materials are equally well welded when usingthis system. Controls on the unit enable the sweep frequency to be variedfrom 0 to 100 oscillations per second while sweep amplitude and arcposition are controllable and proportional to the arc length in anapproximately 1:1 ratio. There is controllable variable dwell on each sideof the oscillation in order to obtain good fusion, arc blow is counteractedand the heat imput can be balanced when welding thin to thick sections,and undercut is minimized. Porosity is decreased and the system isapplicable, for example, to the welding of thicker stainless steel sectionsresulting in reduced danger from cracking, reduced porosity and greaterweld reliability. This method of arc stabilization and control is nowbecoming increasingly popular as MIG and submerged arc weldingbecome more automated.Seam trackerThis unit bolts on to the head of the welding torch and enables thetorch to follow accurately the line of the joint to be welded.The torch head is placed over the seam or joint and the tracker keeps thearc over the seam with an accuracy of less than 0.25 mm.One type has an electro-mechanical sensor which responds to themovement of the probe tip which moves along the seam. The signals aresent by the probe to the solid state control which operates two linear slideswhose axes are at right angles to each other, one horizontal and the othervertical. These are driven by small d.c. motors and keep the welding head inplace exactly over the seam to be welded, which keeps the torch-to-workdistance constant (Fig. 2.23).Fig. 2.23. Programmable seam tracker.
INTERCHANGEABLE TIPFOR VARYING REQUIREMENTSOF EACH TYPE OF WELD
137
The optical seam tracker using flexible fibre optics for operation andwith microcircuit control operating the cross slides as in the previous unitkeeps the torch head accurately over the joint, which should be a tightmachined edge butt weld, although this system can tolerate a gap of 2 mmand still keep the torch central to the joint.MIG spot weldingSpot welding with this process needs access to the joint on one sideonly and consists of a MIG weld, held in one spot only, for a controlledperiod of time. Modified nozzles are fitted to the gun, the contact tip beingset 8-12 mm inside the nozzle, and the timing unit can either be built intothe power unit or fitted externally, in which case an on-off switch doesaway with the necessity of disconnecting the unit when it is required forcontinuous welding. The timer controls the arcing time, and welds can bemade in ferrous material with full or partial penetration as required. Atypical application of a smaller unit is that of welding thin sheet as used oncar bodies. The spot welding equipment timer is built into a MIG unit andis selected by a switch. Wire of 0.6 mm diameter is used with argon + CO25% + O 2 2% as the shielding gas. Currents of 40-100 A are available at1417 V for continuous welding with a maximum duty cycle of 60%. Thespot welding control gives a maximum current of 160 A at 27 V, enablingspot welds to be made in material down to 0.5 mm thickness, the timingcontrol varying from 0.5-2.0 seconds.On larger units arcing time can be controlled from 0.3 to 4.5 seconds withselected heavier currents enabling full penetration to be achieved on ferrousplate from 0.7 to 2.0 mm thick and up to 2.5 mm sheet can be welded on toplate of any thickness.Cycle arc welding is similar to spot welding except that the cycle keeps onrepeating itself automatically as long as the gun switch is pressed. Theduration of the pause between welds is constant at about 0.35 seconds whilethe weld time can be varied from 0.1 to 1.5 seconds. This process is used forwelding light-section components which are prone to burn-through. In thepause between the welding period, the molten pool cools and just solidifies,thus giving more accurate control over the molten metal.
138
at regular frequency and thus results in a lower heat output than with purespray transfer, yet greater than that with dip transfer. Because of this,thinner sections can be welded than with spray transfer and there is nodanger of poor fusion in a root run as sometimes occurs with dip transferand positional welding is performed much more easily. There is regularand even penetration, no spatter and the welds are of high quality andappearance.To obtain these conditions of transfer it is necessary to have two currentsfed to the arc: {a) a background current which keeps the gap ionized andmaintains the arc and (b) the pulsed current which is applied at 50 or 100 Hzand which melts off the wire tip into a droplet which is then projected acrossthe arc gap. These two currents, which have critical values if satisfactorywelding conditions are to be obtained, are supplied from two sources, abackground source and a pulse source contained in one unit, and theirvoltages are selected separately. The background current, of much lowervalue than the pulse, is half a cycle out of phase with it (see Figs. 2.24a andb). A switch enables the pulse source to be used for dip and spray transfermethods as required. The power supply is a silicon rectifier with constantvoltage output and a maximum current value of about 350 A at opencircuit voltages of 11-45 V similar to those already described.To operate the unit, the 'pulse height' (the value of pulse current) and thebackground current are selected on separate switches, the wire is adjustedto protrude about 10 mm beyond the nozzle and welding is commenced
JECTED
TIMETIP A T BEGINNINGOF PULSE
TIME
139
moving from right to left down the line of the weld with the gun making anangle of 60-70 with the line of weld. When welding fillets the gun is usuallyheld at right angles to the line of weld with the wire pointing directly intothe joint, and thus an excellent view is obtained of the degree of fusion intothe root; welding is again performed from right to left. The process givesgood root fusion with even penetration and good fill-in and is especiallyefficient when used fully automatically. As in all other welding processes,welding is best performed flat but positional welding with pulsed arc is verysatisfactory and relatively easy to perform. Thicknesses between 2 mm and6.5 mm which fall intermediate in the ranges for dip and spray transfer areeasily welded. One of the drawbacks to pulse arc is the necessity to ensureaccurate fit-up. If there are any sizeable gaps a keyhole effect is producedand it is impossible to obtain a regular underbead. The gap should be of theorder of from 0 to about 1.0 mm max. The shielding gas is argon with 1% or2% oxygen or argon with 5% CO 2 and 2% oxygen for welding mild and lowalloy steels, stainless steel and heat-resistant steel, and pure argon foraluminium and its alloys, 9% nickel steel and nickel alloys. Pulse arc isespecially useful when used automatically for stainless steel welding, sincethe accurately formed under- or penetration bead obviates the expensiveoperation of back-chipping and a sealing run and there is little carbon pickup and thus little increase of carbon content in the weld. Aluminiumrequires no back purge and for the back purge on stainless steel a thin stripof plate can be tack welded on the underside of the joint (see Fig. 2.13) andremoved after welding. The argon from the torch supplies the back purgeand prevents oxidation of the underside of the weld.There is good alloy recovery when welding alloy steel and because of theaccurate heat control, welding in aluminium is consistently good withoutporosity and a regular underbead so that it can be used in place of doubleargon TIG with a saving of time and cost.Fabrications and vessels can be fully tack weld fabricated with TIG onthe underside of the seam and pulse arc welded, greatly reducing theFig. 2.25. Automatic pulsed arc welding of stainless steel, flat, 99% argon-1%oxygen.65-70
BACK CHIP-GRINDINGAND SEALING RUN
" ''6
mm
GAP
140
tendency to distortion. The torch should be held at 75-80 to the line of theweld and good results are also obtained fully automatically by weldingfrom left to right with the torch held vertically to the seam. This methodallows greater tolerance in fit-up and preparation with better penetrationcontrol. Because this process is sensitive to the accuracy of fit-up andpreparation, care should be taken to work to close tolerances and excessivegaps should be made up from the reverse side with, for example, the TIGprocess, and then carefully cleaned.Fig. 2.25 and the table give a typical preparation for automatic flat buttwelds in stainless steel using 99% A, 1% O 2 as shielding gas and 1.6 mmdiameter filler wire. For the alloys of nickel the recommended shielding gasis pure argon. A similar technique is used as for the MIG welding ofstainless steel, with a slight pause each side of the weave to avoid undercut.Current (A)Plate thickness(mm)
Runs
4.8, 6.4, 89.5
Volts(approx.)27-2827-28
141
Research work during the late 60s and early 70s had demonstrated thatfor each wire diameter/material combination there is a specific dropletsize for optimum metal transfer. In fact, the diameter of this droplet isvery nearly equal to the wire diameter. Further, for each wire, specificpulse parameters, i.e. peak current and pulse width, can be defined todetach such a droplet.With the advent of electronically controlled and transistorized powersources, it became possible to generate wave shapes that were rectangularinstead of sinusoidal (Fig. 2.26c). Equally, since the output was no longersynchronized to mains frequency, the pulse frequency could now bevaried from well below 50 Hz to in excess of 300 Hz and functions likeFig. 2.26(0)CURRENT
TIMEBACKGROUNDCURRENT
Fig. 2.26(6)
VOLUME OFMETALTRANSFERREDPER PULSE
OPTIMUM REGION
Fig. 2.26(c)PULSE CURRENT PULSE4DURATION FREQUENCY
PULSECURRENTFREQUENCY-
BACKGROUNDCURRENT
142
Fig. 2.26(d)
CURRENT-*
L ROPLlETS
p.
A VERAGE CURRENT
e.g. 140/1WIRE FEED SPEED5 m/min
PULSE 'FREQUENCYFREQUENCYDROPLETDROPLET
AVERAGE CURRENTE.G. SO A
143
CONNECTOR-riCONTACT CONTROL SWITCHIWIRE SELECTOR SWITCH
^hoN/OFF
FAULT LAMP
murex
Synergic 500MULTIPROCESS
j"POSITIVE WELDING OUTPUT
144
arc voltage trim function enabling the operator to adjust the arc lengthto suit specific needs.Two such modern synergic units are shown in Figs. 2.26e and 2.26/Plasma MIGprocess. A process is being developed in which MIG filler wireis fed through a contact tube situated centrally in the torch head. Atungsten electrode is set at an angle to this contact tube and projects nearlyto the mouth of the shielding nozzle through which the plasma gas issues.An outer nozzle provides a gas shield. The current through the wire assistsFig. 2.26. (/) Ultra-arc 350 synergic transistorized pulsed MIG. Spray transferone-knob synergic control of five parameters: pulse current, pulse time,background current, pulse frequency and wire feed speed. Input 200, 230 or460 V 3-phase. Single current control 50-350 A. Constant energy CC and CVwhich reduces shrinkages and distortion. The constant energy is irrespective ofthe stick out and makes welding of difficult ferrous metals easier, smooth arc.Micro processor control has nine preset programs e.g. mild steel of two sizesusing 95% Ar, 5% CO 2 ; stainless steel of three sizes using 98% Ar, 2% O 2 ;silicon bronze of two sizes using 100% Ar; and aluminium of two sizes using100% Ar. (See Appendix 10, p. 433, for photograph of plant.)
A VERAGE AMPERAGECONTROL
5 A BREAKERLOCKABLE PROGRAM/WELD SWITCH
REMOTE/LOCALCONTROL SWITCH
SCHEDULE SELECTOR(PROGRAM)
TERMINAL-
+ TERMINAL
145
the melting and gives good starting characteristics and a stable arc, so thatthin plate is weldable at high welding speeds.Repair of cast iron by automated MIG process using tubular electrodes. Withthe advent of flux cored wire (2.10#) carbon can be added to the core andhigh speed welding performed using high nickel iron wire. As an example,nickel FC 55 is a tubular wire, the core being filled with carbon, slaggingconstituents and deoxidizers. It can be used with or without a shielding gassuch as CO 2 and no post-weld heat treatment is required. Standardgas-metal arc equipment is used, the joints have high strength and the HAZis free from the carbide complex which can cause embrittlement. It makespossible the automatic welding of cast irons to themselves or to stainlesssteel or high nickel alloys and can be used for overlaying and metal arc spotwelding.Fig. 2.27. Gas mixing system for mixing shielding gases.
WELDING SHOP
146
Fig. 3.1. Connexions for inert gas welding using air-cooled torch.COMBINED WELDING CABLE AND GAS TUBE
COUPLINGFLOW
METER
REGULA TORTORCH/
-EARTH
147
148
(See also BS 3019, General recommendations for manual inert gas tungstenarc welding. Part 1, Wrought aluminium, aluminium alloys and magnesiumalloys', Part 2, Austenitic stainless and heat resisting steels.)The arc burns between a tungsten electrode and the workpiece within ashield of the inert gas argon, which excludes the atmosphere and preventscontamination of electrode and molten metal. The hot tungsten arc ionizesargon atoms within the shield to form a gas plasma consisting of almostequal numbers of free electrons and positive ions. Unlike the electrode inthe manual metal arc process, the tungsten is not transferred to the workand evaporates very slowly, being classed as 'non-consumable'. Smallamounts of other elements are added to the tungsten to improve electronemission. It is, however, a relatively slow method of welding.GasesArgon in its commercial purity state (99.996%) is used for metalsnamed above, but for titanium extreme purity is required. Argon with 5%hydrogen gives increased welding speed and/or penetration in the weldingof stainless steel and nickel alloys; nitrogen can be used for copper weldingon deoxidized coppers only. Helium may be used for aluminium and itsalloys and copper, but it is more expensive than argon and, due to its lowerdensity, a greater volume is required than with argon to ensure adequateshielding, and small variations in arc length cause greater changes in weldconditions. A mixture of 30% helium and 70% argon is now used, and givesfast welding speeds. The mechanized d.c. welding of aluminium withhelium gives deep penetration and high speeds.The characteristics of the arc are changed considerably with change ofdirection of flow of current, that is with arc polarity.Electrode positiveThe electron stream is from work to electrode while the heavierpositive ions travel from electrode to work-piece (Fig. 3.2a). If the work isof aluminium or magnesium alloys there is always a thin layer of refractoryoxide of melting point about 2000C present over the surface and whichhas to be dispersed in other processes by means of a corrosive flux to ensureweldability. The positive ions in the TIG arc bombard this oxide and,together with the electron emission from the plate, break up and dispersethe oxide film. It is this characteristic which has made the process sosuccessful for the welding of the light alloys. The electrons streaming to thetungsten electrode generate great heat, so its diameter must be relativelylarge and it forms a bulbous end. It is this overheating with consequentvaporization of the tungsten and the possibility of tungsten being
149
The electron stream is now from electrode to work with the zone ofgreatest heat concentrated in the workpiece so that penetration is deep andthe pool is narrower. The ionflowis from work to electrode so that there isno dispersal of oxidefilmand this polarity cannot be used for welding thelight alloys. The electrode is now near the zone of lesser heat and needs beof reduced diameter compared with that with positive polarity. For a givendiameter the electrode, when negative, will carry from four to eight timesFig. 3.2. Electron streams between electrode and work: (a) d.c, tungstenelectrode +ve of large diameter tends to overheat; (b) d.c, tungsten electrode ve of small diameter; (c) a.a, electrode diameter between that of electrode+ ve and ve electrode.
GAS SHIELD
OXIDE FILMIS DISPERSED
WIDE
ZONE OFPOOLGREATEST HEAT 'WORK-VE'///////////////////////////////////s/s
ZONE OFGREATEST HEAT'/////////////.
SHALLOW
DEEP ANDNARROW POOL
WORK + VE ,y
DEPTH OF PENETRATIONBETWEEN THAT OFELECTRODE +VE AND
,^IK/"""ffl(c)
'////////////////////////////////////A
the current than when it is positive and twice as much as when a.c. is used.(Fig. 3.2b.)Alternating currentWhen a.c. is used on a 50 Hz supply, voltage and current arereversing direction 100 times a second so that there is a state of affairsbetween that of electrode positive and electrode negative, the heat beingfairly evenly distributed between electrode and work (Fig. 3.2c). Depth ofpenetration is between that of electrode positive and electrode negative andthe electrode diameter is between the previous diameters. When theelectrode is positive it is termed the positive half-cycle and when negativethe negative half-cycle. Oxide removal takes place on the positive halfcycle.See note on square wave equipment and wave balance control(pp. 160-3).Inherent rectification in the a.c. arcIn the a.c. arc the current in the positive half-cycle is less than thatin the negative half-cycle (Fig. 3.3b). This is known as inherent rectificationand is a characteristic of arcs between dissimilar metals such as tungstenand aluminium. It is due to the layer of oxide acting as a barrier layer to thecurrent flowing in one direction and to the greater emission of electronsfrom the tungsten electrode when it is of negative polarity. The result of thisimbalance is that an excess pulsating current flows in one direction only andthe unbalanced wave can be considered as a balanced a.c. wave, plus anexcess pulsating current flowing in one direction only on the negative halfcycle. This latter is known as the d.c. component and can be measured with
Fig. 3.3. Alternating current: (a) balanced wave; (b) unbalanced wave, inherentrectification (current in + ve half-cycle less than that in ve half cycle).+ VEHALFCYCLE
HALFCYCLE(a)+ VEHALFCYCLE-VEHALFCYCLE(b)
151
152
HV IRON CORETRANSFORMER
MAINSSUPPLY
CAPACITOR
SPARKGAP
1ARC VOLTS
TRAINS
153
(although for re-ignition purposes it is required only for the positive halfcycle) and is of about 5 milliseconds or less duration compared with thehalf-cycle duration of 10 milliseconds (Fig. 3.7). To initiate the arc, theelectrode is brought to about 6 mm from the work with the HF unit andwelding current switched on. Groups of sparks pass across the gap,ionizing it, and the welding current flows in the form of an arc withoutcontamination of the electrode by touching down. The HF unit can giverise to considerable radio and TV interference and adequate suppressionand screening must be provided to eliminate this as far as possible. The useof HF stabilization with the a.c. arc enables this method to be used foraluminium welding, although inherent rectification is still present, butpartial rectification can be reduced to a minimum by correct phasing of thespark train.Scratch start. Some units do not employ an HF unit for starting the arcwithout touch down. The tungsten is scratched momentarily onto the workand the arc is ionized. Naturally there will be some very small tungstencontamination but this will not greatly interfere with the mechanicalproperties of the joint in non-critical conditions.Lift start. In this method no HF unit is used, the tungsten electrode isplaced down upon the work where the welding is to begin. The operatorpresses a switch which connects it to the electronic control but, as yet, nocurrent flows.The torch is then lifted a little from the work (or tilted on the gasnozzle), the arc is struck as the electrode makes a gap from the work andit then slopes up to the values set for the work in hand. Upon releasingthe switch the current slopes down to zero and thus prevents theformation of a finishing crater. With this method there is no HFinterference with any other HF apparatus.Surge injection unit. This device supplies a single pulse surge of about 300 Vphased to occur at the point when the negative half-cycle changes to theFi
S- 3-7>
Sur
Se
volta
154
VOLTAGE
155
156
there may be a two position switch for high or low current ranges, andthese are usually constant voltage units.Power units, dx. and ax. These units, which supply either a.c. or d.c, areconnected to single- or three-phase 50 Hz mains, fed into a step-downtransformer and then into a thyristor which may also act as a contactorso that there are no mechanical parts to open and close when welding isbegun and ended.The thyristors, which can be switched under load, are fitted to a heatsink and the whole is forced draught cooled. Current can be supplied forMM A and TIG and output can be for electrode +ve or ve or a.c. bymeans of the controlling printed circuit.The auxiliary supply is at a lower voltage of about 110 V and there isautomatic regulation for variation of the mains voltage. In addition therecan be burn back control, soft start, pulse and spot welding facilities andthe units are suitable for using hard or soft solid core wires and flux coredwire using either short circuit or spray transfer.*Duty cycleOver a period of 10 minutes, a 60% duty cycle means that the unitcan be used at that particular current (about 275 A in Fig. 3.9b) for 6minutes and then given 4 minutes to cool down. Increasing the weldingcurrent above that recommended for the particular duty cycle increases thequantity of heat evolved and the excessive temperature rise can lead tofailure. Decreasing the welding current increases the period within the 10minutes for which the unit can be operated. Thermal cut-outs may be fittedwhich trip and prevent serious damage while thyristors are bolted to aheat sink and the whole unit force draught cooled.Exceeding the duty cycle value of current can cause overheating and maydamage the unit.Fig. 3.9. (a) Series capacitor used to block d.c. component.SERIESWELDINGTRANSFORMER
CHOKE
'-tfotiV
SMAINSSUPPLY
* A typical formula for obtaining the voltage drop V, across the arc when a current A isflowing is: V = 10+ (0.04/1). Thus a current of 70 A gives a drop of ~ 12.8 V.
157
Slope-in (slope-up) and soft start. The use of normal welding current atthe beginning of the weld often causes burn-through and increases the riskof tungsten contamination. To prevent this a slope-in control is providedwhich gives a controlled rise of the current to its normal value over apreselected period of time, which can be from 0 to 10 seconds. The softstart control is available on some equipment and performs the samefunction but it has a fixed time of operation and can be switched in or outas required.Slope-out (slope-down) (crater fill). The crater which would normallyform at a weld termination can be filled to the correct amount with the useof this control. The crater-filling device reduces the current from that usedfor the welding operation to the minimum that the equipment can supply ina series of steps. The slope-out control performs the same function, but thecurrent is reduced over a period of about 20 seconds depending upon thesetting of the control (not steps). The tendency to cracking is reduced by theuse of this control (Fig. 3.10).Fig. 3.9. (b) Illustrating how the welding current decreases as the % duty cycleof a power unit increases.350 -
S 300 -
Qc 250 H
200-
15020
30
506070DUTY CYCLE %
Fig. 3.10
SLOPE-OUT
(SECONDS)-
158
Fig. 3.11. (b) 250 a.c./d.c. TIG MMA square wave with OC/CV feeder. Available voltages 230/380/415/500 a.c. 50 Hz OCV 80. Welding mode switch5-310 A, a.c. or d.c.e.n., d.c.e.p. Pre and post flow gas 250 A at 40% duty cycle. Balance control penetration/cleaning. Arc force control (soft ordigging arc). (See Appendix 10, p. 436, for photograph of unit.)ARC FORCE CONTROL POTENTIOMETER TO SETOPTIMUM STICK WELDING CHARACTERISTICS FORA SOFT OR DIGGING ARC\a.c. BALANCE CONTROL POTENTIOMETER FOROPTIMUM PENETRATION/CLEANING ONALUMINIUMTRIGGER HOLD SWITCHPRE-FLOW TIMERRANGE: 0.1-5 sOPTIONAL SPOT TIMER KITOPTIONAL a.c./d.c. METER. FLIP SWITCHTO READ EITHER AMPS OR VOLTSAMPERAGE CONTROL POTENTIOMETERRANGE: 5-310 A
160
5Qc
161
to peak keeps the arc ionized without application of the HF. A switchenables this HF to be used continuously if required although its continuoususe may interfere with radio frequency apparatus in the vicinity.Variation in mains voltage is compensated automatically, there isprovision for MMA, pulse and spot welding and often there may be tworanges of current, either of which can be controlled by the one knob control(Fig. 3.13).Soft start (slope-up) and crater fill (slope-down) are provided with preand post-gas and water supply controls. Pulse duration, height andbackground and wave balance controls are also fitted.Fig. 3.13. Syncrowave 300 and 500 A square wave a.c, d.c, power unit forTIG and MMA welding. Input 220-576 V as required, mains voltagecompensated. 500 A model gives 500 A at 100% duty cycle. Solid statecontactors, slope-in and slope-out. Pulsed mode for improved penetration andcontrol of weld pool. Rectification by SCR's with one knob control of weldingcurrent. 300 A model has dual current range, 5-75 A and 15-375 A, 500 Amodel has single range 25-625 A. Square wave output has wave balancecontrol. Post timer for gas and water. Slope-up and slope-down (crater fill).STARTINGCURRENTCURRENTCONTROLRHEOSTATWA VEIVOL TMETERCURRENT \BALANCEPOST FLOW IREMOTE/PANELAMMETER*CONTROLTIMER/SWITCH \
ULZ/V / ML, i un
REMOTE/STD^SWITCH^STARTING^^CURRENTSWITCHHIGH^FREQUENCYsCRATER
HHHHll
FILL'/
a.c./d.c. SELECTORSWITCH
WMKKKBM
POLARITY /SWITCH /-, 'J
255BSiiHHiS5S5H55HH|PULSES PERSECOND*
- ^
PULSERON/OFFSWITCH
^%0N
=- = "M
S>AC^ GROUNDCURRENT*
TJ
ON/OFF^SWITCH
Tl A/I IZ *
1 IMt
162
Fig. 3.14. Square wave a.c. and d.c. 260 A (also a 360 A model) for a.c. andd.c. TIG and MMA, 50 Hz. Input 3-phase 380-415 V (or single phase 220 V,200 A model). Output 10-375 A, 30% duty cycle, 375 A, 35 V; 60% cycle,300 A, 32 V 100%; cycle 235 A, 29 V. Two current ranges, minimum current10 A. Pre and post flow gas, slope up and slope down, spot timer. 80 OCV.Start lift arc and HF. TIG switch latching torch. Remote and pulse controloptional extras. (See Appendix 10, p. 417, for photograph of unit.)
SLOPE-DOWN CONTROLSPOT WELD CONTROLWELD CURRENT CONTROLSLOPE-UP CONTROLa.c. WAVE BALANCECONTROLGAS PRE-FLOWCONTROLCONTROL CIRCUITFUSE (2 A)FAULT INDICATORLAMPPOWER INDICATORLAMP
POWER-
REMOTE CONTROL-)-.SOCKET (6 WAY)
PULSE CONTROLSOCKET(2 WAY)WORK RETURN CONNECTION
ELECTRODE TORCHCONNECTION
163
giving maximum cleaning but with minimum penetration. With the controlin the other direction the greatest heat is in the work so that we havemaximum penetration but with minimum cleaning (3). With d.c. TIGwelding as with MMA the control is set for a balanced wave.Electrical contactorsThe contactors control the various circuits for welding, inert gas,water flow and ancillary equipment. The contactor control voltage is of theorder of 25-45 V and if the TIG head is machine mounted, a 110 V supplyfor the wire feed and tractor is provided. The post-weld argon flowcontactor allows the arc to be extinguished without removing the torchwith its argon shield from the hot weld area, thus safeguarding the hotelectrode end and weld area from contamination whilst cooling. Anargon-water purge is also provided and contactors may be foot-switchoperated for convenience. Where the ancillary equipment is built into oneunit an off-manual metal arc-TIG switch enables the unit to be used foreither process.With the advanced SCR method of control the SCR's act as a contactorso that there are no mechanical contactors in the welding current circuit.Cooling is by heat sink and forced draught and this method is very reliablesince there are no moving parts.Gas regulator, flowmeter and economizerThe gas regulator reduces the pressure in the argon cylinder from175 or 200 bar down to 0-3.5 bar for supply to the torch (Fig. 3.16#and b). The flowmeter, which has a manually operated needle valve,controls the argon flow from 0-600 litres/hour to 0-2100 litres/houraccording to type (Fig. 3.16c).The economizer may be fitted in a convenient position near the welderand when the torch is hung from the projecting lever on the unit, argon gasand (if fitted) water supplies are cut off. A micro-switch operated by thelever can also be used to control the HF unit.Fig. 3.15. Wave balance control.ELECTRODE
ELECTRODE(1) BALANCED WAVE
164
165
Additional equipmentAdd-on equipment can be used with existing transformers andrectifiers. The equipment shown in Fig. 3.17 is fitted with a pulse generatorand can be connected to a thyristor controlled rectifier power unit or to a.c.or d.c. arc welding sources. When connected to a d.c. source the pulsegenerator is used for arc ignition only, being automatically cut off afterignition, but it cuts in again if required to establish the arc. When used withan a.c. source the pulse generator ensures arc ignition without touchdownand ensures the re-ignition of the arc when welding. Soft start, crater fill,current control with one knob and remote control facilities are also fitted.TorchThere is a variety of torches available varying from lightweight aircooled to heavy duty water cooled types (Fig. 3.18# and b). The mainfactors to be considered in choosing a torch are:(1) Current-carrying capacity for the work in hand.(2) Weight, balance and accessibility of the torch head to the work inhand.The torch body holds a top-loading compression-type collet assemblywhich accommodates electrodes of various diameters. They are securelygripped yet the collet is easily slackened for removal or reposition of theelectrode. As the thickness of plate to be welded increases, size of torch andFig. 3.16. (c) Argon flowmeter.
GAS FLOW(LITRES PER HOUR)
100BOBBIN OR FLOATRISING WITH INCREASINGFLOW RATE
50-
166
electrode diameter must increase to deal with the larger welding currentsrequired.Small lightweight air cooled torches rated at 75 A d.c. and 55 A a.c. areideal for small fittings and welds in awkward places and may be of pencil orswivel head type. Collet sizes on these are generally 0.8 mm, 1.2 mm and1.6 mm diameter. Larger air cooled torches of 75 A d.c. or a.c. continuousrating or 100 A intermittent usually have a collet of 1.6 mm diameter. Air orwater cooled torches rated at 300 A intermittent may be used withelectrodes from 1.6 to 6.35 mm diameter and can be fitted with water cooledshields while heavy duty water cooled torches with a water cooled nozzle of500 A a.c. or d.c. continuous rating and 600 A intermittent employ largerelectrodes. A gas lens can be fitted to the torch to give better gas coverageand to obtain greater accessibility or visibility.Normally, because of turbulence in the flow of gas from the nozzle, theelectrode is adjusted to project up to a maximum of 4-9 mm beyond thenozzle (Fig. 3.20). By the use of a lens which contains wire gauzes of coarseand fine mesh, turbulence is prevented and a smooth even gas stream isobtained, enveloping the electrode which, if the gas flow is suitablyincreased, can be used on a flat surface projecting up to 19 mm from thenozzle orifice, greatly improving accessibility. The lens is screwed on to thetorch body in place of the standard nozzle and as the projection ofelectrode from nozzle is increased the torch must be held more vertically tothe work to obtain good gas coverage.The ceramic nozzles (of alumina, silicon carbide or silicon nitride),Fig. 3.17. Add-on unit for TIG welding.SLOPE-INSOFT START
SLOPE-OUTCRATER FILL0-20 s
PLUG OUTLETFOR MMA WELDINGPROVIDED IFREQUIRED
INDICA TIONLED'S. REDAND GREEN.ILLUMINATE IFa.c. POWERSOURCEIS USED GREEN FORd.c.
WELDING
REMOTE CONTROLOF WELDING CURRENTREMOTE CONTROLSWITCH TO RIGHTGIVES REMOTE CONTROLFROM / m a xPOTENTIOMETER TORIGHT
RETURNGIVES REMOTECONTROL FROMADD-ON UNIT
GAS/ARGONOUTLETTORCH SWITCH
167
CAP(LONG OR SHORT)
WASHERS.
SWITCH CABLEGASWELDINGCURRENT
CERAMIC NOZZLEVARIOUS TYPESTUNGSTENELECTRODE(COLLET HELD)
Key:1. Thoriated or zirconiated tungstenelectrode (0.8, 1.2, 1.6, 2.4, 3.2 mmdiameter).2. Ceramic nozzle.3. 0 ring.4. Collet holder.5. Collet (sizes as above to take variousdiameters of electrodes).6. Electrode cap (long and short).7. Body assembly.8. Sheath.10. Argon hose assembly.
168
which direct the flow of gas, screw on to the torch head and are easilyremovable for cleaning and replacement. Nozzle orifices range from 9.5 to15.9 mm in diameter and they are available in a variety of patterns forvarious applications. Ceramic nozzles are generally used up to 200 A a.c.or d.c. but above this water cooled nozzles or shields are recommendedbecause they avoid constant replacement.Electrodes (see also BS 3019, Pts 1 and 2)The electrode may be of pure tungsten but is more generally oftungsten alloyed with thorium oxide (thoria ThO 2 ) or zirconium oxide(zirconia ZrO 2 ).The thoriated electrode is generally used with d.c.; 1 % thoriated isoften used but 2 % thoriated gives good arc striking characteristics at lowd.c. values. Although thoriated electrodes may be used for a.c. welding,it is generally better to use zirconiated.Tungsten has a melting point of 3380 C and a boiling point of5950 C so that there is only little vaporization in the arc and it retains itshardness when red hot. Though the electrodes are costly they are classedas virtually 'non-consumable'. They are supplied with a ground greyfinish to ensure good collet contact, electrode diameters being 0.5, 1.2, 2.4,3.2, 4.0, 4.8, 5.6 and 6.4 mm for zirconiated electrodes with additionalsizes for 1 % thoriated electrodes (e.g. 0.8, 8.0, 9.5 mm).Though pure tungsten electrodes may be used, thoriated tungstenelectrodes give easier starting on d.c. with a more stable arc and littlepossibility of tungsten contamination in the weld and they have a greatercurrent carrying capacity for a given diameter than pure tungsten.However, when they are used on a.c. difficulty is encountered inmaintaining a hemispherical end on the electrode. Thus zirconiatedelectrodes are preferred for a.c. welding because of good arc startingcharacteristics and the reduced risk of tungsten contamination. Zirconiated tungsten electrodes are used for high quality welds in aluminiumand magnesium.Selection of electrode size is usually made by choosing one near themaximum range for electrode and work. Too small an electrode will resultin overheating and thus contamination of the work with tungsten, whiletoo large an electrode results in arc control difficulty. Aim for a shininghemispherical end on the electrode, the lengths being usually 75 or 150mm.In the table of electrode current ratings it should be noted that thefigures given are for class 1 welding using balanced a.c. waveform. Highercurrents than these may be used by experienced welders.
169
Electrode grindingUsually electrodes need grinding to a point only when thinmaterials are to be welded. They should be ground on a fine grit, hardabrasive wheel used only for this purpose to avoid contamination, groundwith the electrode in the plane of the wheel and rotated while grinding(Fig. 3.19).Electrode current ratings (BS 3019, Pts 2 and 3)d.c.; thoriated electrodesElectrode diameter (mm)Max current (A)
0.520
0.515
aSquare wave has slightly higher values. Thoriated may be used but zirconiatedis preferable.Note. These are BS values. Experienced welders may use higher currents.Ratings on a.c. are roughly 40 % lower than using d.c. electrode ve (DCSP) and60% duty cycle.
170
UP TO 25 A
25-100 A
>
~>>
100-200 4
1504
NOT ACCEPTABLE'EYE'DIAMETER GREATER THANELECTRODE DIAMETER; TIP ISUNSTABLE. POSSIBILITY OFTUNGSTEN INCLUSIONSCHANGE TO LARGER DIAMETER ELECTRODE
150 4
Fig. 3.20. Electrode protrusion. No gas lens. In awkward places protrusion canbe increased. Gas shield must cover area being welded.
-GASNOZZLE
49 mm
171
at a value which depends upon the metal to be welded, say 140 A, and theduration is varied until the correct amount of penetration is achieved(remember that the heat input depends upon (pulse current x duration).The pulse heats up the molten pool, more filler wire is melted off,penetration is achieved and the pulse ceases; the metal then solidifies,cooling slightly ready for the next pulse.Fig. 3.21 shows a basic pulse for d.c. and a.c. and since there is suchcontrol over the molten pool, fit-up tolerances are not so severe as inwelding with non-pulsing current. Pulsed TIG is used on mild and lowalloy steels, stainless steels, heat-resistant steels, titanium, inconel, monel,nickel and aluminium and its alloys and for the orbital welding of thinpipes.The pulse frequency can be increased from about 1 to 10 pulses persecond by the use of the pulse control, while the width control varies pulsewidth and the background current control varies this as a constantpercentage of the weld current as shown in Fig. 3.22. Using these controls
Fig. 3.21. Pulsed current. Pulses are variable in frequency (pulses per second)and width (peak current).
PULSEDURATION
\,_BACKGROUt V>
fPULSEAMPLI7 UDE
LEVELTIME
172
enables the operator to control the heat input into the weld and thus theroot penetration.Safety precautionsThe precautions to be taken are similar to those when manualmetal arc welding. In addition however there is the high voltage unit usedfor arc initiation without touchdown. This unit is similar in output to thatof the car ignition coil and care should be taken when it is switched on. Donot let the electrode touch the body when switched on or a severe shock willbe felt. BS 639 recommended EW filters are graded according to weldingcurrent thus: up to 50 A, no. 8; 15-75 A, no. 9; 75-100 A, no. 10; 100-200 A,no 11; 200-250 A, no, 12; 250-300 A, no. 13 or 14.It will be noted that these filters are darker than those used for similarcurrent ranges in MMA welding. The TIG (and MIG) arcs are richer ininfra-red and ultra-violet radiation, the former requiring some provisionfor absorbing the extra associated heat, and the latter requiring the use ofdarker lenses.It is recommended that the student reads the booklet Electric arc welding,safety, health and welfare, new series no. 38; published for the DepartmentFig. 3.22
JTJITLTLTIME0TIMEPULSE FREQUENCY INCREASEI
~n~n~n~i
TIMEBACKGROUND CURRENT
173
Welding techniques
of Employment by HMSO; and also BS 679, Filters for use during welding;British Standards Institution.
Welding techniquesCarbon steelTIG welding can be used with excellent results on carbon steelsheet and pipework, and for this and other steel welds the angle of torchand rod are similar to that for aluminium, namely torch 80-90 to line oftravel and filler wire at 20-30 to the plate (Fig. 3.23). The filler wire ischosen to match the analysis of the plate or pipe.The welding of aluminium and its alloysThe table (p. 175) gives details of the filler wire types for weldingthe various alloys. Angles of torch and filler wire are shown in Fig. 3.23.Casting alloys. Those with high silicon content, LM2, LM6, LM8 andLM9, can be welded to the Al-Mg-Si alloys with Al-Si 4043 wire. Similarlythe Al-Mg casting alloys LM5 and LM10 can be welded to the wroughtalloys using 5356 wire. Serious instability of LM10 may occur due to localheating and the alloy must be solution treated after welding.
Fig. 3.23. Angles of torch and rod showing typical weld: aluminium alloy plate11 mm thick 70-80 prep., 1.5 mm root face, no gap, a.c. volts 102, arc voltsdrop, 17-18 volts: electrode 4.8 mm diameter, current 255 A, arc lengthapprox. 4 mm.
CONTACT TUBEIN NOZZLE
2-3 mm
174
Technique. The supply is a.c. and the shielding gas pure argon. Rememberthat, with TIG and MIG processes using shielding gases, the weldingposition must be protected from stray draughts and winds which willdestroy the argon shield. This is particularly important when site weldingand (waterproof) covers or a tent to protect welder and gas shields fromwind and rain must be erected if they are to be fully protected. Pre-heatingis required for drying only to produce welds of the highest quality. Allsurfaces and welding wire should be degreased and the area near the jointand the welding wire should be stainless steel wire brushed or scraped toremove oxide and each run brushed before the next is laid. After switchingon the gas, water, welding current and HF unit, the arc is struck by bringingthe tungsten electrode near the work (without touching down). The HFsparks jump the gap and the welding current flows.Arc length should be about 3 mm. Practise starting by laying the holderon its side and bringing it to the vertical position using the gas nozzle as afulcrum, or use a striking plate and get the tungsten hot before starting theweld. (This does not apply to scratch start.) The arc is held in one positionon the plate until a molten pool is obtained and welding is commenced,proceeding from right to left, the rod being fed into the forward edge of themolten pool and always kept within the gas shield. It must not be allowed totouch the electrode or contamination occurs. A black appearance on theweld metal indicates insufficient argon supply. The flow rate should bechecked and the line inspected for leaks. A brown film on the weld metalindicates presence of oxygen in the argon while a chalky white appearanceof the weld metal accompanied by difficulty in controlling the weldindicates excessive current and overheating. The weld continues with theedge of the portion sinking through, clearly visible, and the amount ofsinking, which determines the size of the penetration bead, is controlled bythe welding rate.Run-on and run-off plates are often used to prevent cold starts andcraters at the end of a run, which may lead to cracking. Modern sets haveslope-up and slope-down controls which greatly assist the weldingoperation but it is as well to practise using these plates.Preparations for single V butt joints are shown in Fig. 3.24a while 3.24bshows a backing strip in position.Tack welding and the use of jigs for line-up is similar to that used forsteel. The tacks should be reduced in size by chiseling or grinding beforewelding the seam and care should be taken, when breaking any jigs awaythat were temporarily welded in, that damage does not occur to thestructure or casting.
175
Welding techniquesAluminium and its alloys. Filler rod guide - TIG and MIG606160636082
5083
5454
5154A5251
1050A
40435356(3)
53564043
3103
53565183
535651834043535651834043535651835556A40435356(3)5183
535651835556A535651835556A5183535655556A
4043518353565154A51835356535651835154A5154A5554(2)5356
404340434043518353561050A(l)(2)53561050A(l)5154A40431050A5183535653565356(1) corrosive conditions5183(2) elevated temperatures(3) colour matching(after anodizing)Old designations1050A IB5154A NG55356 NG65183 NG84043 NG215554 NG 525556 NG 61
Parent metal
5083606160636083
No. of runs
Filler roddiam. (mm)
2.02.43.24.86.4
11122
100-110120130-160230240
2.43.23.24.84.8
Platethickness (mm)2
Butt no gap
2.4
II
3.2
176
TIG tack welding is used for line-up of plate and tube beforefinallyMIGwelding the seam. Temporary backing bars are grooved to the shape of theunderbead and made of mild or stainless steel. These help to form andshape the penetration bead when root runs cannot be made and control ofpenetration is difficult. When ungrooved bars are used they should beremoved after welding, the root run back-chipped and a sealing run made.Any backing strips to be welded in place should be of aluminium alloy, tackwelded in place and fused in with the root run.The vertical double-operator method (Fig. 3.25), using filler wire on oneside only, gives sound non-porous welds with accurate penetration beadcontrolled by one operator 'pulling through' on the reverse side. There isexcellent argon shielding from both sides but the method is expensive inman-hours of work and needs more skill. It however reduces residualstresses as there is less total heat input and welding speed is increased.Magnesium and magnesium alloysEquipment is similar to that for the aluminium alloys and thetechnique similar, welding from right to left with a short arc and with thesame angles of torch and filler rod, with pure argon as the shielding gas andan a.c. supply. Little movement of the filler rod is required but withmaterial over 3 mm thick some weaving may be used. For fillet welding thetorch is held so as to bisect the angle between the plates and at sufficientangle from the vertical to obtain a clear view of the molten pool, withFig. 3.24. (a) Manual TIG process: preparation of aluminium and aluminiumalloy plate. Single V butt joints. Flat. Plate thickness 4.8 mm-9.5 mm, rootrun may be back chipped and a sealing run made, though this adds to the costof the weld.75-80*
0 - 1 . 6 mm^ *"
1.5-3mm|34.5 mm
177
enough weave to obtain equal leg fusion. Tilted fillets are used to obtainequal length.The material is supplied greased or chromated. Degreasing removes thegrease and it is usual to remove the chromate by wire brushing from the sideto be welded for about 12 mm on each side of the weld and to leave thechromate on the underside where it helps to support the penetration bead.No back purge of argon is required. The surface and edges should be wirebrushed and the filler rod cleaned before use. Each run should be brushedbefore the next is laid.Backing plates can be used to profile the underbead and can be of mildsteel, or of aluminium or copper 6.4-9.5 mm wide, with grooves 1.6-3.2 mmdeep for material 1.6-6.4 mm thick. (Fig. 3.26.)Jigs, together with correct welding sequence, can be used to preventdistortion, but if it occurs the parts can be raised to stress relieftemperatures of approximately 250-300C. Ensuring sufficient flow ofargon will prevent any oxidized areas, porosity, and entrapped oxides andnitrides.Welding rods are of similar composition to that of the plate and the tableindicates the relative weldability of similar and dissimilar alloys. It is notrecommended that the Mg-Zr alloys should be welded to alloys containingAl or Mn.Fig. 3.25. (a) Angles of torches and filler wire, (b) Double operator verticalwelding aluminium alloys.10-20
^ROUNDED
35(b)
CORNERS
rru
178
Zn%
Zr%
RE%
RZE 1RZ5ZT1TZ6MSR BAM503
2.0-3.03.5-5.01.7-2.55.2-6.00.20.03
0.5-1.00.4^-1.00.5-1.00.5-1.00.4-1.00.01
2.5-4.01.2-1.750.10.22.2-2.7
AZ31
0.7-1.3
A8
0.4-1.0
Others%
MEL weldingrod typeW6W7W1W 12W 13W2
2.5-4.0 Th1.5-2.2 Th2.0-3.0 Ag1.3-1.7 Mn0.02 Ca2.5-3.5 Al, 0.04 W 15CaW 140.1 Sn, Cu, Si,Fe, Ni, to ().4max, 7.5-8. 1 Al
0.9-1.6
70-904.8
9.5
179
For fillet welds the torch is held at about 90 to the line of travel androughly bisecting the angle between the plates, so that the nozzle is clear ofeither plate, and it is often necessary to have more projection of the wirebeyond the nozzle to give good visibility, but it should be kept to aminimum. Tilted fillets give a better weld profile and equal leg length. Thetable gives recommended filler wires for the various alloys.Stainless and heat-resistant steelThe production welding of stainless steel by this process is apt tobe rather slow compared with MMA, MIG or pulsed arc. (See the sectionon the MMA welding of stainless steel.)Areas adjacent to the weld should be thoroughly cleaned with stainlesssteel wire brushes and a d.c. supply with the torch negative used. Theshielding gas is pure argon or argon-hydrogen mixtures (up to 5%) whichgive a more fluid weld pool, faster rate of deposition (due to the highertemperature of the arc), better 'wetting' and reduction of slag skin by thehydrogen.The addition of oxygen, CO 2 or nitrogen is not recommended. Jointpreparation is given in Fig. 3.27.
Fig. 3.27. Preparation of stainless steel and corrosion- and heat-resistant steels.(TIG and MIG.)MATERIALTHICKNESS
4fe
BELOW2 mm
2 mm
{b) PREFERRED
3.2 mm
60-80
BACKING BAR ORARGON BACK PURGE
60-804.8 mm
2 mm ROOT FACE
~ BACKING BAR ORBACK PURGE
Technique. The torch is held almost vertically to the line of travel and thefiller rod fed into the leading edge of the molten pool, the hot end neverbeing removed from the argon shield. Electrode extension beyond thenozzle should be as short as possible: 3.0-5.0 mm for butt and 6.0-11.0 forfillets. To prevent excessive dilution, which occurs with a wide weave,multi-run fillet welds can be made with a series of 'stringer beads'. The arclength should be about 2 mm when no filler wire is used and 3-4 mm withfiller. Gas flow should be generous and a gas lens can be used to advantageto give a non-turbulent flow. Any draughts should be avoided.Nickel alloysAlthough this process is very suitable for welding nickel and itsalloys it is generally considered rather slow, so that it is mostly done onthinner sections of sheet and tube.Shielding gas should be commercially pure argon and addition ofhydrogen up to 10% helps to reduce porosity and increases welding speedsespecially for MONEL alloy and Nickel alloy 200. Helium has the sameadvantages, greatly increasing welding speed. Great care should be takento avoid disturbance of the protective inert gas shield by draughts, and thelargest nozzle diameter possible should be used, with minimum distancebetween nozzle and work. The use of a gas lens increases the efficiency ofthe shield and gives increased gas flow without turbulence. Argon flow isof the order of 17-35 litres per hour for manual operation and higher forautomatic welding. Helium flow should be about 1J3 times this flow rate.The torch is held as near 90 to the work as possible - the more acute theangle the greater the danger of an aspirating effect causing contaminationof the gas shield. Electrodes of pure, thoriated or zirconiated tungstencan be used, ground to a point to give good arc control and shouldproject 3 4.5 mm beyond the nozzle for butt welds and 6-12 mm forfillets.Stray arcing should be avoided as it contaminates the parent plate, andthere should be no weaving or puddling of the pool, the hot filler rod endbeing kept always within the gas shield, and fed into the pool by touching iton the outer rim ahead of the weld. The arc is kept as short as possible- upto 0.5 mm maximum when no filler is used.To avoid crater shrinkage at the end of a weld a crater-filling unit can beused or failing this, extension tabs for run-off are left on the work andremoved on completion. Fig. 3.28 gives suitable joint preparations.For vertical and overhead joints the technique is similar to that for steel,but downhand welding gives the best quality welds.
181
Welding techniquesFiller wires for TIG, PLASMA and MIG dip, spray and pulsedsubmerged arc filler metals and fluxes
Material
Filler wireTIG/plasmaMIG dip, pulsed
Filler wireMIG spray
Filler wire/fluxsubmerged arc
Nickel alloy 61
MONEL alloy 60
MONEL alloy 60MONEL alloy 67
Not recommendedMONEL alloy 67
INCONEL alloy 82
INCONEL alloys601, 82, 625INCONEL alloy 625
INCONEL alloys82, 625INCONEL alloy 625INCONEL alloy 617INCONEL alloys82, 625Not recommended
INCOLOY alloy DSNIMONIC alloy 75
NC 80/20NC 80/20
Not recommendedNC 80/20
BRIGHTRAY alloyseriesNILO alloy series
NC 80/20
Not recommended
Not recommendedINCONEL alloys 82, 625,INCOFLUX 4, 7INCONEL alloy 625,INCOFLUX 7Not recommendedINCONEL alloy 82,INCOFLUX 4Not recommended
Cast ironsSteels containingmolybdenum
Not recommendedINCO alloy 276INCO alloy HX,INCONEL alloy 617INCONEL alloy 625INCONEL alloys82, 625, 617INCOLOY alloy 625
Not recommendedNot recommendedNot recommendedNot recommended
182
Square butt
REINFORCEMENT
f-~~"1__[o.8 1.5 mm
I U -
REMOVABLECOPPER BACKING
V groove
v ^ T T ' ^ V REINFORCEMENT
\J.
1\T
-~*/
[1.0-2.0 mm
y^j^
-| | r -
1 5 mm R00T
FACE
v<"~~Iv~^x/ REINFORCEMENT\f"H/ |i.0-2.Omm\
//
V/^-TH h y -
LII
) NO BACKING USEDUNDER SIDt Oh WtLUCHIPPED AND WELDED
1 5 mm ROOT FACE
RootWidth ofMaterialthickness groove (top) space(mm)(mm)(mm)SWT1.01.21.62.43.2
3.24.04.84.8-6.46.4
0000-0.80-0.8
4.86.48.09.512.716.0
8.913.015.518.023.029.5
3.24.84.84.84.84.8
6.48.09.512.716.0
10.413.016.521.627.0
2.42.43.23.23.2
183
184
up to 0.4%. Gunmetal is a tin bronze containing zinc and often some lead.Welding of these alloys is most often associated with repair work using aphosphor bronze filler wire but to remove the danger of porosity, nonmatching filler wires containing deoxidizers should be used.Filler alloys recommended are:CIO 4.5-6.0% Sn, 0.4% P, remainder Cu.C l l 6.0-7.5% Sn, 0.4% P, remainder Cu.Copper-zinc (brass and nickel silvers), a.c. with argon shield, d.c. withhelium shield. The copper-zinc alloys most frequently welded areAdmiralty brass (70% Cu, 29% Zn, 1% Sn), Naval brass (62% Cu, 36.75%Zn, 1.25% Sn) and aluminium brass (76% Cu, 22% Zn, 2% Al). Porosity,due to the formation of zinc oxide, occurs when matching filler wire is usedso that it is often preferable to use a silicon-bronze wire which reducesevolution of fumes. This may, however, induce cracking in the HAZ. Postweld stress relief in the 250-300 C range reduces the risk of stress corrosioncracking. The range of nickel silver alloys is often brazed.Filler alloys recommended are:C14 70-73% Cu, 1.0-1.5% Sn, 0.02-0.06% As.C15 76-78% Cu, 1.8-2.3% Sn, 0.02-0.06% As.Work-hardening and precipitation-hardening copper-rich alloysThe work-hardening alloys are not often welded becausemechanical properties are lost in the welding operation. Heat-treatablealloys such as copper-chromium and copper-beryllium are welded withmatching filler rods using an a.c. supply to disperse the surface oxides. Theyare usually welded in the solution-treated or in the over-aged condition andthen finally heat-treated.HardfacingThe tungsten arc is a good method for deposition of stellite andother hard surfacing materials on a base metal. The heat is moreconcentrated than that of the oxy-acetylene flame and although there maybe some base metal pick-up this can be kept to a minimum by using correcttechnique and there is not a great deal of dilution. It produces a clean,sound deposit and is very useful for reactive base metals.The electrode is connected to the ve pole (straight polarity) with thelargest diameter filler rod possible to reduce tungsten contamination.Deposition is similar to that when the oxy-acetylene flame is used anddeposition moves from right to left. Filler rods of 3.2, 4.0, 4.8, 6.4 and 8 mmare available and alloys include stellite and nickel-based alloys, and
185
deposition proceeds in the normal way for hard surfacing - do not puddlethe pool as this increases dilution.Easily hardfacedLow and medium carbon steel to 0.4% C. Above 0.4% C, oxy-acetyleneonly.Low-alloy steels.Nickel and nickel-copper alloys.Chrome-nickel stainless steels, niobium stabilized. (Not free machiningnor titanium stabilized).11-14% manganese steels.More difficult to hardfaceCast iron.Stainless steel, straight and titanium stabilized.Tool and die steels, water-hardening, oil-hardening and air-hardeningtypes and hot work grade.Straight chromium stainless steels.
Automatic weldingFor automatic welding the TIG torch is usually water cooled andmay be carried on a tractor moving along a track or mounted on a boom soas to move over the work or for the work to move under the head. The headhas a control panel for spark starter, water and gas and current contactor,and the torch has lateral and vertical movement, the arc length being keptconstant by a motor-driven movement controlled by circuits operatingfrom the arc length. Filler wire is supplied from the reel to the weld pool byTIG process. Recommended filler wires for copper weldingFiller wireType(BS 2870-2875)C106C107C101C102C103
GradePhosphorus deoxidizednon-arsenicalPhosphorus deoxidizedarsenicalElectrolytic tough pitchhigh conductivityFire-refined tough pitchhigh conductivityOxygen-free highconductivity
Argon orheliumshield
C7, C2 1
C8
186
ADJUSTABLEWELDING HEAD
187
TIG welding has now been applied to the robot system with twomanipulators. In this method of welding the workpieces are held in jigs onthe plates of the manipulators, one being welded while the other is beingloaded. The six axes of the robot enable it to handle the filler wire and placeit in the best position without limitation of the wrist movement of the robot.Since the HF necessary for the arc initiation may cause unwanted signalsto the microprocesser all conductors have been screened. The controlcomputer selects and records the particular welding program and togetherwith the robot achieves synchronized movements, and welding operationsare commenced when the operator has loaded one of the two manipulatorsof the system. (See Chapter 5, Welding with robots, for illustration of thissystem.)Various parameter sequences for various operations can be pre-recordedand recalled as required.Spot welding
Mild steel, stainless and alloy steel and the rarer metals such astitanium can be spot welded using a TIG spot welding gun. The pistol gripwater cooled gun carries a collet assembly holding a thoriated tungstenelectrode positioned so that the tip of the electrode is approximately 5 mmFig. 3.30. Orbital TIG pipe welding.
188
within the nozzle orifice, thus determining the arc length. Interchangeablenozzles enable various types of joints to be welded flat, or vertically. Avariable timing control on the power unit allows the current to be timed toflow to ensure fusion of the joint and a switch on the gun controls gas,water, HF unit and current contactor. To make a weld, the nozzle of thegun is pressed on to the work in the required position and when the gunswitch is pressed the following sequence occurs: (1) gas and water flow tothe gun, (2) the starter ignites the arc and the current flows for a periodcontrolled by the timer, (3) current is automatically switched off and postweld argon flows to cool electrode tip and weld.Note. Refer also to BS 3019, General recommendations for inert gas,tungsten arc welding, Part 1: Wrought aluminium, aluminium alloys andmagnesium alloys, Part 2: Austenitic stainless and heat resisting steels.TitaniumTitanium is a silvery coloured metal with atomic weight 47.9,specific gravity 4.5 (cf. Al 2.7 and Fe 7.8) melting point 1800C and UTS 310N/mm 2 in the pure state. It is used as deoxidizer for steel and sometimes instainless steel to prevent weld decay and is being used in increasing amountsin the aircraft and atomic energy industries because of its high strength-toweight ratio.Titanium absorbs nitrogen and oxygen rapidly at temperatures above1000C and most commercial grades contain small amounts of these gases;the difficulty in reducing the amounts present makes titanium expensive.Because of this absorption it can be seen that special precautions have to betaken when welding this metal.Where seams are reasonably straight a TIG torch with tungstenelectrode gives reasonable shrouding effect on the upper side of the weld,and jigs may be employed to concentrate the argon shroud even more overthe weld. In addition the underbead must be protected and this may bedone by welding over a grooved plate, argon being fed into this groove sothat a uniform distribution is obtained on the underside. It can be seentherefore that the success of welding in these conditions depends upon thesuccessful shrouding of the seam to be welded.For more complicated shapes a vacuum chamber may be employed. Thechamber into which the part to be welded is placed is fitted with hand holes,and over these are bolted long-sleeve rubber gloves into which the operatorplaces his hands, and operates the TIG torch and filler rod inside thechamber. An inspection window on the sloping top fitted with welding glassenables a clear view to be obtained. All cable entries are sealed tightly andthe air is extracted from the chamber as completely as possible by pumps,
Plasma-arc welding
189
and the chamber filled with argon, this being carried out again if necessaryto get the level of oxygen and nitrogen down to the lowest permissible level.The welding may be performed with a continuous flow of argon throughthe chamber or in a static argon atmosphere. Since the whole success of theoperation depends upon keeping oxygen and nitrogen levels down to anabsolute minimum great care must be taken to avoid leaks as weldingprogresses and to watch for discoloration of the weld indicating absorptionof the gases.Tantalum
190
foil to 3-4 mm thickness in stainless steel, nickel and nickel alloys, copper,titanium and other rare earth metals (not aluminium or magnesium).Ions and plasmaAn ion is an atom (or group of atoms bound into a molecule)which has gained or lost an electron or electrons. In its normal state anatom exhibits no external charge but when transference of electrons takesplace an atom will exhibit a positive or negative charge depending uponwhether it has lost or gained electrons. The charged atom is called an ionand when a group of atoms is involved in this transference the gas becomesionized.All elements can be ionized by heat to varying degrees (thermalionization) and each varies in the amount of heat required to produce agiven degree of ionization, for example argon is more easily ionized thanhelium. In a mass of ionized gas there will be electrons, positive ions andneutral atoms of gas, the ratio of these depending upon the degree ofionization.A plasma is the gas region in which there is practically no resultantcharge, that is, where positive ions and electrons are equal in number; theregion is an electrical conductor and is affected by electric and magneticfields. The TIG torch produces a plasma effect due to the shield of argon andthe tungsten arc but a plasma jet can be produced by placing a tungstenelectrode centrally within a water-cooled constricted copper nozzle. Thetungsten is connected to the negative pole (cathode) of a d.c. supply and thenozzle to the positive pole (anode). Gas is fed into the nozzle and when anarc is struck between tungsten electrode and nozzle, the gas is ionized in itspassage through the arc and, due to the restricted shape of the nozzleorifice, ionization is greatly increased and the gas issues from the nozzleorifice, as a high-temperature, high-velocity plasma jet, cylindrical in shapeand of very narrow diameter realizing temperatures up to 10000C. Thistype is known as the non-transferred plasma (Fig. 3.31a). With thetransferred arc process used for welding, cutting and surfacing, therestricting orifice is in an inner water-cooled nozzle within which thetungsten electrode is centrally placed. Both work and nozzle are connectedto the anode and the tungsten electrode to the cathode of a d.c. supply (inAmerican terms, d.c.s.p., direct current straight polarity). Relatively lowplasma gas flow (of argon, argon-helium or argon-hydrogen) is necessaryto prevent turbulence and disturbance of the weld pool, so a further supplyof argon is fed to the outer shielding nozzle to protect the weld (Fig. 3.316).In the lead from work to power unit there is a contactor switch as shown.
191
A high-frequency unit fed from a separate source from the mains supplyinitiates the pilot arc and the torch nozzle is positioned exactly over thework. Upon closing the contactor switch in the work-to-power unitconnexion, the arc is transferred from electrode to work via the plasma.Temperatures up to 17000 C can be obtained with this arc. To shape thearc two auxiliary gas passages on each side of the main orifice may beincluded in the nozzle design. Theflowof cooler gas through these squeezesthe circular pattern of the jet into oval form, giving a narrower heataffected zone and increased welding speed. If a copper electrode is usedinstead of tungsten as in the welding of zirconium, it is made the anode. Thelow-current arc plasma with currents in the range 0.1-15 A has a longeroperating length than the TIG arc, with much greater tolerance to changeFig. 3.31. (a) Non-transferred plasma arc. (b) Transferred plasma arc.d.cSUPPLY
TUNGSTEN-ELECTRODE(CA THODE)
HF
GENERATOR
~GAS FLOW
(a)^-COPPER NOZZLE(ANODE)
CONSTRICTINGORIFICE
d.c.SUPPLY
PLASMA JET
HFGENERATOR
PLASMA GASWATER COOLEDNOZZLESHIELDING GAS
OUTER SHIELDINGNOZZLE
WORK
192
in arc length without significant variation in the heat energy input into theweld. This is because it is straight, of narrow diameter, directional andcylindrical, giving a smaller weld pool, deeper penetration and less heatspread whereas the TIG arc is conical so that small changes in arc lengthhave much more effect on the heat output. Fig. 3.32 compares the two arcs.Since the tungsten electrode is well inside the nozzle (about 3 mm) inplasma welding, tungsten contamination by touchdown or by filler rod isavoided, making welding easier.Equipment. In the range 5-200 A a d.c. rectifier power unit with droopingcharacteristic and an OCV of 70 V can be used for argon andargon-hydrogen mixtures. If more than 5% hydrogen is used, 100 V ormore is required for pilot arc ignition. This arc may be left in circuit with themain arc to give added stability at low current values. Existing TIG powersources such as that in Fig. 3.11 may be used satisfactorily, reducing capitalcost, the extra equipment required being in the form of a console placed onor near the power unit. Input is 380-440 V, 50 Hz, a.c. single-phase withapproximately 3.5 A full load current. It houses relays and solenoid valvescontrolling safety interlocks to prevent arc initiation unless gas and waterpressures are correct; flowmeters for plasma and shielding gases, gas purgeand post-weld gas delay and cooling water controls. For low-currentwelding in the range 0.1-15 A, often referred to in Europe as micro-plasmaand in America as needle plasma welding, the power unit is about 3 KVA,200-250 V, 50 Hz single-phase input, fan cooled with OCV of 100 Vnominal and 150 V peak d.c, for the main arc, and output current ranges0.1-2.0 A and 1.0-15 A. The pilot arc takes 6 A at 25 V start and 2.5 A at 24 Vrunning, the main arc being cylindrical and only 0.8 mm wide. Tungstenelectrodes are 1.6, 2.4 and 3.2 mm diameter, depending upon application.Gases. Very pure argon is used for plasma and shield (or orifice) whenwelding reactive metals such as titanium and zirconium which have astrong affinity for hydrogen. For stainless steel and high-strength nickelalloys argon, or argon-hydrogen mixtures are used. Argon-5% hydrogenmixtures are applied for this purpose (cylinders coloured blue with a widered band around the middle) and argon-8% hydrogen and even up to 15%hydrogen are also used. With these mixtures the arc voltage is increasedgiving higher welding speeds (up to 40% higher) and the thin oxide filmpresent even on stainless and alloy steels is removed by hydrogen reductiongiving a clean bright weld, and the wetting action is improved. For copper,nickel and their alloys argon is used in keyhole welding (Fig. 3.33) forthinner sections, for both orifice and shielding gas. Argon and helium is
193
used in the melt-in welding of thinner sections and helium for orifice andshielding gas for sections over 3 mm thick.De-ionized cooling water should be used, and gas flow rates at 2.0 barpressure are about 0.25-3.3 litres per minute plasma and 3.8-7 litres perminute shielding in the 5-100 A range. Cleaning and preparation areFig. 3.32. (a) Plasma arc. (b) TIG arc.
TORCH BODY
ORIFICE GAS
CENTRAL TUNGSTENELECTRODECERAMIC SHIELDNOZZLE ORIFICE
CONSTRICTED ARC
SHIELDING GASPLASMA
STREAM
fa)
CENTRAL TUNGSTENELECTRODE
CERAMIC SHIELD
SHIELDING GASOPEN CONE-SHAPEDARC
194
similar to those for TIG, but when welding very thin sections, oil films oreven fingerprints can vary the degree of melting, so that degreasing shouldbe thorough and the parts not handled in the vicinity of the weld aftercleaning.Technique. Using currents of 25-100 A, square butt joints in stainless steelcan be made in thicknesses of 0.8-3.2 mm with or without filler rod, theangle of torch and rod being similar to that for TIG welding. The variablesare current, gas flow and welding rate. Too high currents may break downthe stabilizing effect of the gas, the arc wanders and rapid nozzle wear mayoccur. In 'double arcing' the arc extends from electrode to nozzle and thento the work. Increasing plasma gas flow improves weld appearance andincreases penetration, and the reverse applies with decreased flow. Aturbulent pool gives poor weld appearance.In 'keyhole' welding of thicknesses of 2.5-6.5 mm a hole is formed in thesquare-edge butt joint at the front edge of the molten pool, with the arcpassing through the section (Fig. 3.33). As the weld proceeds, surfacetension causes the molten metal to flow up behind the hole to form thewelding bead, indicating complete penetration, and gas backing for theunderbead is required. When butt welding very thin sections, the edges ofthe joint must be in continuous contact so that each edge melts and fusesinto the weld bead. Separation of the edges gives separate melting and noweld. Holding clamps spaced close together near the weld joint and abacking bar should be used to give good alignment, and gas backing isrecommended to ensure a fluid pool and good wetting action. Flanging isrecommended for all butt joints below 0.25 mm thickness and allows forgreater tolerance in alignment. In the higher current ranges joints up to6 mm thick can be welded in one run. Lap and fillet welds made with fillerrod are similar in appearance and employ a similar technique to those madewith the manual TIG process. Edge welds are the best type of joint for foilthickness, an example being a plug welded into a thin-walled tube.In tube welding any inert gas can be used within the tube for underbeadprotection.Faults in welding very thin sections are: excessive gaps which the metalcannot bridge; poor clamping allowing the joint to warp; oil films varyingthe degree of melting; oxidation or base metal oxides preventing goodFig. 3.33. Surface tension causes molten metal to flow and close keyhole.^KEYHOLE
195
wetting'; and nicking at the ends of a butt joint. This latter can be avoidedby using run-off plates or by using filler rod for the start and finish of theweld.Plasma spray hard facingIn this method the arc plasma melts the hard facing powderparticles and the high-velocity gas stream carries the molten particles on tothe surface (Fig. 3.34). Although there may be some voids caused, 90-95%densities can be obtained and the method is particularly suitable forapplying refractory coatings because this method has a better bond withthe parent plate than the spray and fuse method. Because the heat islocalized, surfaces can be applied to finished parts with no distortion andthe finish is very smooth. The cobalt, nickel- and tungsten-based powdersare all supplied for this process and suitable applications are gas turbineparts, such as sealing rings of gas turbines, mixer and feed parts, sleeves,sheets and wear pads and slides, etc.Plasma transferred arc hardfacingThis powder deposition process is fully automated and uses a solidstate SCR, the power output being 300 A, 32 V, at 100% duty cycle. Thepilot arc is initiated by HF and the unit has pulse facilities. The powder issupplied from a powder feeder operating on the rotating drum principle.Powder feed rate is controlled by varying the feed opening over the knurledrotating wheel upon which a regulated ribbon of powder is applied, andthe powder feed can be regulated to provide an upslope and downslope feedrate. This powder is carried from the container to the work in a stream ofargon and is melted in the plasma, the argon providing a shield around theplasma heat zone (Fig. 3.35). Torches are of varying size and cover mostFig. 3.34. Plasma surfacing.-TUNGSTEN
ELECTRODE
NOZZLE- POWDERPLASMA GAS
WORK-*
196
PLASMA GASCOPPER NOZZLEARGON SHIELDING GASPOWDER CARRIED BYARGON GASWORK
Spot weldingIn this method of welding use is made of the heating effect whichoccurs when a current flows through a resistance. Suppose two steel platesA and B (Fig. 4.1) are to be welded together at X. Two copper electrodesare pressed against the plates squeezing them together. The electricalresistance is greatest at the interface where the plates are in contact, andif a large current at low voltage is passed between the electrodes throughthe plates, heat is evolved at the interface, the heat evolved being equal toP Rt joules, where /is the current in amperes, R the resistance in ohms and/ the time in seconds. A transformer supplies a.c. at low voltage and highcurrent to the electrodes (Figs. 4.1 and 4.2).Fig. 4.1
Fig. 4.2HIGH CURRENTLOW VOLTAGE
- MOVINGCOPPER
7ELECTR0DES
>SEC
TRANSFORMER
197
198
For any given joint between two sheets a suitable time is selected and thecurrent varied until a sound weld is obtained. If welds are made near eachother some of the current is shunted through the adjacent weld (Fig. 4.3) sothat a single weld is not representative of what may occur when severalwelds are made. Once current and time are set, other welds will be ofconsistent quality. If the apparatus is controlled by a pedal as in thesimplest form of welder, then pressure is applied mechanically and the timefor which the current flows is switch controlled, as for example in certaintypes of welding guns used for car body repairs. This method has the greatdisadvantage that the time cannot be accurately controlled, so that if it istoo short there is insufficient heat and there is no fusion between the plates,whilst if the time is too long there is too much heat generated and thesection of the plates between the electrodes melts, the molten metal isspattered out due to the pressure of the electrodes and the result is a hole inthe plates. In modern spot-welding machines the pressure can be appliedpneumatically or hydraulically or a combination of both and can beaccurately controlled. The current is selected by a tapping switch on theprimary winding of the transformer and the time is controlled electronically, the making and breaking of the circuit being performed by thyristors.When the current flows across the interface between the plates, theheating effect causes melting and fusion occurs at A (Fig. 4.4). Around thisthere is a narrow heat-affected zone (HAZ) since there is a quenching effect
Fig. 4.3
SHUNT EFFECT OFNEARBY WELDS
Fig. 4.4z FUSION ZONE A
Spot welding
199
due to the electrodes, which are often water cooled. There are equi-axedcrystals in the centre of the nugget and small columnar crystals growinwards towards the centre of greatest heat.Types of spot weldersIn the pedestal type there is a fixed vertical pedestal frame andintegral transformer and control cabinet. The bottom arm is fixed to theframe and is stationary during welding and takes the weight of theworkpiece. The top arm may be hinged so as to move down in the arc of acircle (Fig. 4.5a) or it may be moved down in a straight line (Fig. A.5b).Pivoting arms are adjustable so as to have a large gap between theelectrodes, the arms are easily adjusted in the hubs and various length armsare easily fitted giving easy access to difficult joints. The vertical travelmachine has arms of great rigidity so that high pressures can be applied,and the electrode tips remain in line irrespective of the length of stroke, sothat the machine is easily adapted for projection welding. Additionally thespot can be accurately positioned on the work, and since the moving partshave low inertia, high welding speeds can be achieved without hammering(see Fig. 4.6<z and b).Welding gunsPortable welding guns are extensively used in mass production.The equipment consists of the welding station often with hydro-pneumaticbooster to apply the pressures, a water manifold, one or two welding guns
fa) PIVOTTING
ARMS
with balancers, cable between transformer and guns and a control station.In modern machines the composite station with built-in cabinet comprisessequence controls with integrated circuits, thyristor contactors anddisconnect switch. Articulated guns (Figs. 4.1a and b) have both armsarticulated as in a pair of scissors, giving a wide aperture betweenelectrodes, and are used for welding joints difficult of access. Small
Fig. 4.6. (a) Air-operated spot welding machine with pivoting arms.
201
articulated guns are used for example in car body manufacture for weldingsmall flanges, and in corners and recesses. C guns (Fig. 4.7c) have thepiston-type ram of the pressure cylinder connected to the moving electrode,which thus moves in a straight line. There is great rigidity and a highworking speed because of the low inertia of the moving parts. Theelectrodes are always parallel and the precision motion is independent of
Fig. 4.6. (b) Air-operated spot welding machine with vertical action.
202
Aift CYLINDER
HYDRAULIC OPERATINGCYLINDER
WZLQING CYLINDER
203
the arm length with easily determined point of welding contact. They areused for quality welds where the height does not preclude them. Integraltransformer guns are used to reduce handling costs of bulky fabrications,and the manual air-cooled gun and twin spot gun are used in repair work oncar bodies and agricultural equipment and for general maintenance, thelatter being used where there is access for only one arm as in closed boxsections and car side panels.The welding cycleThe cycle of operations of most modern machines is completelyautomatic. Once the hand or foot switch is pressed, the cycle proceeds tocompletion, the latest form having digital sequence controls with printedcircuits, semi-conductors, digital counting and air valve operation byrelays. The simplest cycle has one function, namely weld time, the electrodeforce or pressure being pre-set, and it can be best illustrated by two graphs,one the electrode pressure plotted against time and the other the currentplotted against the same time axis (Fig. 4.8). The time axis is divided into100 parts corresponding to the 50 Hz frequency of the power supply.Fig. 4.8 shows a simple four-event control. First the squeeze is applied andheld constant (a-b on the graph). The current is switched on at X, held forseven complete cycles (7/50 s) and switched off at Y. The pressure is helduntil c on the graph, the weld cooling in this period. Finally the squeeze isreleased and the repeat cycle of operations begins again at av The switchescomprise repeat-non-repeat, thyristors on-off and heat control in-out.For more complex welding cycles, necessary when welding certain metalsto give them correct thermal treatment, the graphs are more complex withup to ten functions with variable pressure cycle, and these machines areoften operated from three phases. Machines for the aeronautical and spaceindustries are specially designed and incorporate variable pressure headsFig. 4.8. Standard four-event sequence for spot welding.
204
and up to ten functions. Most aluminium alloys lose the properties given tothem by work hardening or heat treatment when they are heated. To enablethe correct thermal treatment of heating and cooling to be given to themduring the welding cycle three-phase machines are often employed.The transformer
The transformer steps the voltage down from that of the mains tothe few volts necessary to send the heavy current through the secondarywelding circuit. When the current is flowing the voltage drop across thesecondary may be as low as 3-4 volts and in larger machines the current canbe up to 35 000 A. Because of these large currents there is considerable forceacting between the conductors due to the magnetic field, so transformersmust be robustly constructed or movement may cause breakdown of theinsulation, and in addition they may be water cooled because of the heatingeffect of the current. The secondary winding consists of one or two turns ofcopper strip or plates over which the primary coils fit, the whole beingmounted on the laminated iron core. Because any infiltration of moisturemay lead to breakdown, modern transformers have the primary windingand secondary plates assembled as a unit which is then vacuum encapsulated in a block of epoxy resin. The primary winding has tappingswhich are taken to a rotary switch which selects the current to be used.The current flowing in the secondary circuit of the transformer providesthe heating effect and depends upon (1) the open circuit voltage and (2) theimpedance of the circuit, which depends upon the gap, throat depth andmagnetic mass introduced during welding and the resistance of the metal tobe welded. The duty cycle is important, as with all welding machines, as itaffects the temperature rise of the transformer. For example, if a spotwelder is making 48 spot welds per minute, each of 0.25 seconds duration,the duty cycle is (48 x 0.25 x 100) -r- 60 - 20%. Evidently knowing theduty cycle and welding time, the number of welds that can be made perminute can be calculated.
ElectrodesThe electrode arms and tips (Fig. A.9a) which must carry the heavycurrents involved and apply the necessary pressure must have the followingproperties: (1) high electrical conductivity so as to keep the PR loss (theheating due to the resistance) to a minimum, (2) high thermal conductivityto dissipate any heat generated, (3) high resistance to deformation underlarge squeeze pressures, (4) must keep their physical properties at elevatedtemperatures, (5) must not pick up metal from the surface of the workpiece,
Properties
Uses
Note. The addition of various elements increases the hardness but reduces the conductivity.
206
(6) must be of reasonable cost. The following types of electrodes are chieflyused, and are given in the table. Electrolytic copper (99.95% Cu) has highelectrical and thermal conductivity and, when work hardened, resistsdeformation but at elevated temperatures that part of the electrode tip incontact with the work becomes annealed due to the heating and the tipsoftens and deforms. Because of this it is usual to water-cool the electrodesto prevent excessive temperature rise.*Water coolingAdequate electrode cooling is the most essential factor to ensureoptimum tip life; the object is to prevent the electrode material fromreaching its softening temperature, at which point it will lose its hardnessFig. 4.9. (a) Electrodes and holders.I
CRANKED OFFSETELECTRODE
CENTRE
OFFSET
FLAT
DOME
TIPTRODES (SCIAKY)
TAPER SHANKHOLDER
See also BS 807 and BS 4215. Spot welding electrodes and electrode holders.
Electrodes
207
208
cycles. The chief causes of wear are: electrical; wrong electrode material,poor surface being welded, contacts not in line; mechanical; electrodehammering, high squeeze, weld and forge pressures, abrasion in loadingand unloading and tearing due to the parting of the electrodes.
Seam weldingIn a seam welding machine the electrodes of a spot welder arereplaced by copper alloy rollers or wheels which press on the work to bewelded (Fig. 4. \0a and b). Either one or both are driven and thus the workpasses between them. Current is taken to the wheels through the rotarybearings by silver contacts with radial pressure and the drive may be byknurled wheel or the more usual shaft drive which enables various types ofwheel to be easily fitted. If the current is passed continuously a continuousseam weld results but, as there is a shunt effect causing the current to flowthrough that part of the weld already completed, overheating may occurresulting in burning of the sheets. To avoid this the current can be pulsed,allowing sufficient displacement of the already welded portion to take placeand thus obviating most of the shunt effect. For materials less than 0.8 mmthick or at high welding speeds (6 m/min) no pulsing is required, the 50 Hzfrequency of the supply providing a natural pulse. Above 2 x 0.8 mmthickness pulsation is advisable, and essential above 2 x 1.5 mm thickness,while for pressure-tight seams the welds can be arranged to overlap and ifthe seams are given a small overlap with wide-faced wheels and highpressure a mash weld can be obtained.By the use of more complex electro-mechanical bearing assemblies,longitudinal and circumferential welds can be made (Fig. 4.10c).Seam welding guns are extremely useful for fabricating all types of tanks,exhaust systems, barrels, drip-mouldings on car body shells, etc. They haveelectrode drive which automatically propels the gun along the seam so that
iV
a.c. o /SUPPLY3MAINS ^S
\oSEC.
1SEAM
* \ ^ DRIVEN^C WHEELS
Seam welding
209
Fig. 4.10. (b) 'Thin wheel' seam welding machine with silver bearings.
JfffflBISMACOVMCT5
FOOTSWITCH-^^
CIRCUMFERENTIALSEAM
210
it only requires guidance, and they are operated in the same way as spotwelding guns.Direct current spot weldingWe have seen that when iron or steel to be welded is placed in aspot or seam welder the impedance of the secondary circuit is increased andthe secondary current varies according to the mass introduced. By usingd.c. this loss is obviated, the power consumed is reduced and the electrodelife increased because skin effect is eliminated. This enables coated steels,stainless and other special steels in addition to aluminium alloys to bewelded to high standards. The machine is similar in appearance to the a.c.machine but has silicon diodes as the rectifying elements.Three-phase machinesThree-phase machines have been developed to give impulse ofcurrent in the secondary circuit at low frequency, with modulated waveform to give correct thermal treatment to the material being welded. Thesemachines have greatly increased the field of application of spot welding intolight alloys, stainless, and heat-resistant steels, etc. A typical sequence ofoperations is: squeeze, which multiplies the number of high spots betweenthe contact faces; welding pressure, which diminishes just before thewelding current flows; immediately after the passage of the current, forgingor recompression pressure is applied which is above the elastic limit of thematerial and completes the weld. Setting of the welding current can be doneby welding test pieces with increasing current until the diameter of thenugget, found by 'peeling' the joint, is (2t + 3), where t is the thickness ofthe thinner sheet. This current is noted. It is then increased until spatter ofthe nugget occurs and the welding current is taken as midway between thesetwo values, with final adjustments made on test pieces.Nickel and nickel alloys have higher electrical resistivity and lowerthermal conductivity than steel and are usually welded in thin sections aslap joints, although the crevice between the sheets may act as a stress raiserand affect the corrosion and fatigue resistance. High pressures are requiredfor the high-nickel alloys so as to forge the solidifying nugget, and themachine should have low inertia of the moving parts so that the electrodehas rapid follow-up during welding. Current may be set as in the previoussection, and in some cases it is advantageous to use an initial squeezefollowed by an increasing (up-sloping) current. When the nugget is justbeginning to form with diffusion of the interface, the squeeze force isreduced to about one-third of its initial value and held until the current isswitched off; this reduces danger of expulsion of molten metal and givesbetter penetration of the weld into the two sheets.
Projection welding
211
Projection weldingProtrusions are pressed on one of the sheets or strips to be weldedand determine the exact location of the weld (Fig. 4.11). Upon passage ofthe current the projection collapses under the electrode pressure and thesheets are welded together. The machines are basically presses, the tippedelectrodes of the spot welder being replaced by flat platens with T slots forthe attachment of special tools, and special platens are available whichallow the machine to be used as a spot welder by fitting arms and electrodes(Fig. 4.12), and automatic indexing tables can be used to give increasedoutput. Projection welding is carried out for a variety of components suchas steel radiator coupling elements, brake shoes, tin-plate tank handles andspouts, etc. The press type of machine is also used for resistance brazing inwhich the joining of the parts is achieved with the use of an alloy with alower melting point than the parent metal being welded so that there is nomelting involved.Cross wire welding is a form of projection welding, the point of contactof the two wires being the point of location of the current flow. Low-carbonmild steel, brass, 18/8 stainless steel, copper-coated mild steel andgalvanized steel wire can be welded but usually the bulk of the work is donewith clean mild steel wire, bright galvanized, or copper coated as used formilk bottle containers, cages, cooker and refrigerator grids, etc., andgenerally several joints are welded simultaneously.Modern machines are essentially spot welders in ratings of 25, 70, or 150kVA fitted with platens upon which suitable fixtures are mounted andhaving a fully controlled pneumatically operated vertical head, and theelectrical capacity to weld as many joints as possible simultaneously. Largeprogrammed machines are manufactured for producing reinforcementmesh automatically.Fig. 4. U. Projection welding.MOVINGSHEETS BEINGWELDED
PRIMARY' (INPUT)
FIXED
SHAPE OF PROJECTION
212
vvvv
213
between the ends brings them to welding heat. Extra pressure is nowapplied and the ends are pushed into each other, the white hot metalwelding together and an enlargement of section taking place. The sectionmay be machined to size after the operation if necessary.
ruuuvmTRANSFORMER
WELD
nmnmmnnTRANSFORMER
214
CLAMPS ARCWELD
1QTRANSFORMER
Fig. 4.15. Machine for welding rail sections. 1000 kVA. 3-phase, 440 V. Welding sequence: (1) Both rails securelyclamped in welder. (2) Rails aligned vertically and horizontally under full clamping pressure. (3) Weld initiated bypush button control. (4) Moving head moves forward on the burn-off or pre-flashing stroke used to square up theends of the rails if necessary. On completion of this, pre-heating begins until the requisite number of pre-heats havelapsed. At this point the rails should be in a suitably plastic state to allow for straight flashing and finally forging.
5Additional processes of welding
216
217
turns into a slag in its lower layers under the heat of the arc and protects theweld from contamination. The wire electrode is fed continuously to the arcby a feed unit of motor-driven rollers which is voltage-controlled in thesame way as the wire feed in other automatic processes and ensures an arcof constant length. Thefluxis fed from a hopperfixedto the welding head,and a tube from the hopper spreads thefluxin a continuous mound in frontof the arc along the line of weld and of sufficient depth to completelysubmerge the arc, so that there is no spatter, the weld is shielded from theatmosphere and there are no radiation effects (UV and IR) in the vicinity.(Fig. 5.1a and b.) A latest development to increase deposition rate is to laydown a powder in front of flux feed and welding head; this is generallyused with a tandem a.c./d.c. head.Welding heads
Fully automated welding heads for this process can also be usedwith modification for gas shielded metal arc welding including CO2, solidandfluxcored, thus greatly increasing the usefulness of the equipment. Thehead can be stationary and the work moved below it, as for example in thewelding of circumferential and longitudinal seams, or the head may be usedwith positioners or booms or incorporated into custom-built massproduction welding units for fabricating such components as brake shoes,axle housings, refrigerator compressor housings, brake vacuum cylinders,etc., and hard surfacing can also be carried out. The unit can also be tractormounted (cf. Fig. 5.2c) and is self-propelled, with a range of speeds of100 mm to 2.25 m per minute, and arranged to run on guide bars or rails.Oscillating heads can be used for root runs on butt joints to maintain aFig. 5.1.WIRE FEED NOZZLEOR CONTACT TUBE.
WIRE ELECTRODE CONTINUOUSL Y FED
SURPLUS GRANULARFLUX COLLECTEDBY RECOVERY UNIT
GRANULARFLUX SOLIDIFIED INTOSLAG IN HEAT OF ARCDEPOSITEDWELD METAL
\\
DIRECTIONOF WELDINGFLUX FEEDTUBE
218
constant welding bead on the underside of the joint, and two and even threeheads can be mounted together or the heads can be arranged side by side togive a wide deposit as in hard surfacing. Fillet welding can be performed byinclining two heads, one on each side of the joint, with flux feeds andrecovery, the heads being mounted on a carriage which travels along agantry over the work (Fig. 5.2). Two heads mounted in tandem andtravelling either along a guide rail or directly on the workpiece are used forbutt joints on thick plate, and both can operate on d.c. or the leading headcan operate on d.c. and the trailing head on a.c.Three electrode heads can be gantry mounted on a carriage, the leadingelectrode being d.c. operated with the trailing electrodes a.c. This methodgives high deposition rates with deep penetration. Special guide unitsensure in all cases that the electrode is correctly positioned relative to thejoint.The main components in the control box are: welding voltage and arcFig. 5.1. (b)WIRE REEL
CONTROLBOX
WIRESTRAIGHTENER
WIRE FEEDDRIVE MOTOR
WIRE FEEDGEARBOX
NOZZLEASSEMBLY
FLUX HOPPER
FLUX VALVE
219
220
which fit the wire diameter being used, and the contact tube is used for theshielding gas when gas shielded welding is being performed and is watercooled. The coil arm holder has a brake hub with adjustable braking effectand carries 300 mm i.d. coils, and a flux hopper is connected to a flux funnelattached to the contact tube by a flexible hose.A guide lamp which is attached to the contact tube provides a spot oflight which indicates the position of the wire, thus enabling accuratepositioning of the head along the joint, and a flux recovery unit collectsunfused flux and returns it to the hopper.A typical sequence of operations for a boom-mounted carriage carryingmultiple welding head is: power on, carriage positioned, welding heads 1, 2,etc., down, electrode feed on, wire tips set, flux valve open, welding speedset, welding current set, welding voltage set, flux recovery on; press switchto commence welding.Power unitThe power unit can be a motor- or engine-driven d.c. generator ortransformer-rectifier with outputs in the 30-55 V range and with currentsfrom 200 to 1600 A with the wire generally positive. In the case of multiplehead units in which the leading electrode is d.c. and the trailing electrode isa.c. a transformer is also required. In general any power source designed forautomatic welding is usually suitable when feeding a single head.Wires are available in diameters of 1.6, 2.0, 2.4, 3.2, 4.0, 5.0, 6.0 mm onplastic reels or steel formers. Wrappings should be kept on the wire untilready for use and the reel should not be exposed to damp or dirtyconditions.A variety of wires are available including the following (they are usuallycopper coated). For mild steel types with varying manganese content, e.g.0.5%, 1.0%, 1.5%, 2.0% manganese, a typical analysis being 0.1% C, 1.0%Mn, 0.25% Si, with S and P below 0.03%. For low alloy steels, 1,25% Cr,0.5% Mo; 2.25% Cr, 1.0% Mo; 0.2% Mn, 0.5% Mo; and 1.5% Mn 0.5% Moare examples, whilst for the stainless steel range there are: 20% Cr, 10% Nifor unstabilized steels; 20% Cr, 10% Ni, 0.03% C, for low-carbon 18/8steels; 19% Cr, 12% Ni, 3% Mo for similar steels; 20% Cr, 10% Ni, nobiumstabilized; 24% Cr, 13% Ni for steels of similar composition and forwelding mild and low-alloy steels to stainless steel.Many factors affect the quality of the deposited weld metal: electrodewire, slag basicity, welding variables (process), cleanliness, cooling rate,etc. For hardfacing, the alloy additions necessary to give the hard surfaceusually come from the welding wire and a neutral flux, and tubular wirewith internal flux core is also used in conjunction with the external flux.
221
Hardness values as welded, using three layers on a mild steel base, arebetween 230 and 650 HV depending upon the wire and flux chosen.Flux (see also Vol. 1, pp. 61-3)Fluxes are suitable for use with d.c. or a.c. They are gradedaccording to their form, whether (1) fused or (2) agglomerated. Fusedfluxes have solid glassy particles, low tendency to form dust, good recyclingproperties, good slag-flux compatibility, low combined water and littlesensitivity to humid conditions. Agglomerated fluxes have irregular-sizedgrains with low bulk density, low weight consumption at high energy inputswith active deoxidizers and added alloying elements where required.Fluxes are further classified as to whether they are acidic or basic, thebasicity being the ratio of basic oxides to acidic oxides which they contain.In general the higher the basicity the greater the absorption of moisture andthe more difficult it is to remove.*The general types of flux include manganese silicate, calcium manganesealuminium sulphate, rutile, zirconia and bauxite, and the choice of fluxaffects the mechanical properties of the weld metal. Manufacturers supplyfull details of the chemical composition and mechanical properties of thedeposited metal when using wires of varying compositions with variousselected fluxes (i.e. UTS, % elongation Charpy impact value, and CTODtfigures at various temperatures).Fluxes that have absorbed moisture should be dried in accordance withthe makers' instructions, as the presence of moisture will affect themechanical properties of the deposited metal. The flux, whether fused oragglomerated, should be chosen to give the weld as near as possible thesame characteristics as the parent plate. Wire composition and chosenflux must be compatible. Tensile and yield strength, together with impactvalues of the welded joint must all be considered.The strength of carbon-manganese steels depends upon the carbon,silicon and manganese content. Of these, the manganese content can mosteasily be varied by additions to the flux to obtain the various levels ofstrength. In general, the manganese content of the weld metal should beequal to or exceed that of the parent plate. Too much manganese willresult in brittleness. The impact value is governed by the basicity of theflux; an increase of basicity results in a decrease of arc stability, areduction in weld appearance and more difficult slag removal. In generalCaO + CaF 2 + MgO + K 2 O + Na 2 O + KMnO + FeO). The basicity may varySiO21,+ pp.KA12s+T i 2 + Zr2)from 0.7 to 3.1 (see also Vol.61-4.t Crack tip opening displacement Vol. 1, pp. 284-9.* Basicity (BI) =
222
the flux of highest basicity consistent with stable arc, good weldappearance and easy slag removal should be chosen.Electrode wires, wound on reels, are available, together with compatiblefluxes for carbon-manganese steels, low-alloy steels and stainless steels.For duplex stainless steels use a flux such as OK 16.93 or 18.86, and forsuper duplex use flux OK 16.88. See table, p. 181, for filler wire and fluxes.Joint preparationJoint edges should be carefully prepared and free from scale, paint,rust and oil, etc., and butt seams should fit tightly together. If the fit-up hasgaps greater than 0.8 mm these should be sealed with a fast manual weld.When welding curved circumferential seams there is a tendency for themolten metal and slag, which is very fluid, to run off the seam. This can beavoided or reduced by having the welding point 15-65 mm before top deadcentre in the opposite direction to the rotation of the work and in somecases the speed of welding and current can be reduced. Preparation of jointsis dependent upon the service to which the joint is to be put and thefollowing preparations are given as examples only (Fig. 5.3).BackingAs the cost of back-chipping and making a sealing run hasescalated it becomes more and more necessary to be able to weld plates andcylinders of large size with a run on one side only. This may be the case, forexample, if the fit-up of the sections is poor and a weld in the root of thesection may not be able to bridge a wide root gap successfully. In these casesa backing can be used so that the weld is performed from one side only andwith which a good profile of underbead is obtained even when fit-up andalignment are not good. The following are examples of differing types ofbacking strips available.Ceramic tile backing strip. This is shown in section in Fig. 5Aa and issuitable for slag-forming processes such as submerged arc, or flux coredand MMA can be used for vertical and horizontal-vertical butts. A recessin the tile allows the slag to form below the underbead and is stripped offand discarded with the aluminium foil which holds it in position as the weldprogresses.Fibreglass tape backing strip is a closely woven flexible material of aboutfour to six layers and fibreglass tape which gives good support to theunderbead or root run of the weld and is usually used in conjunction with acopper or aluminium backing bar. It is non-hygroscopic and has low fumelevel. Sizes are from 30 mm wide heavy single layer, 35 mm wide four layerand 65 mm wide six layer.
223
Fibreglass tape, sintered sand backing plate. This is typical for submergedarc single or twin wire as in large structures, e.g. deck plates in shipyards,etc. The backing is of sintered sand (silica) about 600 mm long, 50 mm wideand 10 mm thick reinforced with steel wires. It has a fibreglass tape fitted tothe upper surface to support the root of the weld and has adhesive outeredges to allow for attachment to the joint, which should be dry and whichshould have a 40-50 included angle preparation and a root gap of about4 mm. The backing is slightly flexible to allow for errors of alignment andhas 45 bevelled ends. Overlapping tape prevents burn-through at the
3 E
_j
//s
^-60^-^
0-15-*///
LAP JO/NTS
CORNER JOINTWITH BACKING
- MANUALPLATE 2 0 m m THICK
MANUALPLATE 2 5 m m THICK
BACKING
224
1ALUMINIUMFOIL(ADHESIVE)
JUNCTION OF BACKINGALUMINIUM SECT/ON1TO SUPPORT BACKING
Electroslag welding
225
MOLTEN METAL
SOLIDIFIED^WELD MLTAL
226
thicknesses less than 20 mm the joints can be reduced to 18-24 mm, the gapensuring that the guide tube does not touch the plate edges. Water-cooledcopper shoes act as dams and position the molten metal and also give it therequired weld profile. As with electroslag welding the current passingthrough the molten slag generates enough heat to melt the electrode end,guide and edges of the joint, ensuring a good fusion weld. If a plainuncoated guide tube is used, flux is added to cover the electrode and guideend before welding commences. To start the process the arc is struck on thework. It continues burning under the slag with no visible arc or spatter. Theslag should be viewed through dark glasses as in gas cutting because of itsbrightness when molten.An a.c. or d.c. power source in the range 300-750 A is suitable, such as isused for automatic and MMA processes. Striking voltage is of the order of70-80 V, with arc voltages of 30-50 V, higher with a.c. than d.c.The advantages claimed for the process are: relatively simpler, cheaper,and more adaptable than other similar types, faster welding than MMA ofthick plate, cheaper joint preparation, even heat input into the joint thusreducing distortion problems, no spatter losses, freedom from weld metaldefects and low consumption of flux. Fig. 5.6 illustrates the layout of themachine.
227
human hand, wrist and forearm and the following gives the approximatemovement values:rotational 340, radial arm 550 mm max., vertical arm 850 mmmax., wrist bending 90, wrist turning 180.The accuracy of these movements is 0.1-0.2 mm at 500 mm distance andit should be noticed that the robot can be equipped with heads for selection,grinding, polishing and spot welding, if required.Evidently there must be large production runs of components withrepetitive welding to be performed for the cost of the station, consisting ofpositioners, control cabinets, robot with gas shielded metal arc welding,Fig. 5.6. (a) Consumable guide layout showing water-cooled dams.
CONSUMABLEGUIDE
PARENT PLA TE
WATER COOLEDCOPPER SHOESLAG BATH
WATER
228
Fig. 5.6. (c) The consumable guide welding process using, in this case, twinwire/tube system. The dams have been removed to show the position of theguide tubes.
Fig. 5.7
Key:1.2.3.4.5.
Control panel, by which operator determines when robot should start welding thenext work piece.Handling unit. Different types are available. On this one fixtures for the componentare mounted on tilting turntables.Handling unit on same foundation as robot giving stability and accuracy.Screen.Welding robot with rapid, accurate movements.
6a. Constant voltage power source for welding head. Wire feed unit can be positionedseparately.6b. Wire reel.6c. Programming unit.6d. Wire feed.7. Control cabinet, controlling movements and where removable programming unit ilocated. Program is stored on tape cassette.
230
head and power and control unit, to be justified. Once the decision has beentaken for the outlay to be justified the advantages that accrue are great.The production station, which varies according to the size of the workpieces, can consist, for example, of two positioners, on which the work is jigheld. These positioners (Fig. 5.8) and the data required in the weldingoperations are controlled by a microcomputer and are servo-steered.The robot head has a gas shielded metal arc welding gun adapted to fitthe head, the power source is of the thyristor-controlled constant voltagetype and the wire is fed from a unit which controls speed of feed andcompensates for variations of mains voltage and friction of the feed rollers.To program the robot, the programming unit is taken from the controlcabinet and the robot run through the complete welding sequence for thepart to be fabricated. The welding gun is moved from point to point andeach section is fed with the speed required and the welding parameters(current and voltage, etc.), and the accelerated movement from one weldingpoint to the next is also programmed and mistakes are easily corrected. Thecomputer memory has say 500 position capacity with additional instructions with a tape recorder increasing the memory. The storage of theprogram is on a digital tape cassette so that the switch from one program toanother can be made without starting from scratch. As is usual pre- andpost-flow of the shielding gases and crater filling are all part of the program.(Note. The TIG method of welding may also be performed by robots. SeeChapter 3.)Fig. 5.8. Computer control, servo-powered positioner. Dual axes, fast andaccurate handling, Self-braking worm gears.
231
Pressure welding
Pressure weldingThis is the joining together of metals in the plastic condition (notfusion) by the application of heat and pressure as typified by theblacksmith's weld. In general the process is confined to butt welding. Theparts (tubes are a typical example) are placed on a jig which can applypressure to force the parts together.The faces to be welded are heated by oxy-acetylene flames, and when thetemperature is high enough for easy plastic flow to take place, heatingceases and the tubes are pushed together causing an upset at the weldedface. The welding temperature is about 1200C for steel. It is consideredthat atoms diffuse across the interfaces and recrystallization takes place,the grains growing from one side to the other of the welded faces since theyare in close contact due to the applied pressure. Any oxide is completelybroken up at a temperature well below that of fusion welding but due to theheating time concerned, grain growth is often considerable. Steel, somealloy steels, copper, brass, and silver can be welded by this process.Cold pressure welding
INDEX RELEASEHANDLE GIVINGCORRECT DIEOPENING
232
233
is applied to the points to be welded at temperatures below the recrystallization temperature of the metals involved. This applied pressure brings theatoms on the interface to be welded into such close contact that they diffuseacross the interface and a cold pressure weld is made.It is a method for relatively ductile metals such as aluminium, coppercupro-nickel, gold, silver, platinum, lead, tin and lead-tin alloys, etc., and itis particularly suited to welds in circular wire section. In the type describedof the multiple upset type, the surfaces to be welded are placed in contactand held in position by gripping dies and are fed together in smallincrements by a lever (Fig. 5.9). Each lever movement giving interfacepressure displaces the original surfaces by plastic flow and after about fourto six upsets, the last movement completes the weld and the flash is easilyremoved. In the machine illustrated, copper wire 1.1-3.5 mm diametermax. or aluminium wire to 4.75 max. can be butt welded. Fig. 5.10a and billustrates the micrographs of welds made in copper to copper and copperto aluminium wire.Ultrasonic weldingUltrasonic vibrations of several megacycles per second (the limitof audibility is 20000-30000 Hz) are applied to the region of the faces tobe welded. These vibrations help to break up the grease and oxide film andheat the interface region. Deformation then occurs with the result thatwelding is possible with very greatly reduced pressure compared with anordinary pressure weld. Very thin section and dissimilar metals can bewelded and because of the reduced pressure there is reduced deformation(Fig. 5.11).Fig. 5.11. Ultrasonic welding.TOP ANVILVIBRATEDULTRASONICALLY
SPECIMENSI ylOBE WELDED
, BOTTOM1 ANVIL
234
Friction weldingThe principle of operation of this process is the changing ofmechanical energy into heat energy. One component is gripped and rotatedabout its axis while the other component to be welded to it is gripped anddoes not rotate but can be moved axially to make contact with the rotatingcomponent. When contact is made between rotating and non-rotatingparts heat is developed at the contact faces due to friction and the appliedpressure ensures that the temperature rises to that required for welding.Rotation is then stopped and forging pressure applied, causing moreextrusion at the joint area, forcing out surface oxides and impurities in theform of a flash (Fig. 5.12). The heat is concentrated and localized at theinterface, grain structure is refined by hot work and there is little diffusionacross the interface so that welding of dissimilar metals is possible.In general at least one component must be circular in shape, the idealsituation being equal diameter tubes, and equal heating must take placeover the whole contact area. If there is an angular relationship between thefinal parts the process is not yet suitable.The parameters involved are: (1) the power required, (2) the peripheralspeed of the rotating component, (3) the pressure applied and (4) the timeof duration of the operation. By adjusting (1), (2) and (3), the time can bereduced to the lowest possible value consistent with a good weld.Power required. When the interfaces are first brought into contact,maximum power is required, breaking up the surface film. The powerrequired then falls and remains nearly constant while the joint is raised towelding temperature. The power required for a given machine can be chosenso that the peak power falls within the overload capacity of the drivingmotor. It is the contact areas which determine the capacity of a machine.The rotational speed can be as low as 1 metre per second peripheral and thepressure depends upon the materials being welded, for example for mildsteel it can be of the order of 50 N/mm 2 for the first part of the cyclefollowed by 140 N/mm 2 for the forging operation. Non-ferrous metalsrequire a somewhat greater difference between the two operations. Thefaster the rotation of the component and the greater the pressure, theshorter the weld cycle, but some materials suffer from hot cracking if thecycle is too short and the time is increased with lower pressure to increasethe width of the HAZ. At the present time most steels can be weldedincluding stainless, but excluding free cutting. Non-ferrous metals are alsoweldable and aluminium (99.7% Al) can be welded to steel.
Friction welding
235
EQUAL DIAMETERIDEAL FORM
TUBES
IMPROVED PREPARATIONOF UNEQUAL DIAMETER BAR
AXIALLYMOVINGA COMPONENT ( \
ROTATINGCOMPONENT
\J
SURFACESMOVE INTOCONTACT
r\FRICTIONBETWEENSURFACESRAISESTEMPERATURE
FORGINGPRESSUREAPPLIED AFTERROTA TION ISSTOPPED. WELDCOMPLETED
236
237
There are various control systems: (1) Time control, in which after agiven set time period after contact of the faces, rotation is stopped andforge pressure is applied. There is no control of length with this method. (2)Burn-off to length: parts contact and heating and forging take place withina given pre-determined length through which the axially moving component moves. (3) Burn-off control: a pre-determined shortening of thecomponent is measured off by the control system when minimum pressuresare reached. Weld quality and amount of extrusion are thus controlled, butnot the length. (4) Forging to length: the axially moving work holder movesup to a stop during the forging operation irrespective of the state of theweld and generally in this case extrusion tends to be excessive.The extrusion of flash can be removed by a subsequent operation or, forexample for tubes of equal diameter, a shearing unit can be built into themachine operating immediately after forging and while the component ishot, thus requiring much less power. Fig. 5.12(a) illustrates a joint designedto contain the flash.In the process known as inertia welding the rotating component is held ina fixture attached to a flywheel which is accelerated to a given speed andthen uncoupled from its drive. The parts are brought together under highthrust and the advantage claimed is that there is no possibility of the drivingunit stalling before the flywheel energy is dissipated.Friction welding machines resemble machine tools in appearance, asillustrated in Fig. 5.13.
238
FILAMENT
ANODE
ELECTRON BEAM
239
to a relatively low vacuum after each loading. In either case welds suffer nocontamination because of vacuum conditions. Viewing of the spot for setup, focusing and welding is done by various optical arrangements.Welding in non-vacuum conditions requires much greater power thanfor the preceding method because of the effects of the atmosphere on thebeam and the greater distance from gun to work, and a shielding gas may berequired around the weld area. Research work is proceeding in this fieldinvolving guns of higher power consumption. Difficulties may also beencountered in focusing the beam if there is a variation in the gun-to-workdistance, as on a weld on a component of irregular shape.Welds made with this process on thicker sections are narrow with deeppenetration with minimum thermal disturbance and at present welds areperformed in titanium, niobium, tungsten, tantalum, beryllium, nickelalloys (e.g. nimonic), inconel, aluminium alloys and magnesium, mostly inthe aero and space research industries. The advantages of the process arethat being performed in a vacuum there is no atmospheric contaminationand the electrons do not affect the weld properties, accurate control overwelding conditions is possible by control of electron emission and beamfocus, and there is low thermal disturbance in areas adjacent to the weld(Fig. 5.15). Because of the vacuum conditions it is possible to weld the morereactive metals successfully. On the other hand the equipment is verycostly, production of vacuum conditions is necessary in many cases andthere must be protection against radiation hazards.
240
3 x 108 m/s, so that the frequency range of visible light is in the range430-750 x 1012 Hz.Atoms of matter can absorb and give out energy and the energy of anyatomic system is thereby raised or lowered about a mean or 'ground'level. When an atom or molecule is at an energy level higher than that ofthe ground state (or level) it is said to be excited, and in this condition twosimilar atoms can combine to form a molecule called a 'dimer'. Thecombination is for an extremely short time, and only when in the excitedstate. Energy can only be absorbed by atoms in definite small amounts(quanta) termed photons, and the relationship between the energy leveland the frequency of the photon is E = hv, where E is the energy level, his Planck's constant and v the photon frequency, so that the energy leveldepends upon the frequency of the photon. An atom can return to a lowerenergy level by emitting a photon and this takes place in an exceedinglyshort space of time from when the photon was absorbed, so that if aphoton of the correct frequency strikes an atom at a higher energy level,the photon which is released is the same in phase and direction as theincident photon.The principle of the laser (Light Amplification by Stimulated Emissionof Radiation) is the use of this stimulated energy to produce a beam ofFig. 5.15. Electron beam welding machine with indexing table, tooled forwelding distributor shafts to plates at a production rate of 450 per hour. Thegun is fitted with optical viewing system. Power 7.5 kW at 60 kV, 125 mA.Vacuum sealing is achieved by seals fitted in the tooling support plate and atthe bottom of the work chamber. As the six individual tooling stations reachthe welding station they are elevated to the weld position and then rotated byan electronically controlled d.c. motor.ji
*^V^L
VACUUM
tguhUB*
B A W ftCtCATt
1 <II^-:
II|l^^rt*aiSMnot
241
coherent light, that is one which is monochromatic, and the radiation hasthe same plane of polarization and is in phase. Lasers operate with wavelengths in the visible and infra-red region of the spectrum. When the beamis focused into a small spot and there is sufficient energy, welding, cuttingand piercing operations can be performed on metals.The ruby laser has a cylindrical rod of ruby crystal (A12O3) in whichthere is a trace of chromium as an impurity. An electronic flash gun, usuallycontaining neon, is used to provide the radiation for stimulation of theatoms. This type of gun can emit intense flashes of light of one or twomilliseconds duration and the gun is placed so that the radiations impingeon the crystal. The chromium atoms are stimulated to higher energy levels,returning to lower levels with the emission of photons. The stimulationcontinues until an 'inversion' point is reached when there are morechromium atoms at the higher levels than at the lower levels, and photonsimpinging on atoms at the higher energy level cause them to emit photons.The effect builds up until large numbers of photons are travelling along theaxis of the crystal, being reflected by the ends of the crystal back along theaxis, until they reach an intensity when a coherent pulse of light, the laserbeam (of wave-length about 0.06 /mi), emerges from the semi-transparentrod end. The emergent pulses may have high energy for a short time period,in which case vaporization may occur when the beam falls on a metalsurface, or the beam may have lower energy for a longer time period, inwhich case melting may occur, while a beam of intermediate power andduration may produce intermediate conditions of melting and vaporization, so that control of the time and energy of the beam and focusing of thespot exercise control over the working conditions.Developments of the ruby laser include the use of calcium tungstate andglass as the 'host' material with chromium, neodymium, etc., as impurities,a particular example being yttrium-aluminium-garnet with neodymium(YAG), used for operations on small components.The CO2 laser uses carbon dioxide for its main gas, with a little heliumor nitrogen. The tube may be some metres long, the average length of thebeam (10.6/mi) being longer than that of the solid state laser and othercontinuous wave or pulsed (the power increasing with the length of thetube). To increase the power without increasing the length of the unit,folded-beam lasers have many shorter tubes set parallel to each other; thebeam passes down each tube and is reflected from specially groundpolished copper mirrors set at the end of each tube. As with other gaslasers, electrical stimulation is by means of an HF discharge from a tube(similar to a fluorescent tube).A solid state laser (ruby, Nd-YAG), with operational wave-length of1.06 /im in the infra-red wave band, uses the heating effect of the beam.
242
Gas lasers use argon fluoride, krypton fluoride and xenon fluoride (andchlorides), giving a pulsed beam of 25-50 W at the ultra-violet end of thespectrum with little or no heat. On starting the tube, electricalstimulation from a radio frequency (r.f.) generator is connected to eachend of the tube. The helium atoms, or those of other seeding gases, arestimulated and their energy level raised above ground level. These atomstransfer their energy to the other gas in the tube, until inversion occurs anda coherent beam is emitted. This is known as collision excitation and gaslasers are used for visual effects of various colours.The excimer laser is of the helium-neon type and stimulation of the gasis to an energy level such that two atoms combine to form a 'dimer'.Energy is obtained from an HF electrical discharge through the tube.When the laser beam strikes a surface it dissociates the bond between themolecules and removes the surface by chemical action. It is used at presentfor micro-machining metallic and non-metallic surfaces, in rubbers,polymers, papers, glass etc., for surface hardening, marking and cuttingthin foils, and in eye operations to alter the contour of the cornea tocorrect short sight (a laser beam from the ultraviolet part of the spectrumis used).2 kW CO 2 lasers can be used to weld up to 3 mm thick material and arean alternative to the electron beam for thin gauge material. The width ofthe weld may be increased at speeds below 12 mm/s due to interactionbetween the beam and an ionized plasma which occurs near the work. Atspeeds of 20 mm/s and over, laser and electron beam welds are practicallyindistinguishable from one another.
Stud weldingThis is a rapid, reliable and economical method of fixing studs andfasteners of a variety of shapes and diameters to parent plate. The studsmay be of circular or rectangular cross-section, plain or threaded internallyor externally and vary from heavy support pins to clips used in componentassembly.There are two main methods of stud welding: (1) arc (drawn arc), (2)capacitor discharge, and the process selected for a given operation dependsupon the size, shape and material of the stud and the composition andthickness of the parent plate, the arc method generally being used forheavier studs and plate, and capacitor discharge for lighter gauge work.Arc (drawn arc) process
Stud welding
243
FOOTIADAPTOR
INTERCHANGEABLECHUCK
TWINADJUSTABLELEGS
CABLE
244
now closes and full welding current flows in an arc, creating a molten statein plate and stud end. The solenoid is de-energized and the stud is pushedunder controlled spring pressure into the molten pool in the plate. Finallythe main current contactor opens, the current is switched off, and theoperation cycle is complete, having taken only a few hundredths of asecond (Fig. 5.17).This method, which is usually employed, whereby the welding current iskept flowing until the return cycle is completed, is termed 4 hot plunge1. Ifthe current is cut offjust before the stud enters the molten pool it is termed'cold plunge'. The metal displaced during the movement of the stud intothe plate is moulded into fillet form by the ceramic ferrule or arc shield heldagainst the workpiece by the foot. This also protects the operator, retainsheat and helps to reduce oxidation.Studs from 3.3 mm to 20 mm and above in diameter can be used onparent plate thicker than 1.6 mm, and the types include split, U shaped,J bent anchors, etc. in circular and rectangular cross-section for theengineering and construction industries, and can be in mild steel (lowcarbon), austenitic stainless steel, aluminium and aluminium alloys (3-4%Mg). The rate of welding varies with the type of work, jigging, location,etc., but can be of the order of 8 per minute for the larger diameters and 20per minute for smaller diameters.Fig. 5.17. Arc stud welding, cycle of operations.CHUCK
>V
ARC SHIELDS
/>(c) MAIN CONTACTOR CLOSES ANDMAIN ARC ESTABLISHED
7///////////%
245
/ / JI I I 1 I 1 W U
246
coil is de-energized and spring pressure pushes the stud into contact withthe workpiece, the discharge takes place and the weld is made.This process minimizes the depth of penetration into the parent metalsurface and is used for welding smaller diameter ferrous and non-ferrousstuds and fasteners to light gauge material down to 0.45 mm thickness inlow-carbon and austenitic stainless steel, and 0.7 mm in aluminium and itsalloys and brass, the studs being from 2.8 to 6.5 mm diameter. Studs areusually supplied with a standard flange on the end to be welded (Fig. 5.18)but this can be reduced to stud diameter if required and centre punch marksshould not be used for location. The studs can be welded on to the reverseside of finished or coated sheets with little or no marking on the finishedside. The studs are not fluxed and no arc shield or ferrule is required.Typical equipment with a weld time cycle of 3-7 milliseconds consists ofa control unit and a hand- or bench-mounted tool or gun.The control unit houses the banks of capacitors of 100 000-200 000 n Fcapacitance depending upon the size of the unit, the capacitance requiredfor a given operation being selected by a switch on the front panel. Thecontrol circuits comprise a charging stage embodying a mains transformerand a bridge-connected full-wave silicon rectifier and the solid-state circuitsfor charging the capacitors to the voltage predetermined by the voltagesensing module. Interlocking prevents the energy being discharged byoperating the gun switch until the capacitors have reached the power preset by voltage and capacitance controls.The printed circuit voltage sensing module controls the voltage to whichthe capacitors are charged and switches them out of circuit when they arecharged to the selected voltage, and is controlled by a voltage dial on thepanel. A panel switch is also provided to discharge the capacitors ifrequired.Solid-state switching controls the discharge of the capacitors betweenstud and work, so there are no moving contactors. The gun, similar inappearance to the arc stud welding gun, contains the adjustable springpressure unit which enables variation to be made in the speed of return ofthe stud into the workpiece, and a chuck for holding the stud. Legs areprovided for positioning or there can be a nosecap gas shroud for use whenwelding aluminium or its alloys using an argon gas shield. The weldcannot be performed until legs or shroud are firmly in contact with theworkpiece.Welding rates attainable are 12 per minute at 6.35 mm diameter to 28 perminute at 3.2 mm diameter in mild steel. Similar rates apply to stainlesssteel and brass but are lower for aluminium because of the necessity ofargon purging. Partial scorch marks may indicate cold laps (insufficient
247
Explosive welding
energy) with the possibility of the stud seating too high on the work. Theweld should show even scorch marks all round the stud, indicating a soundweld. Excessive spatter indicates the use of too much energy.Automatic single- and multiple-head machines, pneumatically operatedand with gravity feed for the fasteners, are currently available.
Explosive weldingThis process is very successfully applied to the welding of tubes totube plates in heat exchangers, feedwater heaters, boiler tubes to clad tubeplates, etc.; and also for welding plugs into leaking tubes to seal the leaks.The welds made are sound and allow higher operating pressures andtemperatures than with fusion welding, and the tubes may be of steel,stainless steel or copper; aluminium brass and bronze tubes in naval brasstube plates are also successfully welded.The tube and tube plate may be parallel to each other (parallel geometry)with a small distance between them and the tube plate can be counterboredas in Fig. 5.19a. The explosive (e.g. trimonite) must have a low detonationvelocity, below the velocity of sound in the material, and there is no limit tothe joint area so that the method can be used for cladding surfaces. For thetube plate welds several charges can befiredsimultaneously, the explosivebeing in cartridge form.In the oblique geometry method now considered (YIMpact patent) thetwo surfaces are inclined at an angle to each other, Fig. 5.196, the tube platebeing machined or swaged as shown. As distance between tube and platecontinuously increases because of the obliquity, there is a limit to thesurface area which can be welded because the distance between tube andplate becomes too great.The detonation value of the explosive can be above the velocity of sound
TUBE
(a) PARALLEL
(b) OBLIQUE
248
249
Fig. 5.20
MACHINED ORSWAGED ANGLE
INSERTPOSITIONINGLEGS
EXPLOSIVE WELD-TUBE CUT OFF(c) COMPLETED WELD
METAL PLUG
r/ / / / / / / / / / / /
/////////////W
Since all the configuration is confined to the plug, the tube plate hole iscleaned by grinding, the plug with explosive charge is inserted and thedetonator wires connected. The plugs are available in diameters with1.5 mm increments.This method has proved very satisfactory in reducing the time and cost inrepair work of this nature.Personnel can be trained by the manufacturers or trained personnel areavailable under contract.
Gravity weldingThis is a method for economically welding long fillets in the flatposition using gravity to feed the electrode in and to traverse it along theplate. The equipment is usually used in pairs, welding two fillets at a time,one on each side of a plate, giving symmetrical welds and reducing stressand distortion. The electrode holder is mounted on a ball-bearing carriageand slides smoothly down a guide bar, the angle of which to the weld can beadjusted to give faster or slower traverse and thus vary the length of depositof the electrode and the leg length of the weld.The special copper alloy electrode socket is changed for varyingelectrode diameters and screws into the electrode holder, the electrodebeing pushed into a slightly larger hole in the socket and held there by theweight of the carriage. Turning the electrode holder varies the angle ofelectrode inclination. The base upon which the guide and support bar ismounted has two small ball bearings fitted so that it is easy to move alongthe base plate when resetting. If the horizontal plate is wider than about280 mm a counterweight can be used with the base, otherwise the base canbe attached to the vertical plate by means of two magnets or a jig can beused in place of the base to which the segment is fixed. A flexible cableconnects the electrode holder to a disconnector switch carried on the support arm. This enables the current to be switched on and off so that electrodes can be changed without danger of shock. A simple mechanism at thebottom of the guide bar switches the arc off when the carriage reaches thebottom of its travel (Fig. 5.22).At the present time electrodes up to 700 mm long are available indiameters of 3.5, 4.0, 4.5, 5.0 and 5.5 mm using currents of 220-315 A withrutile, rutile-basic and acid coatings suitable for various grades of steel.Gravity welding is usually used for fillets with leg lengths of 5-8 mm, thelengths being varied by altering the length of deposit per electrode. An a.c.power source is used for each unit with an OCV of 60 and arc volts about40 V with currents up to 300 A. Sources are available for supplying up to 6
Thermit welding
251
Thermit weldingThermit (or alumino-thermic) is the name given to a mixture offinely divided iron oxide and powdered aluminium. If this mixture is placedin afireclaycrucible and ignited by means of a special powder, the action,once started, continues throughout the mass of the mixture, giving outgreat heat. The aluminium is a strong reducing agent, and combines withthe oxygen from the iron oxide, the iron oxide being reduced to iron.The intense heat that results, because of the chemical action, not onlymelts the iron, but raises it to a temperature of about 3000 C. Thealuminium oxidefloatsto the top of the molten metal as a slag. The crucibleis then tapped and the superheated metal runs around the parts to bewelded, which are contained in a mould. The high temperature of the ironresults in excellent fusion taking place with the parts to be welded.Additions may be made to the mixture in the form of good steel scrap, or asmall percentage of manganese or other alloying elements, therebyproducing a good quality thermit steel. The thermit mixture may consist ofabout 5 parts of aluminium to 8 parts of iron oxide, and the weight ofthermit used will depend on the size of the parts to be welded. The ignition
SUPPORT ARM^^^ GUIDE BAR- ELECTRODECARRIAGE (ONBALL BEARINGS)
ADJUSTMENT 0F\INCLINATION OF tGUIDE BAR!- o
f-7y
^/
BASE
\y
^ Z ^~^P
ELECTRODEHOLDER
NK
ELECTRODEANGLE i \
252
powder usually consists of powdered magnesium or a mixture of aluminium and barium peroxide.PreparationThe ends which are to be welded are thoroughly cleaned of scaleand rust and prepared so that there is a gap between them for the moltenmetal to penetrate well into the joint. Wax is then moulded into this gap,and also moulded into a collar round the fracture. This is important, as itgives the necessary reinforcement to the weld section. The moulding box isnow placed around the joint and a mould of fireclay and sand made, a riser,pouring gate and pre-heating gate being included. The ends to be weldedare now heated through the pre-heating gate by means of a flame and thewax is first melted from between the ends of the joint. The heating iscontinued until the ends to be welded are at red heat. This prevents thethermit steel being chilled, as it would be if it came into contact with coldmetal. The pre-heating gate is now sealed off with sand and the thermitprocess started by igniting the powder. The thermit reaction takes up toabout 1 minute, depending upon the size of the charge and the additionsthat have been made in the form of steel scrap and alloying elements etc.When the action is completed the steel is poured from the crucible throughthe pouring gate, and it flows around the red-hot ends to be welded, excellent fusion resulting. The riser allows extra metal to be drawn by the weldedsection when contraction occurs on cooling, that is it acts as a reservoir.The weld should be left in the mould as long as possible (up to 12 hours),since this anneals the steel and improves the weld.Thermit steel is pure and contains few inclusions. It has a tensile strengthof about 460 N/mm 2 . The process is especially useful in welding togetherparts of large section, such as locomotive frames, ships' stern posts andrudders, etc. It is also being used in place of flash butt welding for thewelding together of rail sections into long lengths.At the present time British Rail practice is to weld 18 m long rails intolengths of 91 to 366 m at various depots by flash butt welding. These lengthsare then welded into continuous very long lengths in situ by means of thethermit process and conductor rails are welded in the same way. Normalrunning rails have a cross-sectional area of 7184 mm2 and two techniquesare employed, one requiring a 7 minute pre-heat before pouring the moltenthermit steel into the moulds and the other requiring only 1^ minutes preheat, the latter being the technique usually employed. Excess metal can beremoved by pneumatic hammer and hot chisel or by portable trimmingmachine.
Underwater welding
253
Underwater weldingThe three main methods of underwater welding at present are (1)wet, (2) localized dry chamber, (3) dry habitat (surroundings).Wet welding
254
the slowest method as it is a low deposition rate process. It can be used forroot runs and hot passes, but MMA or the flux cored method is used forfilling and capping. Stringer bead techniques may be used to imparttoughness, and temper beads to minimize HAZ hardness. Generally thehigh-strength, basic-coated steel electrodes which may contain iron powderare used. They are pre-heated in a drying oven immediately before use andpre-heat of about 100C can be applied locally to the joint.After welding, the joints are subject to X-ray or ultra-sonic testingaccording to the welding codes used.Coffer dam
INTERCHANGEABLE COLLETSFOR VARIOUS SIZES OFELECTRODES
ELECTRIC POWERCABLE
OXYGEN SUPPLY(WHEN USED FOR CUTTING)
6Oxy-acetylene welding
256
Oxy-acetylene welding
cylinders are rated according to the amount of gas they contain, varyingfrom 0.68 m 3 at a pressure of 137 bar to 9.66 m 3 at 200 bar.The volume of oxygen contained in the cylinder is approximatelyproportional to the pressure; hence for every 10 litres of oxygen used, thepressure drops about 0.02 N/mm 2 . This enables us to tell how much oxygenremains in a cylinder. The oxygen cylinder is provided with a valvethreaded right hand and is painted black. On to this valve, which contains ascrew-type tap, the pressure regulator and pressure gauge are screwed. Theregulator adjusts the pressure to that required at the blowpipe. Since greaseand oil can catch fire spontaneously when in contact with pure oxygenunder pressure, they must never be used on any account upon any part ofthe apparatus. Leakages of oxygen can be detected by the application of asoap solution, when the leak is indicated by the soap bubbles. Never test forleakages with a naked flame.Liquid oxygenLiquid oxygen, nitrogen, argon and LPG are available in bulksupply from tankers to vacuum-insulated evaporators (VIE) in which theliquid is stored at temperatures of 160 to 200 C and are veryconvenient for larger industrial users.There is no interruption in the supply of gas nor drop in pressure duringfilling.The inner vessel, of austenitic stainless steel welded construction, hasdished ends and is fitted with safety valve and bursting disc and is availablein various sizes with nominal capacities from 844 to 33 900 m 3. Nominalcapacity is the gaseous equivalent of the amount of liquid that the vesselwill hold at atmospheric pressure. The outer vessel is of carbon steel andfitted with pressure release valve. The inner vessel is vacuum and pearliteinsulated from the outer vessel, thus reducing the thermal conductivity to aminimum. The inner vessel A (Fig. 6.1) contains the liquid with gas above,and gas is withdrawn from the vessel through the gaseous withdrawal line Band rises to ambient temperature in the superheater-vaporizer C, fromwhich it passes to the supply pipeline. If the pressure in the supply fallsbelow the required level the pressure control valve D opens and liquid flowsunder gravity to 'the pressure-raising vaporizer E, where heat is absorbedfrom the atmosphere, and the liquid vaporizes and passes through the gaswithdrawal point H raising the pressure to the required pre-set level whichcan be up to 1.7 N/mm 2 (250 lbf/in2), and the valve D then shuts.In larger units, to allow for heavy gas demand, when the pressure falls onthe remote side of the restrictive plate F, liquid flows from the vessel via thewithdrawal line G and passes to the superheater-vaporizer where it changes
257
INNER VESSEL
LINE
258
Storage(1) Store in a well ventilated, fire-proof room with flame-proofelectrical fittings. Do not smoke, wear greasy clothing or haveexposed flames in the storage room.(2) Protect cylinders from snow and ice and from the direct rays of thesun, if stored outside.(3) Store away from sources of heat and greasy and oily sources. (Heatincreases the pressure of the gas and may weaken the cylinder wall.Oil and grease may ignite spontaneously in the presence of pureoxygen.)
259
260
261
CYLINDERPRESSURE
BLOWPIPEPRESSURE
CONNECT/ONTO CYLINDER
262
263
OUTLETPRESSURE GAUGE1ST STAGE VALVE. PRESETREDUCES CYLINDER PRESSURETO LOWER PRESSUREREQUIRED BY 2ND STAGE.E.G. 200bar TO 23bar.(CYLINDER PRESSURE DEPENDSUPON TYPE OF CYLINDER,VOLUME AND CONTENTS).
CYLINDER PRESSUREGAUGE
264
Oxy-acetylene weldingFig. 6.3. (b) Multi-stage regulator.
Key:1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.
Disc monogram.Ring cover.Knob.Set screw.Name plateScrew P. A.Bonnet.Spring centre.Spring.Nut.Packing plate.Diaphragm.Diaphragm carrier.Washer.Screw P. A.Nozzle.Valve pin.Valve.
19. Washer.20. Spring.21. Outlet adaptor LH.Outlet adaptor RH.22. Inlet nut LH.Inlet nut RH.23. Inlet nipple.24. Filter.25. Retaining ring.26. Plug.27. Safety valve LP.28. Gauge.29. Gauge.30. Relief valve HP.31. Gauge glass.32. Sleeve.33. Spring.34. Valve.
35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.
Plunger.Nozzle and seat.Sealing ring.Diaphragm carrier.Diaphragm.Disc.Spring.Damper plug.Pivot.Bonnet.Screw.Disc anti-tamper.Spring.Valve.Seat retainer.Seat.Valve holder.Indicator assembly.
265
Fig. 6.3. (d) Two-stage regulator. 230 bar inlet fitted with resettable flashbackarrestor.
266
quantities are being used, the regulator may become blocked with particlesof ice, causing stoppage. This happens most frequently in cold weather, andcan be prevented by use of an electric regulator heater. The heater screwsinto the cylinder and the regulator screws into the heater. The heater isplugged into a source of electric supply, the connexion being by flexiblecable.HosesHoses are usually of a seamless flexible tube reinforced with pliesof closely woven fabric impregnated with rubber and covered overall with atough, flexible, abrasion-resistant sheath giving a light-weight hose. Theyare coloured blue for oxygen, red for fuel gases, black for non-combustiblegases and orange for LPG, Mapp and natural gas. Available lengths arefrom 5 to 20 m, with bore diameters 4.5 mm for maximum working pressureof 7 bar, 8 mm for a maximum of 12 bar and 10 mm for a maximumworking pressure of 15 bar. Nipple- and nut-type connexions and couplersare available for 4.5 mm (f in.), 8 and 10 mm hoses with 6.4 mm {\ in. BSP)and 10mm (fin. BSP) nuts. A hose check valve is used to preventfeeding back of gases from higher or lower pressures and reduces thedanger of a flashback due to a blocked nozzle, leaking valve, etc. It isconnected in the hose at the blowpipe end or to the economizer orregulator, and consists of a self-aligning spring-loaded valve which seals offthe line in the event of backflow. BS 924 J and 796 J apply to hoses.The welding blowpipe or torch
There are two types of blowpipes: (1) high pressure, (2) lowpressure, and each type consists of a variety of designs depending on theduty for which the pipe is required. Special designs are available forrightward and leftward methods of welding (the angle of the head isdifferent in these designs), thin gauge or thick plate, etc., in addition toblowpipes designed for general purposes.The high-pressure blowpipe is simply a mixing device to supplyapproximately equal volumes of oxygen and acetylene to the nozzle, and isfitted with regulating valves to vary the pressure of the gases as required(Fig. 6.4a, b). A selection of shanks is supplied with each blowpipe, havingorifices of varying sizes, each stamped with a number or with theconsumption in litres per hour (1/h). Various sizes of pipes are available,from a small light variety, suitable for thin gauge sheet, to a heavy dutypipe. A high-pressure pipe cannot be used on a low-pressure system.The low-pressure blowpipe has an injector nozzle inside its body throughwhich the high-pressure oxygen streams (Fig. 6.5). This oxygen draws the
267
6.7.8.9.
268
low-pressure acetylene into the mixing chamber and gives it the necessaryvelocity to preserve a steady flame, and the injector also helps to preventbackfiring. The velocity of a 1/1 mixture of oxygen/acetylene may be 200 mper minute, while the maximum gas velocity occurs for a 30% acetylenemixture and may be up to 460 m per min. (These figures are approximateonly.)It is usual for the whole head to be interchangeable in this type of pipe, thehead containing both nozzle and injector. This is necessary, since there is acorresponding injector size for each nozzle. Regulating valves, as on thehigh-pressure pipes, enable the gas to be adjusted as required. The lowpressure pipe is more expensive than the high-pressure pipe; and it can beused on a high-pressure system if required, but it is now used on a very smallscale.A very useful type of combined welding blowpipe and metal-cuttingtorch is shown in Fig. 6.6. The shank is arranged so that a full range ofnozzles, or a cutting head, can be fitted. The design is cheaper than for acorresponding separate set for welding and cutting, and the cutter issufficient for most work.The oxy-acetylene flameThe chemical actions which occur in the flame have already beendiscussed in Volume 1, and we will now consider the control and regulationof the flame to a condition suitable for welding.
Fig. 6.6. Combined welding and cutting pipes. Will weld sections from 1.6 mmto 32 mm thick, and cut steel up to 150 mm thick with acetylene and 75 mmwith propane.
SHANK
269
Adjustment of the flame.* To adjust the flame to the neutral condition theacetylene is first turned on and lit. The flame is yellow and smoky. Theacetylene pressure is then increased by means of the valve on the pipe untilthe smokiness has just disappeared and the flame is quite bright. Thecondition gives approximately the correct amount of acetylene for theparticular jet in use. The oxygen is then turned on as quickly as possible,and as its pressure is increased the flame ceases to be luminous. It will nowbe noticed that around the inner blue luminous cone, which has appearedon the tip of the jet, there is a feathery white plume which denotes excessacetylene (Fig. 6.1a). As more oxygen is supplied this plume decreases insize until there is a clear-cut blue cone with no white fringe (Fig. 6.7b). Thisis the neutral flame used for most welding operations. If the oxygen supplyis further increased, the inner blue cone becomes smaller and thinner andthe outer envelope becomes streaky; the flame is now oxidizing (Fig. 6.7c).Since the oxidizing flame is more difficult to distinguish than thecarbonizing or carburizing (excess acetylene) flame, it is always better tostart with excess acetylene and increase the oxygen supply until the neutralcondition is reached, than to try to obtain the neutral flame from theoxidizing condition.Some welders prefer to regulate the oxygen pressure at the regulatoritself. The acetylene is lighted as before, and with the oxygen valve on theblowpipe turned full on, the pressure is adjusted correctly at the regulatoruntil the flame is neutral. In this way the welder is certain that the regulatoris supplying the correct pressure to the blowpipe for the particular nozzlebeing used.Fig. 6.7
CARBURIZING FLAME
(c)
OXIDIZING FLAME
* The pressure on oxygen and acetylene gauges is approximately that given in thetable on p. 276.
270
271
272
inlet orifice, centred against the valve and pushed hard home resetting thevalve mechanism. On some models there is a visible lever which is actuatedwhen the arrestor cut-off valve operates. This lever actuates the mechanismbut should never be reset until the cause of the flashback is determined andput to rights.After several actuations, carbon deposits may interfere with the correctfunctioning of the arrestor so it should be exchanged. Arrestors aregenerally used up to oxygen pressures of 10 bar, propane of 5 bar andacetylene of 1.5 bar.Operation. The spring-loaded valve (or piston) is held by a low meltingpoint solder against the tension of a spring. If a flashback occurs thetemperature rising to 120-150 C melts the solder and the non-returnvalve is forced onto its seat and prevents further reverse flow of gas. Thereis little restriction of gas flow under normal working conditions but in thecase of the piston being activated the whole unit must be replaced (Figs.6.86, c).
PRESSURE SENSI Tl VECUT-OFF VALVE 2
FLAME ARRESTOR 1
PRESSURE RELIEFVAL VE 3
273
SINTEREDELEMENTS
THERMALLYACTIVATEDCUT-OFF VALVE
CHECKVALVE
(O
NORMAL GASFLOW IN
274
Fig. 6.9a indicates the main features of a good fusion weld, with thefollowing features:(a) Good fusion over the whole side surface of the V.(b) Penetration of the weld metal to the underside of the parent plate.(c) Slight reinforcement of the weld above the parent plate.(d) No entrapped slag, oxide, or blowholes.Fig. 6.9b indicates the following faults in a weld:(a) Bad flame manipulation and too large a flame has caused moltenmetal to flow on to unfused plate, giving no fusion (i.e. adhesion).(b) Wrong position of work, incorrect temperature of molten metal,and bad flame manipulation has caused slag and oxide to beentrapped and channels may be formed on each line of fusion,causing undercutting.(c) The blowpipe flame may have been too small, or the speed ofwelding too rapid, and this with lack of skill in manipulation hascaused bad penetration.(N.B. Reinforcement on the face of a weld will not make up for lack ofpenetration.)
Methods of weldingThe following British Standards apply to this section: BS 1845,Filler alloys for brazing; BS 1723, Brazing; Part 1 Specification forbrazing, Part 2 Guide to brazing; BS 1724, Bronze welding by gas; BS 1453,Filler materials for gas welding (ferritic steels, cast iron, austenitic stainlesssteels, copper and copper alloys, aluminium and aluminium alloys andmagnesium alloys); BS 1821, Class 1 oxy-acetylene welding of ferritic steelFig. 6.9GOOD PROFILE OFFACE OF WELD
TOE OF WELDNUNDERCUTOVERLAPm
NO BLOWHOLENOR POROSITY
ROOTFACE
^GOODROOTPENETRATION
LACK OF REINFORCEMENTI LACK OfJNTER-RUNUNDERCUT
FUSION
LACK OF ROOTPENETRATIONIMPERFECTIONS IN A WELD
Methods of welding
275
,60-70
vwwww
MOTION OF BLOWPIPE.ROD MOVES IN STRAIGHT LINE
276
that as the V becomes narrower the blowpipe flame tends to push themolten metal from the pool, forward along onto the unmelted sides of theV, resulting in poor fusion or adhesion. This gives an unsound weld, andthe narrower the V the greater this effect.As the plate to be welded increases in thickness, a larger nozzle isrequired on the blowpipe, and the control of the molten pool becomes moredifficult; the volume of metal required to fill the V becomes increasinglygreater, and the size of nozzle which can be used does not increase inproportion to the thickness of the plate, and thus welding speed decreases.Also with thicker plates the side-to-side motion of the blowpipe over a wideV makes it difficult to obtain even fusion on the sides and penetration to thebottom, while the large volume of molten metal present causes considerable expansion. As a result it is necessary to weld thicker plate withtwo or more layers if this method is used. From these considerations it canbe seen that above 6.4 mm plate the leftward method suffers from severaldrawbacks. It is essential, however, that the beginner should becomeefficient in this method before proceeding to the other methods, since forgeneral work, including the non-ferrous metals (see later), it is the mostused.
Edge preparation(Letters refer toFig. 6.11)
Thicknessof plate(mm)
Nozzlesize(mm)
Oxygen andacetylenepressure(bar)
2.4-3.0
3.0-4.0
0.9-11.2-22-32.6-53.2-74.0-10
0.140.140.140.140.140.21
0 . 8 - 3 mm GAP(b)
1.6-3 mm GAP
Oxygen andacetylenegasconsumption(1/h)285786140200280
277
100-110'
-50*
278
Edge preparation(Letters refer toFig. 6.13)
4.8-8.2
5.5-136.5-188.2-2510-3513-45
8.2-15
Oxygen andacetylenepressure(bar)0.280.280.420.630.35(heavy dutymixer)
3-3.B mm GAP
Oxygen andacetylenegasconsumption(1/h)37052071010001300
279
Vertical weldingThe preparation of the plate for welding greatly affects the cost ofthe weld, since it takes time to prepare the edges, and the preparation givenaffects the amount of filler rod and gas used. Square edges need nopreparation and require a minimum of filler rod. In leftward weldingsquare edges are limited to 3.2 mm thickness and less. In vertical welding,up to 4.8 mm plate can be welded with no V'ing with the single-operatormethod while up to 16 mm plate can be welded with no V'ing with the twooperator method, the welders working simultaneously on the weld fromeach side of the plate. The single-operator method is the most economicalup to 4.8 mm plate.The single-operator method (up to 4.8 mm plate) requires more skill inthe control of the molten metal than in downhand welding. Welding isperformed either from the bottom upwards, and the rod precedes the flameas in the leftward method, or from the top downwards, in which case themetal is held in place by the blowpipe flame. This may be regarded as therightward method of vertical welding, since the flame precedes the roddown the seam. In the upward method the aim of the welder is to use theweld metal which has just solidified as a ' step' on which to place the moltenpool. A hole is first blown right through the seam, and this hole ismaintained as the weld proceeds up the seam, thus ensuring correctpenetration and giving an even back bead.In the vertical welding of thin plate where the edges are close together, asfor example in a cracked automobile chassis, little filler rod is needed andthe molten pool can be worked upwards using the metal from the sides ofthe weld. Little blowpipe movement is necessary when the edges are closetogether, the rod being fed into the molten pool as required. When theedges are farther apart, the blowpipe can be given the usual semicircularmovement to ensure even fusion of the sides.From Fig. 6.14 it will be noted that as the thickness of the plate increases,the angle of the blowpipe becomes much steeper.When welding downwards much practice is required (together with thecorrect size flame and rod), in order to prevent the molten metal fromfalling downwards. This method is excellent practice to obtain perfectcontrol of the molten pool.Double-operator vertical weldingThe flames of each welder are adjusted to the neutral condition,both flames being of equal size. To ensure even supply of gas to each pipethe blowpipes can be supplied from the same gas supply. It is possible to usemuch smaller jets with this method, the combined consumption of which is
280
less than that of a single blowpipe on the same thickness plate. Blowpipesand rods are held at the same angles by each operator, and it is well that athird person should check this when practice runs are being done. To avoidfatigue a sitting position is desirable, while, as for all types of verticalwelding, the pipes and tubes should be as light as possible. Angles ofblowpipes and rods are shown in Fig. 6.15.This method has the advantage that plate up to 16 mm thick can bewelded without preparation, reducing the gas consumption and filler rodused, and cutting out the time required for preparation. When twooperators are welding 12.5 mm plate, the gas used by both is less than 50%
. 3.2 mm
3.2 mm3.2 mm
4.8 mm
281
of the total consumption of the blowpipe when welding the same thicknessby the downhand rightward method. Owing to the increased speed ofwelding and the reduced volume of molten metal, there is a reduction in theheating effect, which reduces the effects of expansion and contraction.Overhead welding
Fig. 6.16. (a) Leftward overhead welding. The flame is used to position themolten metal, (b) Rightward overhead welding. Blowpipe has little motion.Rod moves criss-cross from side to side.
282
This method was devised by the Linde Co. of the United States forthe welding of pipelines (gas and oil), and for this type of work it is verysuitable. Its operation is based on the following facts:(1) When steel is heated in the presence of carbon, the carbon willreduce any iron oxide present, by combining with the oxygen andleaving pure iron. The heated surface of the steel then readilyabsorbs any carbon present.(2) The absorption of carbon by the steel lowers the melting point ofthe steel (e.g. pure iron melts at 1500C, while cast iron with 3^%carbon melts at 1130C).In Lindewelding the carbon for the above action is supplied by using acarburizing flame. This deoxidizes any iron oxide present and then thecarbon is absorbed by the surface layers, lowering their melting point. Byusing a special rod, a good sound weld can be made in this way at increasedspeed. The method is almost exclusively used on pipe work and isperformed in the downhand position only.Block welding
Fig. 6.17THIRD RUN REGINS AGAIN HERE
283
first run started. Similarly with the third run, which starts at F. Uponcompleting the weld in the case of a pipe, the first run finishes at A, thesecond one at C and the third one at E, giving a good anchorage on to theprevious run.*Horizontal-vertical fillet weldingIn making fillet welds (Fig. 6.18), care must be taken that, inaddition to the precautions taken regarding fusion and penetration, thevertical plate is not undercut as in Fig. 6.19Z?, and the weld is not of aweakened section. A lap joint may be regarded as a fillet. No difficulty willbe experienced with undercutting, since there is no vertical leg, but careshould be taken not to melt the edge of the lapped plate.The blowpipe and rod must be held at the correct angles. Holding the
OPEN CORNER
D C(II) SINGLE VPREPARATION
(b) DOUBL
VPRtf'ARATIUN
LEGS OF UNEQUALLENGTH
NO ROOTPENETRATION
POOR WELDS
GOOD WELD
* Refer also to BS 1821 and 2640, Class I and class II oxy-acetylene welding of steel pipelines andassemblies fo r carry ing fluids.
284
flame too high produces undercutting, and the nozzle of the cone should beheld rather more towards the lower plate, since there is a greater mass ofmetal to be heated in this than in the vertical plate (Fig. 6.19# and b).Figure 6.20 a and b show the angles of the blowpipe and rod, the latterbeing held at a steeper angle than the blowpipe. Fillet welding requires alarger size nozzle than when butt welding the same section plate, owing tothe greater amount of metal adjacent to the weld. Because of this, multi-jetblowpipes can be used to great advantage for fillet welding. The single(Fig. 6.19a) preparation is used for joints which are subjected to severeloading, while the double V preparation (Fig. 6.196) is used for thicksection plate when the welding can be done from both sides. The type ofpreparation therefore depends entirely on the service conditions, theunprepared joint being quite suitable for most normal work.All-position rightward welding
285
ROD 10 ABOVEHORIZONTAL
BLOWPIPE NOZZLEALMOST HORIZONTAL'JUST BELOW)
SIDE ELEVATION
SIDE ELEVATIONROD MOVING TO AND FROACROSS WELD AND UP ANDDOWN TO ENABLE SURFACETENSION TO PULL METALINTO POOL
END ELEVATION
OVERHEADBLOWPIPE.:MOVING UPWARDSU,LITTLE SIDE MOVEMENTPLAN
OF WELD
VERTICAL
HORIZONTALVERTICAL
Medium carbonsteel(copper coated)Pipe-weldingsteel
Composition %MnNi0.6
ApplicationCr
0.25
286
287
40-
288
After treatment. The slag and oxide on the surface of the finished weld canbe removed by scraping and brushing with a wire brush, but the weldshould not be hammered. The casting is then allowed to cool off veryslowly, either in the furnace or fire, or if it has been pre-heated with theflame, it can be put in a heap of lime, ashes or coke, to cool. Rapid coolingwill result in a hard weld with possibly cracking or distortion.Malleable cast iron weldingThis is unsuitable for welding with cast-iron rods because of itsstructure. If attempted it invariably results in hard, brittle welds having nostrength. The best method of welding is with the use of bronze rods, and isdescribed below.
289
bond without fusion of the parent metal. There is less thermal disturbancethan with fusion welding due to the lower temperatures involved and theprocess is simple and relatively cheap to perform. Unlike capillary brazing(see pp. 317-19) the strength of the joint is not solely dependent upon theareas of the surfaces involved in the joint but rather upon the tensilestrength of the filler metal. A bronze weld has relatively great strength inshear, and joints are often designed to make use of this (Fig. 6.24a, b and c).The final strength of the welded joint depends upon the bond betweenfiller metal and parent metal so that thorough cleanliness of the joints andimmediate surroundings is essential to ensure that the molten filler metalshould flow over the areas and 'wet' them completely without excessivepenetration of the parent metal, and there should be freedom fromporosity. Care, therefore, should be taken to avoid excessive overheating.Figs. 6.25 and 6.26 show various joint designs for plate and tube.If bronze filler wires are used on alloys such as brasses and bronzes themelting points of wire and parent metal are so nearly equal that the result isa fusion weld.General method of preparation for bronze welding. All impurities such asscale, oxide, grease, etc., should be removed, as these would prevent thebronze wetting the parent metal. The metal should be well cleaned on bothupper and lower faces for at least 6 mm on each side of the joint, so that thebronze can overlap the sides of the joint, running through and under on thelower face.Bronze welding is unlike brazing in that the heat must be kept as local aspossible by using a small flame and welding quickly. The bronze must flowin front of the flame for a short distance only, wetting the surface, and byhaving sufficient control over the molten bronze, welding may be done in
Fig. 6.25. Typical joint designs for bronze welding (sheet and plate).JLAP JOINT
V BUTT JOINT
DOUBLE
290
C4
C5
C(\
CZ6
CZ7
CZ8
Cu 57.00Si 0.20Zn balanceSn optional
to 63.00to 0.50
Cu 57.00Si 0.15Mn 0.05FeO.10Zn balanceSn optional
totototo
Cu 45.00Si 0.15Ni 8.00Zn balanceSn optionalMn optionalFe optional
to 53.00to 0.50to 11.00
pn
to 45.00to 0.50to 16.00
V^U
no
A\tl.UU
Si 0.20Ni 14.00Zn balanceSn optionalMn optionalFe optional
Approx.meltingRecommended pointfor usage onApplications(C)CopperMild steel
875-895 A silicon-bronzeused for coppersheet and tubemild steel and lineproduction applications.
CopperCast ironWrought iron
Mild steelCast ironWrought iron
970-980 A nickel-bronzefor bronze welding steel and malleable iron, building up worn surfaces and weldingCu-Zn-Ni alloysof similar composition.
to 0.50 max.
63.000.300.250.50
to 0.50 max.to 0.50 max.to 0.50 max.
to 1.00 max.to 0.20 max.to 0.30 max.
poet iron
V^dol 11 KJli
Wrought iron
Similartn CSOllllllCtl IU V^^k(CZ8).
291
BRANCH
BELL
JOINT
TYPE 1 JOINT
SHORT BELL
BRANCH JOINT
292
alloys are given in the table, those containing nickel giving greater strength,the bronze flux being of the borax type.Technique. The leftward method is used with the rod and blowpipe held asin Fig. 6.28, the inner cone being held well away from the molten metal. Therod is wiped on the edges of the cast iron and the bronze wets the surface. Itis sometimes advisable to tilt the work so that the welding is done uphill, asshown in Fig. 6.28. This gives better control. Do not get the work too hot.Vertical bronze welding of cast iron can be done by the two-operatormethod, and often results in saving of time, gas and rods and reduces therisk of cracking and distortion.The edges are prepared with a double 90 V and thoroughly cleaned for12 mm on each side of the edges. The blowpipes are held at the angle shownin Fig. 6.29a. Blowpipe and rod are given a side to side motion, as indicatedin Fig. 629b as the weld proceeds upwards, so as to tin the surfaces.Malleable cast ironThe bronze welding of malleable castings may be stated to be theonly way to ensure any degree of success in welding them. Both types(blackheart and whiteheart) can be welded satisfactorily in this way, sincethe heat of the process does not materially alter the structure. The method isthe same as for cast iron, using nickel bronze rods (C5) and a borax-typeflux.SteelIn cases where excessive distortion must be avoided, or where thinsections are to be joined to thick ones, the bronze welding of steel is oftenFig. 6.28. Bronze welding cast iron.
WELD OVERLAPSTOP FACES
293
used, the technique being similar to that for cast iron, except, of course, thatno pre-heating is necessary.Galvanized ironThis can be easily bronze welded, and will result in a strongcorrosion-resisting joint, with no damage to the zinc coating. If fusionwelding is used, the heat of the process would of course burn the zinc (orgalvanizing) off the joint and the joint would then not resist corrosion.Preparation, flame and rod. For galvanized sheet welding, the edges of thejoint are tack welded or held in a jig and smeared with a silver-copper flux.Thicker plates and galvanized pipes are bevelled 60-80 and tacked toposition them. The smallest possible nozzle should be used (for the sheetthickness) and the flame adjusted to be slightly oxidizing. Suitable filleralloys are given in the table (p. 290) as for steel.Technique. No side to side motion of the blowpipes is given, the flame beingdirected on to the rod, so as to avoid overheating the parent sheet. The rodis stroked on the edges of the joint so as to wet them. Excessive flux must bewashed off with hot water.
Fig. 6.29. (a) Two-operator vertical bronze welding of cast iron, (b) Showingmotion of pipe and rod.
90*
294
Oxy-acetylene weldingCopper
. .
295
Technique. The method is similar to that for cast iron, and the finaldifference between the bronze-welded and brazed joint is that the formerhas the usual wavy appearance of the oxy-acetylene weld, while the latterhas a smooth appearance, due to the larger area over which the heat wasapplied. The bronze joint is, of course, much stronger than the brazed one.Brasses and zinc-containing bronzesSince the filler rod now melts at approximately the same temperature as the parent metal, this may now be called fusion welding. When thesealloys are heated to melting point, the zinc is oxidized, with copiousevolution of fumes of zinc oxide, and if this continued, the weld would befull of bubble holes and weak (Fig. 6.32). This can be prevented by using anoxidizing flame, so as to form a layer of zinc oxide over the molten metal,and thus prevent further formation of zinc oxide and vaporization.Preparation. The edges of the faces of the joint are cleaned and prepared asusual, sheets above 3.2 mm thickness being V'd to 90. Flux can be appliedby making it into a paste, or by dipping the rod into it in the usual manner,or a flux-coated rod can be used.Flame and rod. Suitable filler alloys are given in the table (p. 290), whilea brass rod is used for brass welding, the colour of the weld then beingsimilar to that of the parent metal. Owing to the greater heat conductivity,a larger size jet is required than for the same thickness of steel plate. Theflame is adjusted to be oxidizing, as for bronze welding cast iron, and theexact flame condition is best found by trial as follows. A small test pieceof the brass or bronze to be welded is heated with a neutral flame andgives off copious fumes of zinc oxide when molten. The acetylene is nowcut down until no more fumes are given off. If any blowholes are seen inthe metal on solidifying, the acetylene should be reduced slightly further.The inner cone will now be about half its normal neutral length. TooFig. 6.31
SADDLE JOINT
296
Oxy-acetylene weldingFig. 6.32. (a) Unsatisfactory brass weld made with neutral flame,Unetched x 2.5. (b) Brass weld made with insufficient excess of oxygen.Unetched. (c) Correct brass weld made with adequate excess of oxygen.Unetched. x 2.5.
297
much oxygen should be avoided, as it will form a thick layer of zinc oxideover the metal and make the filler rod less fluid.The weld is formed in the 'as cast' condition, and hammering improvesits strength. Where 60/40 brass rods have been used the weld should behammered while hot, while if 70/30 rods have been used the weld should behammered cold and finally annealed from dull red heat.Tin bronze
Aluminium bronze can be welded using a filler rod of approximately 90% copper, 10% aluminium (C13, BS 2901 Pt 3), meltingpoint 1040 C, a rod also suitable for welding copper, manganese bronzeand alloy steels where resistance to shock, fatigue and sea-water corrosionis required. The aluminium bronze flux (melting point 940 C) can be mixedwith water to form a paste if required.Preparation. The edges of the joint should be thoroughly cleaned by filingor wire brushing to remove the oxide film which is difficult to dissolve.Up to 4.8 mm thickness no preparation is required -just a butt joint withgap. Above 4.8 mm the usual V preparation is required and a double Vabove 16 mm thick. Sheets should not be clamped for welding, as this tendsto cause the weld to crack, they must be allowed to contract freely oncooling, and it is advisable to weld a seam continuously and not make startsin various places.Flame and rod. A neutral flame is usually used - any excess of acetylenetends to produce hydrogen with porosity of the weld, while excess oxygencauses oxidation. Flame size should be carefully chosen according to thethickness of the plate - too small a flame causes the weld metal to solidifytoo quickly while there is a danger of burning through with too large aflame.
298
The filler rod should be a little thicker (0.8 mm) than the sheet to bewelded to avoid overheating, and it should be added quickly to givecomplete penetration without deep fusion.Technique. The leftward method is used with a steep blowpipe angle (80) tostart the weld, this being reduced to 60-70 as welding progresses. Theparent metal should be well pre-heated prior to starting welding and duringwelding a large area should be kept hot to avoid cracks. The rod should beused with a scraping motion to clean the molten pool and remove anyentrapped gas.In welding the single-constituent (or a phase) aluminium bronze, i.e.5-7% Al, 93% Cu, the weld metal should be deposited in a single run or atmost two runs to avoid intergranular cracks. Since the metal is hot short inthe range.500-700 C it should cool quickly through the range, and shouldnot be peened. Cold peening is sometimes an advantage. The twoconstituent (a and /?) or duplex aluminium bronzes contain 10% aluminium. They have a wide application, are not as prone to porosity, and areeasier to weld than the 7% Al type, and also their hot short range is smaller.After treatment. Stresses can be relieved by heat treating at low temperature, and any required heat treatment can be carried out as required afterwelding.
Copper weldingTough pitch copper (that containing copper oxide) is difficult toweld, and so much depends on the operator's skill that it is advisable tospecify deoxidized copper for all work in which welding is to be used as themethod of jointing. Welds made on tough pitch copper often crack alongthe edge of the weld if they are bent (Fig. 6.33a), showing that the weld isunsound due to the presence of oxide, often along the lines of fusion. Agood copper weld (Fig. 6.33&), on the other hand, can be bent through 180without cracking and can be hammered and twisted without breaking. Thistype of copper weld is strong and sound, free from corrosion effects, and iseminently satisfactory as a method of jointing.Preparation. The surfaces are thoroughly cleaned and the edges areprepared according to the thickness, as shown in Fig. 6.34. In flanging thinsheet the height of the flange is about twice the plate thickness and theflanges are bent at right angles. Copper has a high coefficient of expansion,and it is necessary therefore to set the plates diverging at the rate of 3-4 mm
Copper welding
299
per 100 mm run, because they come together so much on being welded.Since copper is weak at high temperatures, the weld should be wellsupported if possible and an asbestos sheet between the weld and thebacking strip of steel prevents loss of heat.Tacking to preserve alignment is not advised owing to the weakness ofthe copper tacks when hot. When welding long seams, tapered spacingclamps or jigs should be used to ensure correct spacing of the joint, care
Fig. 6.33. (a) Poor copper weld. Crack developed when bent, (b) Oxy-acetyleneweld in deoxidized copper, x 100.
1ft- :
' V Fig. 6.34. Preparation of copper plates for welding.
1.5 mm MAXGAP HALF SHEET THICKNESS
OVER 1.5 mmGAP'i.'b-'bmm ACCORDING TOPLATE THICKNESS
90DOUBLE V PREPARATIONOF THICKER PLATEGAP 1.5-5 mm ACCORDING TOPLATE THICKNESS
300
being taken that these do not put sufficient pressure on the edges to indentthem when hot. A very satisfactory method of procedure is to place a clampC at the centre of the seam and commence welding at a point say about onethird along the seam.A
DWelding is performed from D to B and then from D to A.Because of the high conductivity of copper it is essential to pre-heat thesurface, so as to avoid the heat being taken from the weld too rapidly. If thesurface is large or the metal thick, two blowpipes must be used, one beingused for pre-heating. When welding pipes they may be flanged or plain buttwelded, while T joints can be made as saddles.Blowpipe,flameand rod. A larger nozzle than for the same thickness of steelshould be used and the flame adjusted to be neutral or very slightlycarbonizing. Too much oxygen will cause the formation of copper oxideand the weld will be brittle. Too much acetylene will cause steam to form,giving a porous weld, therefore close the acetylene valve until the whitefeathery plume has almost disappeared. The welding rod should be of thedeoxidized type, and many alloy rods, containing deoxidizers and otherelements such as silver to increase the fluidity, are now available and giveexcellent results.The weld may be made without flux, or a flux of the borax type used.Proprietary fluxes containing additional chemicals greatly help the weldingoperation and make it easier.Technique. The blowpipe is held at a fairly steep angle, as shown inFig. 6.35, to conserve the heat as much as possible. Great care must betaken to keep the tip of the inner cone 6-9 mm away from the molten metal,since the weld is then in an envelope of reducing gases, which preventoxidation. The weld proceeds in the leftward manner, with a slight sidewaysmotion of the blowpipe. Avoid agitating the molten metal, and do notremove the rod from the flame but keep it in the molten pool. Copper mayFig. 6.35. Copper welding.
Aluminium welding
301
also be welded by the rightward method, which may be used when the fillerrod is not particularly fluid. The technique is similar to that for rightwardwelding of mild steel, with the flame adjusted as for leftward welding ofcopper.Welding can also be performed in the vertical position by either single- ordouble-operator method, the latter giving increased welding speed.After treatment. Light peening, performed while the weld is still hot,increases the strength of the weld. The effect of cold hammering is toconsolidate the metal, but whether or not it should be done depends on thetype of weld and in general is not advised. Annealing, if required on smallarticles, can be carried out by heating to 600-650 C.
Aluminium weldingThe welding of aluminium, either pure or alloyed, presents nodifficulty (Fig. 6.36) provided the operator understands the problemswhich must be overcome and the technique employed.The oxide of aluminium (alumina A12O3), which is always present as asurface film and which is formed when aluminium is heated, has a very highmelting point, much higher than that of aluminium, and if it is not removedit would become distributed throughout the weld, resulting in weaknessand brittleness. A good flux, melting point 570C, is necessary to dissolvethis oxide and to prevent its formation.Fig. 6.36. Oxy-acetylene weld in aluminium, x 45.
302
Oxy-acetylene weldingAluminium and its alloys
Fig. 6.37. {a) Aluminium flat welding. Rightward technique may also beemployed using approximately the same angles of blowpipe and rod. (b)Aluminium welding by the double-operator method.
DIRECTION OFWELDING
303
hotter, the rate of welding increases, and it is usual to reduce the anglebetween blowpipe and weld somewhat to prevent melting a hole in theweld. Learners are afraid of applying sufficient heat to the joint as a rule,because they find it difficult to tell exactly when the metal is molten, since itdoes not change colour and is not very fluid. When they do apply enoughheat, owing to the above difficulty, the blowpipe is played on one spot fortoo long a period and a hole is the result.If the rightward technique is used the blowpipe angle is 45 and the rodangle 30-40. Distortion may be reduced when welding sheets, and theflame anneals the deposited metal.The two-operator vertical method may be employed (as for cast iron) onsheets above 6 mm thickness, the angle of the blowpipes being 50-60 andthe rods 70-80. This method gives a great increase in welding speed(Fig. 6.37)After treatment. All the corrosive flux must be removed first by washingand scrubbing in hot soapy water. This can be followed by dipping thearticle in a 5% nitric acid solution followed by a washing again in hot water.Where it is not possible to get at the parts for scrubbing, such as in tanks,etc., the following method of removal is suitable. Great care, however,should be taken when using the hydrofluoric acid as it is dangerous, andrubber gloves should be worn, together with a face mask.A solution is made up as follows in a heavy duty polythene container.Nitric acid - 100 g to 1 litre water.Hydrofluoric acid - 6 g to 1 litre water.The nitric acid is added to the water first, followed by the hydrofluoricacid.Articles immersed in this solution for about ten minutes will have all theflux removed from them, and will have a uniformly etched surface. Theyshould then be rinsed in cold water followed by a hot rinse, the time of thelatter not exceeding three minutes, otherwise staining may occur.Hammering of the completed weld greatly improves and consolidates thestructure of the weld metal, and increases its strength, since the depositedmetal is originally in the 'as cast' condition and is coarse grained and weak.Annealing may also be performed if required.
304
Alloys
Composition %(remainder aluminium)
Casting alloysBS 1490LM2LM4
LM5LM6LM9
3-6 Mg10-13 Si, 0.5 Mn10-13 Si, 0.3-0.7 Mn
LM18LM20Wrought alloysBS 1470-14771080A1050A3103 (N3)6063 (H9)
4.5-6 Si10-13 Si, 0.4 Cu
061 (H20)6082 (H30)
99.8 Al99.5 Al1-1.5 Mn0.4^-0.9 Mg, 0.3-0.7 Mn0.15 C0.4 Cu, 0.8-1.2 Mg,0.4^0.8 Si, 0.2-0.8 Mn,0.15-0.35 Cr0.5-1.2 Mg, 0.7-1.3 Si,0.4-1.0 Mn
1080A(GlB)1080A(GlC)3103 (NG3)4043 or 5056A(NG21 orNG6)4043 or5056A(NG21 orNG6)4043 or 5056A(NG21 orNG6)
305
Blowpipe, flame, rod and flux. The blowpipe is adjusted as for purealuminium and a similar flame used. The welding rod should preferably beof the same composition as the alloy being welded (see table on p. 290) butfor general use a 5% silicon-aluminium rod is very satisfactory. This type ofrod has strength, ductility, low shrinkage, and is reasonably fluid. A 10%silicon-aluminium rod is used for high silicon castings, while 5%copper-aluminium rods are used for the alloys containing copper, such asY alloy, and are very useful in automobile and aircraft industries. Thedeposit from this type of rod is harder than from the other types.When welding the Al-Mg alloys the oxide film consists of bothaluminium and magnesium oxide making the fluxing more difficult so thatas the magnesium proportion increases welding may become more difficult.Alloys containing more than 2{% Mg, e.g. 5154A (N5) and 5183 (N8) aredifficult to weld and require considerable experience as do the high strengthalloys 6061 (H15) and 6082 (H30). The inert gas arc processes are to bepreferred for welding these alloys.Since there is also a loss of Mg in the welding process note that the fillerrod recommended has a greater Mg content than the parent plate. The fluxused is similar to that for pure aluminium and its removal must be carriedout in the same way.Technique. The welding is carried out as for aluminium sheet, and thecooling of the casting after welding must be gradual.*After-treatment. After welding, the metal is in the' as cast' condition and isweaker than the surrounding areas of parent metal, and the structure of thedeposited metal may be improved by hammering. The area near the weldedzone, however, is annealed during the welding process and failure thusoften tends to occur in the area alongside the weld, and not in the welditself. In the case of heat-treatable alloys, the welded zone can be given backmuch of its strength by first lightly hammering the weld itself and thenheat-treating the whole of the work.For this to be quite successful it is essential that the weld should be of thesame composition as the parent metal. If oxidation has occurred, however,this will result in a weld metal whose structure will differ from that of theparent metal and the weld will not respond to heat treatment. Since manyof this type of alloy are ' hot short', cracking may occur as a result of thewelding process.* When repairing cracked castings, any impurities which appear in the molten pool should befloated to the top, using excess flux if necessary.
306
If sheets are anodized, the welding disturbs the area and changes itsappearance. Avoidance of overheating, localizing the heat as much aspossible, and hammering, will reduce this disturbance to a minimum, butheat treatment will make the weld most inconspicuous.
45#
CORNER WELDLESS THAN 1 mm
AFTER WELDING
AFTER HAMMERING
90N
CORNER WELDABOVE 1mm
307
optional and special fluxes are available for the other alloys. Fluxcontaining boron should not be used with alloys containing chromium as ittends to cause hot cracking in the weld. The joint is tacked in positionwithout flux. The flux is made into a thin paste and painted onto both sidesof the joint and the filler rod and allowed to dry before welding. Fusedflux remaining should be removed by wire brushing and unfused flux withhot water. Flux remaining (after welding the nickel chromium alloys) canbe removed by treatment with a solution of equal parts of nitric acid andwater for 15-30 minutes followed by washing with water. Flux removal isimportant when high-temperature applications are involved, as the fluxmay react with the metal.Technique. Leftward technique is used. Weaving and puddling of themolten pool should be avoided as agitation of the pool causes porosity dueto the absorption of gases by the high-nickel alloys, and the filler rod shouldbe kept within the protective envelope of the flame to prevent oxidation.Keep the flame tip above the pool but for MONEL alloy K500 let it justtouch the pool. Nickel 200 melts sluggishly. INCONEL alloy 600,NIMONIC alloy 75 and the BRIGHTRAY alloys are more fluid whileMONEL alloy 400 and INCOLOY DS alloy flow easily. A slightlycarburizing soft flame (excess acetylene) should be used for the nickel andnickel-copper alloys, whilst for the chromium-containing alloys the flameshould be a little more carburizing.There are no pronounced ripples on the weld surface. They should besmooth without roughness, burning or signs or porosity.Examples of filler metalsMaterialNickel alloys 200, 201MONEL alloys 400, R405, K500INCONEL alloy 600INCONEL alloys 600, 601INCOLOY alloys 800, 800HTINCO alloy 330INCOLOY DS
When welding tube with 80 feather edge preparation and no root gap, thefirst run is made with no filler rod, the edges being well fused together togive an even penetration bead, followed by filler runs. If the work isrotatable, welding in the two o'clock position gives good metal control. Ifthe joint is fixed, vertical runs should be made first downwards followed bya run upwards.
308
NICKELREMOVED
NICKEL WELD
STEEL WELD
309
310
steels and those with a very low carbon content require no heat treatmentafter welding.The original silver-like surface can be restored to stainless steels whichhave scaled or oxidized due to heat by immersing in a bath made up asfollows: sulphuric acid 8%, hydrochloric acid 6%, nitric acid 1%, water85%. The temperature should be 65C and the steel should be left in for 10to 15 minutes, and then immersed for 15 minutes or until clean in a bath of10% nitric acid, 90% water, at 25 C.Other baths made up with special proprietary chemicals with tradenames will give a brighter surface. These chemicals are obtainable from themakers of the steel.Stainless ironThe welding of stainless iron results in a brittle region adjacent tothe weld. This brittleness cannot be completely removed by heat treatment,and thus the welding of stainless iron cannot be regarded as completelysatisfactory. When, however, it has to be welded the welding should bedone as for stainless steel, using a rod specially produced for this type ofiron.
311
. INNER CONE
312
made between deposit and parent metal with the minimum amount ofalloying taking place.This type of deposit, used for its wear-resisting properties, is usually verytough and is practically unmachinable. The surface is therefore usuallyground to shape, but in many applications, such as in reinforcing tramwayand rail crossings, it is convenient and suitable to hammer the deposit toshape while hot, and thus the deposit requires a minimum amount ofgrinding. The hammering, in addition, improves the structure.In the case of the high-carbon deposits, they can be machined or groundto shape and afterwards heat treated to the requisite degree of hardness.When using tungsten carbide rods the cone of the flame should be playedon the rod and pool to allow gases to escape, preventing porosity. Weavingis necessary to give an even distribution of carbide granules in the matrix.Second runs should be applied with the same technique as the first, with nopuddling of the first run since this would give dilution of the hard surfacewith the parent plate.Another method frequently used to build up a hard surface is to deposit asurface of cast iron in the normal way, using a silicon cast iron rod and flux.Immediately the required depth of deposit has been built up, the part isquenched in oil or water depending on the hardness required.This results in a hard deposit of white cast iron which can be ground toshape, and which possesses excellent wear-resisting properties. Thismethod is suitable only for parts of relatively simple shape, that will notdistort on quenching, such as camshafts, shackle pins, pump parts, etc.The use of carbon and copper fences in building up and resurfacingresults in the deposit being built much nearer to the required shape,reducing time in welding and finishing and also saving material.When hard surfacing cast iron, the surface will not sweat. In this case thedeposit is first laid as a fusion deposit, with a neutral flame, and a secondlayer is then 'sweated' on to this first layer. In this way the second layer isobtained practically free from any contamination of the base metal.It will be seen, therefore, that the actual composition of the deposit willdepend entirely upon the conditions under which it is required to operate.A table of alloy steel rods and uses is given at the end of this chapter.StelliteStellite alloys of the cobalt-chrome type with carbon were firstdeveloped in 1900 in the US and were the first wear-resistant cobalt-basedalloys to be used. Later tungsten and/or molybdenum were added. They arehard and have a great resistance to wear and corrosion and there are now
313
314
much acetylene will cause carbon to be deposited around the molten metal.The tip should be one size larger than that for the same thickness steel plate,but the pressure should be reduced, giving a softer flame. For small parts5 mm diameter Stellite rods can be used, while thicker rods are used forlarger surfaces. Too much heat prevents a sound deposit being obtained,because some of the base metal may melt and mix with the molten stellite,thus modifying its structure.Technique. The flame is directed on to the part to be surfaced, but the innercone should not touch the work, both blowpipe and rod making an angle of45-60 with the plate (Fig. 6.406 and c). When the steel begins to sweat theStelliting rod is brought into the flame and a drop of Stellite melted on to thesweating surface of the base metal, and it will spread evenly and make anexcellent bond with the base metal. The surfacing is continued in this way.After treatment. The part should be allowed to cool out very slowly toprevent cracks developing.
DIRECTIONOF TRAVEL
EXCESS ACETYLENEFEATHEROUTER ENVELOPE
315
(by(d) Air-hardening steel (not stainless). When a large area of deposit isrequired these steels should be avoided. Otherwise pre-heat to600-650 C and deposit hard surface whilst at this heat. Then placein a furnace at 650 C for 30 minutes and cool large components inthe furnace and small ones as (b).(e) 18/8 austenitic stainless steel non-hardening welding type. Preheat to 600-650C. Hard surface whilst at this temperature. Bringto an even temperature and cool out as (b).(f) 12-14% manganese austentic steel. Use arc process.
316
317
Brazing
NOTE:POWDER CONTAINER MUST BE INVERTICAL POSITION WHEN OPERATING
VMULTI-JET NOZZLE
318
Surface tensionIf drops of mercury rest on a level plate it will be noticed that thesmaller the drop the more nearly spherical it is in shape, and if any drop isdeformed it always returns to its original shape. If the only force acting onany drop were that due to its own weight, the mercury would spread outover the plate to bring its centre of gravity (the point at which the wholeweight of the drop may be conceived to be concentrated) to the lowest pointso that to keep the shape of the drop other forces must be present. As thedrop gets smaller the force due to its own weight decreases and these otherforces act so as to make the drop more spherical, that is to take up a shapewhich has the smallest surface area for a given volume. Other examples ofthese forces, termed surface tension, are the floating of a dry needle on thesurface of water, soap bubbles and water dripping from a tap. In the firstexample the small dry needle must be laid carefully horizontally on thesurface. If it is pushed slightly below the surface it will sink because of itsgreater density. Evidently the surface of the water exhibits a force (surfacetension) which will sustain the weight of the needle. If a wire frameworkA BCD, with CD, length x, able to slide along Z?C and AD, holds a soap film,the film tends to contract, and to prevent this a force F must be applied atright angles to CD (Fig. 6.42). The surface tension is defined as the force perunit length 5 o n a line drawn in the film surface, and since there are twosurfaces to the film F= 2Sx.Angle of contact (0). The angle of contact between a liquid and a solid maybe defined as the angle between the tangent to the liquid surface at the pointof contact and the solid surface. For mercury on glass the contact angle isabout 140, while for other liquids the angle is acute and may approachzero (Fig. 6.43).
Fig. 6.42D
Fig. 6.43
CONTACT ANGLE(NON-WETTING AND WETTING)
319
Wetting. If the contact angle approaches zero the liquid spreads and wetsthe surface and may do so in an upward direction. If the solid and liquid aresuch that the forces of attraction experienced by the molecules towards theinterior of the liquid are less than the forces of attraction towards the solid,the area of contact will increase and the liquid spreads.Capillarity. If a narrow bore (capillary) tube with open ends is placedvertically in a liquid which will wet the surface of the tube, the liquid rises inthe tube and the narrower the bore of the tube the greater the rise. The wallthickness of the tube does not affect the rise and a similar rise takes place ifthe tube is replaced by two plates mounted vertically and held closetogether. If the tube or the plates are held out of the vertical the effect issimilar and the vertical rise the same. If the liquid does not wet the tube (e.g.mercury) a depression occurs, and the shape of the liquid surface (themeniscus) is shown. The rise is due to the spreading or wetting actionalready considered - the liquid rises until the vertical upward force due tosurface tension acting all round the contact surface with the tube is equal tothe vertical downward force due to the weight of the column of liquid(Fig. 6.44).This wetting action and capillary attraction are involved in the brazingprocess. The flux, which melts at a lower temperature than the brazingalloys, wets the surface to be brazed, removes the oxide film and gives cleansurfaces which promote wetting by a reduction of the contact anglebetween the molten filler alloy and the parent plate at the joint. The moltenfiller alloy flows into the narrow space or joint between the surfaces bycapillary attraction and the narrower the joint the further will be thecapillary flow. Similarly solder flows into the narrow space between tubeand union when 'capillary fittings' are used in copper pipe work.Brazing can be performed on many metals including copper, steel andaluminium, and in all cases cleanliness and freedom from grease is essential.The filler alloy used for aluminium brazing has already been mentioned inthe section on oxy-acetylene welding. In the case of the nickel alloys, timeand temperature are important. For example copper alloys mix readilywith nickel alloy 200 or MONEL alloy 400 and can pick up sufficientFig. 6.44
CAPILLARY ELEVATION
CAPILLARY DEPRESSION
320
nickel to raise the melting point and hinder the flow of the filler metal.Also chromium and aluminium form refractory oxides which makebrazing difficult, so that the use of a flux is necessary. A wide range ofbrazing alloys are available having a variety of melting points. Fig. 6.45shows a modern brazing torch using LPG. See appendix for table ofgeneral purpose silver brazing alloys and fluxes.Aluminium brazingThe fusion welding of fillet and lap joints in thin aluminiumsections presents considerable difficulty owing to the way in which theedges melt back. In addition the corrosive fluoride flux is very liable to beentrapped between contracting metal surfaces so it is advantageous tomodify the design wherever possible so as to include butt joints instead offillet and lap.In many cases, however, corner joints are unavoidable and in these casesflame brazing overcomes the difficulty. It can be done more quickly andcheaply than fusion welding, less skill is required and the finished joint isneat and strong.Fig. 6.45. LP gas brazing torch for brazing, hard and soft soldering. Propanegas recommended, cylinder pressure 7-8 bar. Standard torch pressure 4 bar.Use smaller nozzles for smaller flames. Temperatures up to 950C, piezoelectric ignition.
321
Aluminium brazing is suitable for pure aluminium and for alloys such asLM4, LM18 and for the aluminium-manganese and aluminiummanganese-magnesium alloys, as long as the magnesium content is notgreater than 2%.Preparation. It is always advisable to allow clearance at the joints since theweld metal is less fluid as it diffuses between adjacent surfaces. Clearancejoints enable full penetration of both flux and filler rod to be obtained.Surface oxide should be removed by wire brush or file and greaseimpurities by cleaning or degreasing. Burrs such as result from sawing orshearing and other irregularities should be removed so that the filler metalwill run easily across the surface. Socket joints should have a 45 belling orchamfer at the mouth to allow a lead in for the flux and metal, and toprevent possibility of cracking on cooling, the sections of the surfaces to bejointed should be reduced to approximately the same thickness wherepossible.Blowpipe, flame, flux and rod. The blowpipe and rod are held at the normalangle for leftward welding, and a nozzle giving a consumption of about700 litres of both oxygen and acetylene each per hour is used. The flame isadjusted to the excess acetylene condition with the white acetylene plumeapproximately \\ to 2 times the length of the inner blue cone. The rod canbe of 10-13% silicon-aluminium alloy melting in the range 565-595 C(compared with 659 C for pure aluminium). This is suitable for weldingand brazing the high silicon aluminium alloys and for general aluminiumbrazing. Another type of rod containing 10-13% Si and 2-5% Cu is alsoused for pure aluminium and aluminium alloys except those with 5%silicon, or with more than 2% magnesium, but is not so suitable due to itscopper content if corrosive conditions are to be encountered, but it has theadvantage of being heat-treatable after brazing, giving greater mechanicalstrength.BS 1845, Filler metals for brazingMajor alloying elements only
\/o)
Melting range ( C)
Type
Silicon
Copper
Iron
Aluminium
Solidus
Liquidus
AL1AL2AL3AL4
10-1310-13
2-5
0.60.6
Rem.Rem.Rem.Rem.
535565565565
595595610630
7-8
45-6.0
0-0.10-0.10-0.1
322
MOVEMENTOF BLOWPIPE
ROD APPLIED
HERE
General precautions
323
General precautionsThe following general precautions should be taken in welding:(1) Always use goggles of proved design when welding or cutting. Theintense light of the flame is harmful to the eyes and in additionsmall particles of metal are continually flying about and may causeserious damage if they lodge in the eyes. Welding filters or glassesare graded according to BS 679 by numbers followed by the lettersGW or GWF. The former are for welding operations without aflux and the latter with flux because there is an additional amountTable giving some of the chief types of oxy-acetylene welding rods availablefor welding carbon and alloy steels.Rod
Low-carbon steel
High-tensile steel
High-carbon steel
High-nickel steelWear-resistingsteel (12-14%manganese)StelliteChromemolybdenum steel(creep resisting)Chrome-vanadiumsteelTool steelStainless steel
324
of glare. The grades range from 3/GW and 3/GWF to 6/GW and6/GWF, the lightest shade having the lowest grade number. Foraluminium welding and light oxy-acetylene cutting, 3/GW or3/GWF is recommended, and for general welding of steel andheavier welding in copper, nickel and bronze, 5/GW or 5/GWF isrecommended. A full list of recommendations is given in the BS.(2) When welding galvanized articles the operator should be in a wellventilated position and if welding is to be performed for any lengthof time a respirator should be used. (In cases of sickness caused byzinc fumes, as in welding galvanized articles or brass, milk shouldbe drunk.)(3) In heavy duty welding or cutting and in overhead welding,asbestos or leather gauntlet gloves, ankle and feet spats andprotective clothing should be worn to prevent burns. Whenworking inside closed vessels such as boilers or tanks, take everyprecaution to ensure a good supply of fresh air.(4) In welding or cutting tanks which have contained inflammableliquids or gases, precautions must be taken to prevent danger ofexplosion. One method for tanks which have contained volatileliquids and gases is to pass steam through the tank for some hoursaccording to its size. Any liquid remaining will be vaporized by theheat of the steam and the vapours removed by displacement.Tanks should never be merely swilled out with water and then welded;many fatal explosions have occurred as a result of this method ofpreparation. Carbon dioxide in the compressed form can be used todisplace the vapours and thus fill the tank, and is quite satisfactory but isnot alwayS available. Tanks which have contained heavier types of oil, suchas fuel oil, tar, etc., present a more difficult problem since air and steam willnot vaporize them. One method is to fill the tank with water, letting thewater overflow for some time. The tank should then be closed and turneduntil the fracture is on top. The water level should be adjusted (by letting alittle water out if necessary) until it is just below the fracture. Welding canthen be done without fear as long as the level of the water does not dropmuch more than a fraction of an inch below the level of the fracture.The welder should study the Department of Employment memorandumon Safety measures for the use of oxy-acetylene equipment in factories (Form1704). Toxic gases and fine airborne particles can provide a hazard to awelder's health. The Threshold Limit Value (TLV) is a system by whichconcentrations of these are classified, and is explained in the Department ofEmployment Technical data notes No. 2, Threshold limit values.
325
7Cutting processes
326
327
In the high pressure pipe, fuel gas and heating oxygen are mixed in thehead (Fig. 7.2), and emerge from annular slots for propane or holes foracetylene (Fig. 7.4).The cutting oxygen is controlled by a spring loaded lever, pressure onwhich releases the stream of cutting oxygen which emerges from the central
CUTTINGOXYGENLJt-A-r.K.r*HEATINGOXYGENMIXERIN HEAD\
CUTTING OXYGENCONTROL LEVER///
OXYGEN
tu
tf
FUEL GASKey:1. Nozzle nut.2. Head 90.Head 75.Head 180.3. Screw.4. Bracket latch.5. Handle.6. Nozzle nut.7. Injector cap.8. Injector assembly.9. Tube.9a. Tube.
10.11.12.13.14.15.16.17.18.19.20.11.
D.GAS
FUEi
Push rod.Lock nut.Pivot pin.Control valve fuel gas.Red cap.Spring clip.Filter.Control valve oxygen.Rear cap.Cap washer.Valve spring disc.Rear valve.
22.23.24.25.26.27.28.29.30.31.
Plunger.0 ring.Lever pin.Lever.Button.Grub screw.Lever latch.Spring washer.Forward tube.Tube support.Nut.
328
Cutting processes
U SLOTS
PREHEATING FLAMECUTTING STREAM
329
heavy continuous cutting and the volume of oxygen used is much greaterthan of fuel gas (measured in litres per hour, 1/h).Fig. 7.3 shows a stepped nozzle used for cutting steel sheet up to 4 mmthick and this type is also available with head mixing.The size of torch varies with the thickness of work it is required to cut andwhether it is for light duty, or heavy, continuous cutting.Adjustment of flame
Oxy-hydrogen and Oxy-propane. The correctly adjusted preheating flame is a small non-luminous central cone with a pale blueenvelope.Oxy-natural gas. This is adjusted until the luminous inner cone assumes aclear, definite shape, that may be up to 8-10 mm in length for heavy cuts.Oxy-acetylene. This flame is adjusted until there is a circular short blueluminous cone, if the nozzle is of the concentric ring type, or until there is aseries of short, blue, luminous cones (similar to the neutral welding flame),if it is of the multi-hole type (Fig. 1.5a and b). The effect of too much oxygenis indicated in Fig. 7.5c.
Fig. 7.4
ACETYLENE(b)
Fig. 7.5
(MfllCONCEHTRICTYPE
MULTI-HOLETYPE
TOO MUCHOXYGEN(C)
330
It may be observed that when the cutting valve is released the flame mayshow a white feather, denoting excess acetylene. This is due to the slightlydecreased pressure of the oxygen to the heating jet when the cutting oxygenis released. The flame should be adjusted in this case so that it is neutralwhen the cutting oxygen is released.Care should be taken to see that the cutter nozzle is the correct size forthe thickness to be cut and that the oxygen pressure is correct (the nozzlesizes and oxygen pressures vary according to the type of blowpipe used).The nozzle should be cleaned regularly, since it becomes clogged withmetallic particles during use. In the case of the concentric type of burner,the outer ring should be of even width all round, otherwise it will producean irregular-shaped inner cone, detrimental to good cutting (Fig. 7.6).Technique of cuttingThe surface of the metal to be cut should be free of grease and oil,and the heating flame held above the edge of the metal to be cut, farthestfrom the operator, with the nozzle at right angles to the plate. The distanceof the nozzle from the plate depends on the thickness of the metal to be cut,varying from 3 to 5 mm for metal up to 50 mm thick, up to 6 mm for metal50 to 150 mm thick. Since the oxide must be removed quickly to ensure agood, clean cut, it is always preferable to begin on the edge of the metal.The metal is brought to white heat and then the cutting valve is released,and the cut is then proceeded with at a steady rate. If the cutter is movedalong too quickly, the edge loses its heat and the cut is halted. In this case,the cutter should be returned to the edge of the cut, the heating flameapplied and the cut restarted in the usual manner. Round bars are bestnicked with a chisel, as this makes the starting of the cut much easier. Rivetheads can be cut off flush by the use of a special type nozzle while ifgalvanized plates are to be cut for any length of time, a respirator isadvisable, owing to the poisonous nature of the fumes.
Fig. 7.6
331
To cut a girder, for example, the cut may be commenced at A and takento B (Fig. 7.7). Then commenced at C and taken to B, that is, the flange iscut first. Then the bottom flange is cut in a similar manner. The cut is thencommenced at B and taken to E along the web, this completing theoperation. By cutting the flanges first the strength of the girder is altered butlittle until the web itself is finally cut.Rollers and point guides can be affixed to the cutter in order to ensure asteady rate of travel and to enable the operator to execute straight lines orcircles, etc., with greater ease (Fig. 1.8a).The position of the flame and the shape of the cut are illustrated inFig. 7.86.To close down, first shut off the cutting stream, then the propane oracetylene and then the oxygen valve. Close the cylinder valves and releasethe pressure in the tubes by momentarily opening the cutter valves.To cut holes in plates a slightly higher oxygen pressure may be used. Thespot where the hole is required is heated as usual and the cutting valveFig. 7.7CUT 1
CUT 2
CUT 5
CUT 3
Fig. 7.8
IRON OXIDE
J|i|
BEING BLOWfTAFROM THE CUT | , V
332
released gently, at the same time withdrawing the cutter from the plate. Theextra oxygen pressure assists in blowing away the oxide, and withdrawingthe nozzle from the plate helps to prevent oxide from being blown on to thenozzle and clogging it. The cutting valve is then closed and the lowersurface now exposed is heated again, and this is then blown away, theseoperations continuing until the hole is blown through. The edges of the holeare easily trimmed up afterwards with the cutter.When propane or natural gas is used instead of acetylene, the flametemperature is lower; consequently it takes longer to raise the metal toignition point and to start the cut, and it is not suitable for hand cuttingover 100 mm thick nor for cast iron cutting. Because of this lowertemperature, the speed of cutting is also slower. The advantages, however,are in its ease of adjustment and control; it is cheap to instal and operateand, most important of all, since the metal is not raised to such a hightemperature as with the oxy-acetylene flame, the rate of cooling of themetal is slower and hence the edges of the cut are not so hard. This isespecially so in the case of low-carbon and alloy steels. For this reason, oxypropane or natural gas is often used in works where cutting machines areoperated (see later).The oxy-hydrogen flame can also be used (the hydrogen being suppliedin cylinders, as the oxygen). It is similar in operation to oxy-propane andhas about the same flame temperature. It is advantageous where cutting hasto be done in confined spaces when the ventilation is bad, since the productsof combustion are not so harmful as in the case of oxy-acetylene and oxypropane, but is not so convenient and quick to operate.The effect of gas cutting on steelIt would be expected that the cut edge would present greathardness, owing to its being raised to a high temperature and thensubjected to rapid cooling, due to the rapid rate at which heat is dissipatedfrom the cut edges. Many factors, however, influence the hardness of theedge.Steels of below 0.3% carbon can be easily cut, but the cut edges willdefinitely harden, although the hardness rarely extends more than 3 mminwards and the increase is only 30 to 50 points Brinell.Steels of 0.3% carbon and above and also alloy steels are best preheatedbefore cutting, as this reduces the liability to crack.Nickel, molybdenum, manganese and chrome steels (below 5%) can becut in this way. Steels having a high tungsten, cobalt or chrome content,however, cannot be cut satisfactorily. Manganese steel, which is machined
333
with difficulty owing to the work hardening, can be cut without any badeffects at all.The oxy-acetylene flame produces greater hardening effect than the oxypropane flame, as before mentioned, owing to its higher temperature.Excessive cutting speeds also cause increased hardness, since the heat isthereby confined to a narrower zone near the cut and cooling is thus morerapid. Similarly, a thick plate will harden more than a thin one, owing to itsmore rapid rate of cooling from the increased mass of metal being capableof absorbing the heat more quickly. The hardening effect for low carbonsteels, however, can be removed either by preheating or heat treatmentafter the cut. The hardening effect in mild steel is very small. On thicknessesof plate over 12 mm it is advisable to grind off the top edge of the cut, as thistends to be very hard and becomes liable to crack on bending.The structure of the edges of the cut and the nearby areas will naturallydepend on the rate of cooling. Should the cutting speed be high and thecooling be very rapid in carbon steels, a hard martensitic zone may occur,while with a slower rate of cutting and reduced rate of cooling the structurewill be softer. A band of pearlite is usually found, however, very near to thecut edges and because of this, the hardness zone, containing increasedcarbon, is naturally very narrow. When the cut edge is welded on directly,without preparation, all this concentration of carbon is removed.Thus, we may say that, for steels of less than 0.3% carbon, if the edges ofthe cut are smooth and free from slag and loose oxide, the weld can be madedirectly on to the gas-cut edge without preparation.
334
Fig. 7.9. (a) Cutting machine fitted with four cutting heads.TO OXYGEN ANDACETYLENE SUPPLYTRACING HEAD
335
Stack cuttingThin plates which are required in quantities can be cut by clampingthem tightly in the form of a stack and, due to the accuracy of the modernmachines, this gives excellent results and the edges are left smooth andeven. Best results are obtained with a stack 75-100 mm thick, while Gclamps can be used for the simpler types of stack cutting.Cast iron cuttingCast iron cutting is made difficult by the fact that the graphite andsilicon present are not easily oxidized. Reasonably clean cuts can now bemade, however, using a blowpipe capable of working at high pressure ofoxygen and acetylene. Cast iron cannot be cut with hydrogen.Since great heat is evolved in the cutting process, it is advisable to wearprotective clothing, face mask and gloves.The oxygen pressure varies from 7 N/mm 2 for 35 mm thick cast iron to11 N/mm 2 for 350 to 400 mm thick, while the acetylene pressure isincreased accordingly.The flame is adjusted to have a large excess of acetylene, the length of thewhite plume being from 50-100 mm long (e.g. 75 mm long for 35-50 mmthick plate). The speed of cutting is low, being about 2.5 m per hour for75-125 mm thick metal.Fig. 7.9. (b)
336
Technique. The nozzle is held at 45 to the plate with inner cone 5-6 mmfrom the plate, and the edge where the cut is to be started is heated to redheat over an area about 12-18 mm diameter. The oxygen is then releasedand this area burnt out. The blowpipe is given a zig-zag movement, and thecut must not be too narrow or the slag and metal removed will clog the cut.About 12 to 18 mm is the normal width. After the cut is commenced theblowpipe may be raised to an angle of 70-80, which will produce a lag inthe cut, as shown in Fig. 7.10.Owing to the fact that high pressures are used in order to supply sufficientheat for oxidation, large volumes of gas are required, and this is oftenobtained by connecting several bottles together.
Fig. 7.10
337
OperationThere are two main techniques:(1) progressive,(2) spot.In the former the groove is cut continuously along the plate - it may bestarted at the plate edge or anywhere in the plate area. It can be used forremoving the underbeads of welds prior to depositing a sealing run, or itmay be used for preparing the edges of plates. Spot gouging, however, isused for removing small localized areas such as defective spots in welds.To start the groove at the edge of a plate for continuous or progressivegouging the nozzle is held at an angle of about 20 so that the pre-heatingflames are just on the plate and when this area gets red hot the cuttingoxygen stream is released and at the same time the nozzle is brought at ashallower angle to the plate as shown, depending upon depth of gougerequired. The nozzle is held so that the nozzle end clears the bottom of thecut and the pre-heating flames are about 1.5 mm above the plate.The same method is adopted for a groove that does not start at the plateedge. The starting point is pre-heated with the nozzle making a fairly steepangle with the plate at 20-40. When the pre-heated spot is red hot thecutting oxygen stream is released and the angle of the nozzle reduced to5-10 depending upon the depth of gouge required (Fig. 7.12).To gouge a single spot, it is pre-heated as usual where required, but whenred hot and the cutting stream of oxygen is turned on, the angle of thenozzle is increased (instead of, as previously, decreased) so as to make thegouge deep.The depth of groove cut depends upon nozzle size, speed of progress andangle between nozzle and plate (i.e. angle at which the cutting stream ofoxygen hits the plate). The sharper this angle, the deeper the groove. If theFig. 7.11. Flame gouging nozzle.
338
cutting oxygen pressure is too low ripples are left on the base of the groove.If the pressure is too high the cut at the surface proceeds too far in advanceof the molten pool, and eventually the cut is lost and must be restarted.Use of flame gougingCertain specifications, such as those for fabrication of butt weldedtanks, etc., stipulate that the underbead (or back bead) should be removedand a sealing run laid in place. This can easily and efficiently be done byflame gouging, as also can the removal of weld defects, tack welds, lugs,cleats, and also the removal of local areas of cracking in armour plate, andflashing left after upset welding (Fig. 7.13).
PREHEAT
DEPTHS OF GOUGING
CONTINUANCE OF GROOVEMETHOD OF GOUGING
SEALINGRUN LAID/N
WELD:GOUGED SEALINGSINGLERUN LAIDINU PREPARATION
339
consumed in the process. The oxygen pressure varies with the thickness ofsteel and with the size of electrode being used, about 4 bar (60 lb per in 2 ) formild and low alloy steel plate of 8 to 10 mm thick and about 4.5-5.5 bar(70-80 lb per in.2) for 23 to 25 mm thick. In addition to mild and low-alloysteel, and stainless steel copper, bronze, brass, monel and cupro-nickels canbe roughly cut by this process.
340
Plasma cutting(see also pp. 190-3, Ions and plasma, and Appendix 14 on lasers)This process gives clean cuts at fast cutting speeds in aluminium,mild steel and stainless steel. All electrically conducting materials can becut using this process, including the rare earth metals and tungsten andtitanium and it has superseded powder cutting.The arc is struck between the electrode and the conducting body of thetorch. A gas mixture or air passes under pressure through the restrictednozzle orifice and around the arc, emerging as a high-temperature (up to25000 C) ionized plasma stream, and the arc is transferred from thenozzle and passes between the electrode and work (Fig. 7.14).Great improvements have been made in plasma cutting torches bygreatly constricting the nozzle and thus narrowing the plasma stream,giving a narrower and cleaner cut with less consumption of power. Incertain cases 'double arcing' may occur, in which the main arc jumps fromtungsten electrode to nozzle and then to work, damaging both nozzle andelectrode.
Plasma cutting
341
Power unitA 24 kVA fan cooled unit has input voltages of 220, 380-415, and500 and cutting currents ranging from 50 A minimum to 240 A maximumat 100% duty cycle and OCV of 200 V d.c. with heavy duty rectifiers formain and pilot arc control. An automatic pilot arc switch cuts off when thecutting arc is transferred. This size of unit enables metal of up to 40 mmthickness to be cut and edges prepared quickly and cleanly in stainlesssteel, alloy steels, aluminium and copper (Fig. 7.15).A 75 kVA unit of similar input voltage has cutting currents of 50-250 Awith OCV of 300 V and cutting voltage of 170 V enabling thicknesses of 2.7to 50 mm upwards, in the previously mentioned materials, to be cut andedges prepared at high speed. The cutting head of either unit can be fittedto a carriage to obtain high speeds of cut with greater precision than withmanual cutting.The gases used are argon, hydrogen, nitrogen, and it should be notedthat since high voltages of up to 300 V on open circuit and about 170 Vduring the cutting process, are encountered, great care should be taken tofollow all safety precautions and avoid contact with live parts of the torchwhen the unit is switched on. All work to be done on the torch headshould be with the power supply switched off.Argon-hydrogen and argon-nitrogen are used for cutting. Anycombination of the gases can be selected at will to suit the material andthickness and the actual ratio of the gases will depend upon the operator.The tungsten electrode may be of 1.6 or 2.0 mm diameter and gives a cutof width about 2.5-3.5 mm with a torch-to-work distance of about 10 mmwhen cutting with about 250 A (the work is +ve).Since hydrogen is an explosive gas and nitrogen combines with oxygenof the atmosphere to form the oxides of nitrogen (NO, N 2 O, and N2O4)in the heat of the arc, cutting should be done in a well-ventilated shop (notenclosed in any way) and protective clothing and the correct eye lensprotection always worn, with earmuffs for longer periods.Operation. The unit is switched 'on', current is selected on the potentiometer knob and checked on the ammeter, gases are adjusted for mixtureand the torch switch pressed. The pilot arc gas flows and the pilot arc isignited. The torch is now brought down to about 10 mm from the work(take care not to touch down) and, making sure that all protective clothingincluding head mask is in order, the torch switch is released and the mainarc is transferred to the work. If this does not occur a safety cut-off circuitensures that the pilot arc current circuit is de-energized after a few seconds.
342
The arc commences with slow start current and when the thickness ofwork is pierced, the torch is moved along the plate and if cutting currentand speed of travel are correct a steady stream of molten metal flows fromthe underside of the cut giving a smoothly cut surface. Average currents arein the region of 250 A.The arc is extinguished automatically at the end of the cut or the torchcan be pulled away from the work.Torch (Fig. 7.14). These can be either hand or machine operated and aresupplied with spare electrodes, cutting tips and heat shields. If watercooled torches of either air or mixed gas are used electrolytic action occursin the waterways of the torch, due to dissolved minerals in the water.Corrosion occurs and the torch is severely damaged. To prevent this,de-ionized water (about 2 litres per minute) can be used (see p. 346).
Key:1.2.3.4.5.6.7.8.9.
Heat shield.Cutting tip.Tungsten electrode 3.2 mm diameter.Torch body.0 ringTorch head cover.Torch cap.Collet.Cover retaining nuts and screw.
10.11.12.13.14.15.16.17.18.
Screw.Torch switch.Handle.Switch boot.Sheath.Main arc cable.Gas hose.Pilot arc cable.Control cable with plug.
343
Fig. 7.15. (a) Control panel for power unit for air (gas) plasma cutting.
MUREXSabre-arc 100
fo
Models available:Sabre-arcModel
Input V
40i
OCVoutput
Cuttingcurrent
Thicknessrangemild steel
380/415200 d.c.1(2) phase
10-40 A
220/380/415
370 d.c.
Rating
Plasmacuttinggas
Coolinggas
0.5-15 mm 40 Aat 60%
1-25 mm
100 Aat 100%
Air orN 2 orArH 2
Air orN 2 orCO 2 or O
25-150 A
1-37 mm
150 Aat 75%
Air orN 2 orCO 2 or O 2
Inverterweight21 kg
Fig. 7.15. (b) Sabre-arc unit (left); W T C (Wigan Torch Co.) unit 100-150 A(right).
344
345
Fig. 7.16
KJ;GUARD
SHROUD
TIP CUTTING +0.067-100^0.057- 80 ATHICKNESS 0.052 - 60 A0.106- 100 A0.089 - 70 A
ICURRE NT[
""* NOZZLE^ELECTRODE"AIR TUBES
INSULATOR '(c) Method ofobtaining narrowwidth of cut
ELECTR0DE
AIR TUBEAIR FLOW
VE
(CATHODE)HAFNIUM INSERT -j-
ELECTRODEHAFNIUMPELLET (-VE)
(d) Maximumwear in hafniumelectrode tip
EROSION OFHAFNIUM PELLET
NOZZLEOR CUTTINGTIP (+ VE)
EROSION OF NOZZLEWORK PIECE
346
tip and the amperage required for the thickness to be cut must be chosen.See that the flow of air is unhindered. The torch head is now broughtdown and held over the plate to be cut. The switch on the gun handle ispressed, the pilot arc established and the gap ionized. The torch head isnow brought down to the correct height, as determined by the stand offguide or guard at the plate edge. The plasma is transferred to the work (itis of positive polarity) and the cut commences. The torch head is movedalong so that the cut is smooth and continuous and there is a slighttrailing angle as it passes through the metal. At the end of the cut thetrigger is released and the plasma extinguished, but the air continues toflow for about a minute in order to cool the torch head. This is controlledby a control circuit in the power unit.The life of the electrode decreases with increasing current. At 150 A for40 mm thick plate the life is about 30 min, while at 50 A for 15 mm thickplate the life is about 110 min. In any case the electrode should bechanged when the insert has eroded to a depth of about 1.5 mm (Fig.7.16c). The nozzle or tip has a longer life but should be changed if theorifice is damaged or enlarged. A loss of cutting power may be the resultof melting down due to over-use and is accompanied by a green flame.A ceramic or high-temperature plastic assembly covers the tip (nozzle)to protect it from spatter and a heat shield is often included between tipand shroud. Air passing through the narrow gap between nozzle anddiffuser cools the torch head and guides the cooling air into the cut.Attachments, supplied as extras, can be fitted to the torch to give a longerarc for plasma gouging, this method being quieter than the carbon arcmethod.Multiple starts cause rapid erosion of the hafnium pellet, and the useof higher currents has the same effect. The higher the current the shorterthe life of the tip (nozzle). Remember that tip and electrode areconsumables and should be examined constantly for wear. Mostcomplaints about this process are due to trying to operate the tip orelectrode (or both) after their efficient life is past.Examine tip and electrode and replace or clean, if eroded.De-ionized waterWater taken directly from a tap contains dissolved carbon dioxide(CO 2 ) with possibly hydrogen sulphide (H 2 S) and sulphur dioxide (SO2)together with mineral salts such as calcium bicarbonate and magnesiumsulphate which have dissolved into the water in its passage through variousstrata in the earth. These minerals separate into ions in the water, forexample, magnesium sulphate MgSO 4 separates into Mg2+ ions (positively
charged) and sulphate ions SO|~ which are negatively charged. Similarlywith calcium bicarbonate (Ca(HCO 3 ) 2 ) which gives metallic ions, Ca 2+and bicarbonate ions HCOg".By boiling or distilling the water the minerals are not carried over in thesteam (the distillate) so that the distilled water is largely free of mineral saltsbut may contain some dissolved CO 2 . Distillation is however rather slowand costly in fuel and a more efficient method of obtaining de-ionized wateris now available and uses ion exchange resins. The resins are organiccompounds which are insoluble in water. Some resins behave like acids andothers behave like alkalis and the two kinds can be mixed without anychemical change taking place.When water containing dissolved salts is passed through a columncontaining the resins the metal ions change places with the hydrogen ions ofthe acidic resin so that the water contains hydrogen ions instead of metallicions. Similarly the bicarbonate ions are replaced by hydroxyl ( O H ) ionsfrom the alkaline resin. During this exchange insoluble metallic salts of theacid resin are formed and the insoluble alkali resin is slowly converted intoinsoluble salts of the acids corresponding to the acid radials previously insolution.The water emerging from the column is thus completely de-ionized andnow has a greater resistivity (resistance) than ordinary tap water so that itconducts a current less easily. A meter can be incorporated in the supply ofde-ionized water to measure its resistivity (or conductivity) and this willindicate the degree of ionization of the water in the cooling circuit. Whenthe ionization rises above a certain value the resins must be regenerated.This is done by passing hydrochloric acid over the acidic resin, so that thefree hydrogen ions in the solution replace the metallic ions (Ca2+ andMg2+). This is followed by passing a strong solution of sodium hydroxide(NaOH) through the column, when the hydroxyl ions displace thesulphate and bicarbonate ions from the alkaline resin.This process produces de-ionized water, purer than distilled water, easilyand quickly.Water injection plasma cuttingIn this process, water is injected through four small-diameter jetstangentially into an annular swirl chamber, concentric with the nozzle, toproduce a vortex which rotates in the same direction as the cutting gas(Fig. 7.17). The water velocity is such as to produce a uniform and stablefilm around the high-temperature plasma stream, constricting it andreducing the possibility of double arcing. Most of the water emerges fromthe nozzle in a conical jet which helps to cool the work surface.
348
NOZZLE
SWIRLING GAS
WATER SWIRLCHAMBER
349
. POWDER NOZZLES
351
separate drying and filtering unit should be installed in the air line to ensuredry, clean air. The oxygen and acetylene is supplied through not less than9 mm bore hose with 6 mm bore for the powder supply.The single-tube attachment discharges a single stream of powder into thecutting oxygen and is used for straight line machine cutting of stainlesssteel. The multi-jet type (Fig. 7.18) has a nozzle adaptor which fits over astandard cutting nozzle and has a ring of ports encircling it. The powder isfed through these ports and passes through the heating flame into thecutting oxygen. This type is recommended for hand cutting and for profile,straight and bevel machine cutting. Special cutting nozzles are available forthis process. These give a high velocity parallel cutting oxygen stream fromtheir bore being convergent-divergent. The pre-heater holes are smaller innumber but more numerous and are set closer to the cutting oxygen orificethan in the standard nozzle. This gives a soft narrow pre-heating flame,giving a narrower cut and better finish with a faster cutting speed. Since theiron powder is very abrasive, wear occurs in ports and passages throughwhich the powder passes. By using stainless tube where possible, avoidingsharp internal bends and reinforcing certain parts, wear is reduced to aminimum.
VSCREENOUTLET AIR POWDER'MIXTURE
-FILTERPRESSUREGAUGE
-DRYER
352
Cutting processesTechnique
Underwater cutting
353
Underwater cuttingUnderwater cutting of steel and non ferrous metals is carried outon the oxy-arc principle using the standard type of electrode which has asmall hole down its centre through which the pressurized oxygen flows tomake the cut. By using a thermic electrode, this oxygen stream causesintense oxidation of the material of the electrode, giving a greatly increasedquantity of heat for the cut. In both cases the products of the cut areremoved or blown away by the oxygen stream.A d.c. generator is used with the torch negative and the special type earthconnexion, connected to clean, non-rusted metal in good electrical contactwith the cut, is positive polarity: a.c. is not suitable as there is increaseddanger of electric shock.The torch head for ordinary or thermic electrodes is similar. It is toughrubber covered and has connections for oxygen and electric current. Theelectrodes, usually of 4 mm (^-") and 4.8 mm (-^") diameter are securelyclamped in the head by a collet for the size electrode being used. A twist ofthe torch grip clamps and releases the collet and is used for stub ejection.These collets can be changed to allow the torch head to be used for welding(Fig. 5.23).The oxygen cylinder, fed from a manifold, has a high volume regulatorwhich will give free flow and pressures from 8 bar (118 psi) at 12 m depth to20 bar (285 psi) at 107 m. In general the oxygen supply to the torch shouldgive about 6 bar (90 psi) over the bottom pressure at the electrode tip.Ingress of water to the torch head is prevented by suitable valves andwashers and replaceable flash arrester cartridge and screen are fitted.The seal for the electrode in the torch head is made with washers andcollet and tightened in place with the torch head locknut. When theelectrode is fitted to the head it must bottom on to the washer and be heldtight to prevent leakage of oxygen. Note that the thermic type of electrodewill continue burning once it has been ignited, even when the electricalsupply is switched off, due to the oxidizing action of the gas stream.
354
Use of equipmentAn eyeshield with the correct lens fitted is attached to the outsideof the diver's helmet. No oil nor grease should be used on the equipmentand there should be no combustible nor explosive materials near to thepoint where cutting (or welding) is to be performed. Hose connexionsshould be checked for leaks and all electrical connexions tight, especiallycheck the earth connexion and see that it is in good electrical connexionwith the position of the cut. As electrolysis can cause rapid deterioration,all equipment should be continually inspected for signs of this. If any partof the work is above water level, connect the earth clamp to this afterchecking that there is a good return path from the cut to the earth clamp.A double pole single throw switch of about 400 A capacity is connectedin the main generator circuit as a safety switch. This should always be keptin the 'off' position except when the cut is actually taking place. To begincutting, strike the arc and open the oxygen valve by pressing the lever on thetorch.When working, the diver-welder must always face the earth connexion sothat the cutting is done between the diver and the earth connexion. Whenthe electrode has burnt to a stub of about 75 mm in length the diver shouldcall to the surface to shut off the current by opening the safety switch. Thishaving been done the collet is loosened by a twist of the wrist, the oxygenlever is pressed and the stub is blown out of the holder. A new electrode isnow fitted, making sure that it sits firmly against the sealing washer, and thehandle twisted to lock it in place. Stubs should not be burnt close to theholder for fear of damage. When the safety switch is again placed in the'on' position cutting can again commence.When cutting, bear down on the torch so as to keep the cutting electrodeagainst the work so that the electrode tip is in the molten pool and proceedwith the cut as fast as possible consistent with good cutting. Spray backfrom the cut indicates that it is not through the work completely. Keep allcables and hoses from underfoot and where anything may fall on them.Pipes and tubes may be cut accurately to size under water by a hydraulicallyoperated milling machine which is driven around a circumferential guide.Safety precautionsThe general safety precautions which should be observed whenwelding are listed at the end of the section on oxy-acetylene welding butspecial precautions should be taken when cutting processes using oxygenare used in the welding shop or confined spaces. Oxygen is present in theatmosphere at about 29.9% by volume and below 6-7% life cannot besustained.
355
8The welding of plastics
PlasticsPlastics are replacing steel and other metals used in construction.They are now used in the home, in gas engineering, farming, sportsequipment, and in the automobile industry etc. Equipment made ofplastic is lighter than that made of steel, and since welding and fabricationis relatively easy and the cost of repair lower, it will be well to considersome of the processes involved.Plastics are derived mainly from oil, coal and wood. Polystyrene andpolyvinylchloride (PVC) are examples of those derived from oil and coalwhile the cellulose types (such as cellulose acetate and ethylcellulose) areproduced from wood. Plastics consist of larger molecules built up intochains arranged randomly, from single molecules (monomers) by aprocess of polymerization, assisted by a catalyst. (A catalyst is a substancethat accelerates a chemical reaction but undergoes no permanent changeduring the reaction.) If differing monomers are used, copolymers areproduced from which the characteristics of the original monomers cannotbe obtained.There are two main types of plastic: (1) thermo-setting and (2)thermoplastic. A thermo-setting plastic is one that softens when firstheated and is then moulded into the required form. Upon cooling it setshard and gains its full strength. Upon reheating it does not again softenand thus cannot be reshaped. An example of a thermo-setting plastic isthat made from phenol and formaldehyde, which with an acid catalystgives a soluble and fusible resin used in varnishes, and with an alkalinecatalyst gives an infusible and insoluble resin (Bakelite).Thermoplastic substances soften each time they are heated and can bereshaped again and again, regaining their rigidity and strength each time356
Plastics
357
Plastic
(Q350300
400-500350300270300400300
300-350350350
358
Thin sheets are welded by applying heat and pressure to the joint.The sheets are overlapped and then passed between two rollers; the widthof roller determines the width of the weld. One of the rollers is motordriven and can be heated by an electrical element. The other roller is freerolling and serves only as a back pressure for the heated roller. Thevariables are therefore: (1) the temperature of the heated roller, (2) thespeed at which the surfaces to be welded pass between the rollers, and (3)the pressure between the rollers. The two surfaces to be welded togetherpass when in the spongy state - just below melting. The heating elementfor the main roller has a potentiometer control and the element conductsits heat to the roller. To operate, the temperature is selected for the givenplastic (e.g. PVC), for which welding temperature is 300-500 C. Themotor is set at the correct speed to rotate the driven roller, and finally thepressure between the rollers is set. If the current is too low (temperature),or the pressure and speed of travel between the rollers too high, the twosheets will not weld together. If the current is too high and the speed oftravel too low, the sheets will be welded together only in certain parts andholes will appear. It will be appreciated that the three variables arenotoriously difficult to adjust correctly. Modern machines greatly simplifythis procedure. Note that the process is similar in many ways to seamwelding (p. 208). If the roller is hand-operated (usually for simple weldsonly) a smooth surface, under the part to be welded, is fixed so that ittakes the place of the bottom roller (Fig. SAa). Again the temperature ofthe heating element is set and the roller unit moved down the seam witha medium pressure. As before, if the speed is too high the sheets will not
Observations
ABSPCPEPPPAABS/PCPVC
359
PRESSURE
HEATED ROLLER
360
the air is supplied, while others use air supplied from an externalcompressor. In the latter, there are two leads to the gun: the electricitysupply for the heating element and the compressed air supply. This typeof gun is lighter and of smaller diameter than the type with an electricmotor in the body. However, the gun with the motor has the advantagethat there is only one cable feeding the motor and element (Fig. 8.2). Inboth types the air is blown over an electric element, the temperature beingaccurately controlled (by potentiometer). There is a switch on the outsideof the body of the gun, clearly marked so that any temperature between300 C and 600-700 C can be selected for the air issuing from the gun.In some guns the heating element is easily replaceable. The volume of airpassing over the element is controlled by a movable shutter over the airintake. The gun barrel gets very hot during use and should on no accountbe touched. Some guns have an outer shield over the barrel to prevent itbeing touched accidentally.Nozzles. A variety of nozzles are available, all having either a tight pushon fit, locked on with a clamp ring and screw, or a screwed-on fit. TheseFig. 8.2. (a) Hot air torches for general use.AIR AND TEMPERATURECONTROL
SPEED NOZZLE
PlasticsFig. 8.2. (b) High speed torch or gun showing relative size (Goodburn).
361
362
CRANKED NOZZLE
TACKING NOZZLE
TACKING NOZZLEHOT PLATE NOZZLEHOTPLATE
363
air passes through the baffle hole and preheats the joint, while the rest ofthe hot air is available for the welding operation, enveloping the base ofthe rod and the edges of the preparation. The rod to be used is passeddown the other tube in which it should be an easy sliding fit.The rod is preheated by the tube, and a shoe on the front of the nozzlerests on the completed weld. There is also a speed welding nozzle with nobaffle plate and a simple mixing chamber at the base. Speed welding isdealt with in detail later. Some units have a swing back tacking unit tosave time when changing nozzles. There are special high speed nozzles forleft-hand and right-hand welding in tight corners, and tank openings etc.Nozzles are available for 3, 4, 4.5, 5 and 6 mm round, 4 x 4 x 4 mm,Fig. 8.4. Speed welding nozzles.GUN
PREHEATING HOLE
Fig. 8.5. (a) Sections of welding rod. (b) Profiled welding rods, (c) Multi-run.(a)
364
OVERLAP
LESS THAN 3 mm
65-903-6 mm
rSINGLE BUTT
JGAP 0.5 mm OPTIONAL
65-85
6-8 mm
SINGLE BUTT
70-80OVERS mm
DOUBLE BUTT
5 mm GAP
JX.LAP
365
366
90cPVC
45-60PE
367
368
the angle between the gun and the weld determines the rate of welding,since the preheat hole varies the amount of preheat (Fig. 8.4). When thewelding rate is too slow there are charred edges to the weld (PVC), whenthe rate is too high, there is incomplete fusion with no flow lines. Thecompleted weld should be smooth with a faint wash visible down eachside, an indication of good fusion of rod and parent plastic (Fig. 8.9).Note that if cracks are being repaired they should be welded in acontinuous run, with, if possible, no stopping. To terminate a weld thegun is brought to the near vertical position and the rod is cut off byslipping the nozzle off the rod, leaving it standing attached to the weld.When cool it can be cut off close to the weld. If multi-layers are required(Fig. 8.5) each run should be allowed to cool before the next is applied.Since thermoplastics are poor conductors of heat, the stresses that ariseduring welding are concentrated in a smaller area than when weldingmetals. When welding V-prepared joints, the use of a profile rod and theprocess of speed welding reduces the stresses and accompanying strains.Note that the expansion coefficient of plastics is many times greater thanthat of steel.Practical hints
369
370
the machine produces an excellent weld between the sheets using a wideslot nozzle. For thin plastic sheets (e.g. bags) welding can be performedby a hand or machine driven roller. In both cases speed and temperaturemust be absolutely correct. Using a hand-held automatic welder, verticaland overhead seams about 10 mm thick can be tape welded and a testchannel incorporated.
371
must be applied, because too high a voltage puts greater strain on theplastic (the dielectric).The plastic weld under test is placed on the earthed metal plate and thegun switched on. The probe is then moved over the surface of the joint orother surface under test. When any defect is passed over, there is a brightspark and a hissing sound. The position of the defect is marked and theremainder tested as before. The defects are then repaired and the testeragain moved over the positions of the faults to ensure that they have beencorrectly repaired. All plastics including nylon can be tested for plate orweld porosity using the probe from the gun, the material to be tested lyingon the earthed metal plate.
372
373
The parts to be welded are loaded onto the upper and lower plattens ofthe machine (Fig. 8.12). The fusion faces are then plasticized by beingbrought into contact with the hot plates, which are retracted automaticallywhen the correct plasticizing point is reached. The mouldings are thenbrought together under pressure as with other types of hot plate welding.Upon cooling the assembly is unloaded from the machine.Complicated assemblies can be produced more cheaply in this way,because if one part of the assembly is damaged or cracked, that part canbe repaired by welding after correct preparation in the manner describedin the section on hot air welding.
CIRCLIP
COUPLER
TAPPING TEE
EQUAL TEE
374
any type offittingbeing used, is left in position in the trench, which is thenfilled in. The various joints made in this way can be subjected to tests forinternal pressure (say 10 bar), tensile strength and impact for saddles.It will be noted that with hot plate and electric fusion methods ofwelding, no extra filling rods are required. The electric fusion jointing ofpipes is more convenient than the hot plate method and is largely usedtoday.
Ultrasonic weldingWith this method of machine welding, an alternating current offrequency 50 Hz is connected to a generator where its frequency ischanged to 20-40 kHz (20000-40000 Hz) the capacity of the generatorbeing 100-3000 W as required (Fig. 8.14). This ultrasonic current, say at20 kHz, is fed into a transducer (which is generally a piezo-electric device)which changes the ultrasonic electric vibrations into a mechanicalvibration also at 20 kHz. (The magneto-strictive types are little usednowadays.)A piezo-electric material increases in length when a current flowsthrough a coil surrounding the device and changes the alternating electricfield into mechanical movement. Examples of piezo-electric materials arequartz, tourmaline (a silicate of boron and aluminium with additions ofFig. 8.14. Resonant unit, showing various amplitude gains in ultrasonicwelding (piezo-electric crystal transducer) (Bielomatik).GENERATORMODULARLAYOUT50 Hz MAINS
CONVERTERBOOSTERWELD-HORN
AMPLITUDE
375
magnesium iron and other alkaline metals and fluorine) and Rochelle salt(sodium potassium tartrate etc.). Present-day transducers have thin sheetsor wafers of piezo-electric material bonded to a central metal laminatedcore while two metal strips are bonded to the other faces of the piezoelectric material, the lengths of these strips being about one half that ofsound in the metal core, so that the assembly is resonant at the givenfrequency and vibrates ultrasonically at the frequency of the inputcurrent. The welding head to which the transducer is fixed is inserted toget the gain in amplitude which cannot be obtained from the horn alone.It consists of two parts: the booster and the horn, or tool holder. Thebooster increases the amplitude of the vibration and is clamped at itsnodal point (the point of least vibration). If the booster has a largerdiameter where it is attached to the transducer body than where it isattached to the horn, the amplitude is increased and the ratio of themasses of metal on each side of the node determines the increase ordecrease of the vibration.The horn is specially designed to have the correct sonic properties, andtransmits pressure to the welded surfaces and vibrates to make the weld.It must have good mechanical strength; the end which makes the weld canbe of cylindrical shape, bar shape, or more complex shapes according tothe parts to be welded. The horn can be made of steel alloy, aluminiumalloy or titanium, which all have good ultrasonic properties.The sequence of operations is: (1) machine is loaded; (2) force isapplied; (3) ultrasonic power flows for a given time; (4) hold time duringcooling of the weld; (5) force is removed and machine deloaded.
376
fixed parts generates the heat required for the welding process and thepressure assures good fusion. The pressure is time dependent and isreduced to a lower value for some of the welding time and the coolingtime. The time cycle varies from 1 to 4 seconds in most cases.This method is especially useful for welding thermoplastics of low
378
bonding rubbers and plastics. In addition, the curing time is increased butwith less odour.There is a wide range of adhesives covering most applications forlocking threaded parts, for acidic and porous surfaces and those havinggreat 'peel' strength with a top temperature of 100 C and a tensilestrength of 26 N/mm2.The 'gel' type adhesives are used for fabrics, paper, phenolics, PVC,neoprine, and nitrile rubber, with a curing time of a few seconds only. Onegel has no associated fumes or odour and can be used in confined spaces,while another is clear and thick and does not run. Its top temperature isover 100 C and it resists heat that would destroy a normal bond madewith instant adhesive.Another type is used for the assembly of pulleys, sprockets, bearings,bushes, sleeves etc., and other adhesives are used for pressed fits forcylinder liners of diesel engines. There are many other applications of thistype. There is also a range of adhesives which bond the substrates of glass,ceramics, ferrites, epoxy moulding compounds, phenolic resins, laminatedpaper, and glass fibre laminate epoxy materials.By the use of single-component liquids, drying rapidly at roomFig. 8.16. Bondmatic with foot switch and pencil.
379
temperature, surfaces are made suitable for bonding polyolefins and otherlow-energy surfaces. The liquid is applied by brush, spraying or dippingand is a polyolefin primer so that it should only be used for difficult-tobond surfaces, e.g. polyolefins, polypropylene, PTFE and thermoplasticrubber.With such a variety of adhesives available, each developed for a specificpurpose, it is essential that the operator should contact the makers of theadhesives and obtain a full list of the adhesives available and their methodof usage (Figs. 8.16 and 8.17).Fig. 8.17. Loctite adhesive squeeze bottle.
PVC(HDPVC andLDPVC)a
ABS(ABS/PVC andABS/MAT:hardABS reinforcedwith fibreglass,thermosetting)
380
PolypropyleneRigid and m.p. 170 C. Low SG can be used up to 120 C,(PPHD and PPLD) has: good mechanical strength and is resistant to mostcorrosive substances. Welded polypropylene can be usedup to 120 C as long as little stress is applied. Hasreplaced PVC and polythene in many fields. Used forsheeting, ropes and webbing. Compounded with othersubstances to improve qualities such as anti-cracking.Polyethylene(Ethylene C2H4)
PTFE(Ethylene with fourfluorine atomssubstituted forhydrogen atoms)
Polyacrylates(PMMA)
Polycarbonates
Poly amides
Appendix 1Welding symbols
382
Appendix 1Fig. A l . l
SINGLEV BUTTWELD
REFERENCE LINE
SINGLEBEVEL BUTTWELD(a)
\JSYMBOL
/ARROWLINE(b)
OTHER SIDEY///////////A
Y///////////A
SYMBOLICREPRESENTATION
rid)
ILLUSTRATION(e)
if)
PROCESS
NONDESTRUCTIVE
TESTING
ig)
Supplementary symbolsSHAPE
SYMBOL
ILLUSTRATION
FLAT (USUALLYFINISHED FLUSH)
CONVEX
CONVEX DOUBLEVBUTT WELD
CONCAVE
Y////////ZW/////A
Welding symbols
383
No. Process
1 Arc welding11 Metal-arc welding without gasprotection111 Metal-arc welding with coveredelectrode112 Gravity arc welding with coveredelectrode113 Bare wire metal arc welding114 Flux cored metal-arc welding115 Coated wire metal-arc welding118 Firecracker welding12 Submerged arc welding121 Submerged arc welding with wireelectrode122 Submerged arc welding with stripelectrode13 Gas shielded metal-arc welding131 MIG welding135 MAG welding: metal-arc weldingwith non-inert gas shield136 Flux cored metal-arc welding withnon-inert gas shield14 Gas-shielded welding with nonconsumable electrode141 TIG welding149 Atomic-hydrogen welding15 Plasma arc welding18 Other arc welding processes181 Carbon arc welding185 Rotating arc welding
4344441454748
Forge weldingWelding by high mechanical energyExplosive weldingDiffusion weldingGas pressure weldingCold welding
77172737475751752753767778781782
99191191291391491591691791891992392493949419429439449459469479489499519529539549697971972
2212222122523242529291
Resistance weldingSpot weldingSeam weldingLap seam weldingSeam welding with stripProjection weldingFlash weldingResistance butt weldingOther resistance welding processesHF resistance welding
33131131231332321322
Gas weldingOxy-fuel gas weldingOxy-acetylene weldingOxy-propane weldingOxy-hydrogen weldingAir fuel gas weldingAir-acetylene weldingAir-propane welding
384
Appendix 1
Fig. A 1.2. (a) Elementary welding symbols (BS 499, Part 2, 1980).
DESCRIPTION
SECTIONALREPRESENTATION
4. SINGLE-BEVELBUTT WELD5. SINGLED BUTT WELDWITH BROAD ROOTFACE6. SINGLE-BEVEL BUTTWELD WITH BROADROOT FACE
O(a) RESISTANCE
(b) ARC
385
Fig. A 1.2. (b) Examples of uses of symbols (BS 499, Part 2, 1980).DESCRIPTIONSYMBOL
GRAPHIC REPRESENTATION
SINGLES/BUTT WELD
VSINGLES/BUTT WELD
VAND BACKINGRUN
FILLET WELD
SINGLE-BEVELBUTT WELD
VWITH FILLETWELDSUPERIMPOSED
SQUARE BUTTWELD
bKb^ba^fta^STAGGEREDINTERMITTENTFILLET WELD
nxl -j (e)n XI L(e)nxl y (g)nxl L (e)
<M
386
\GROO VE ANGLE, INCLUDED'ANGLE OF COUNTERSINKFOR PLUG WELDS
S(E)
FIELD WELDSYMBOL
lA
WELD-ALL-AROUNDSYMBOLBASIC WELD SYMBOL....ARROW CONNECTINGORDETAIL REFERENCE < N)REFERENCE LINE TO ARROWTAIL (MA Y BE OMITTEDSIDE OR ARROW SIDENUMBER OF SPOT ORWHEN REFERENCE ISMEMBER OF JOINTPROJECTION WELDSNOT USED)EL EM ENTS IN THIS A RE A1REMAIN AS SHOWN WHEN TAIL ANDARROW ARE REVERSED
387
TYPE OFWELD
NO ARROWSIDE OROTHER SIDESIGNIFICANCE
BOTHSIDES
OTHERSIDE
FILLET
NOT USED
PH IG OR SLOT
SPOT ORPROJECTION
SEAM
SQUARE
~^-
GROOVE
tiEVEL
X >
>-
-<
FLARE-V
FLAREBEVEL
GROOVEWELD SYMBOL
/GROOVEWELD SYMBOL
JRFACING
1111
\r
BACK ORBACKING
NGE
1/
CORNER
~36
IL x
388
Appendix 1Fig. A1.5. Supplementary welding symbols.WELD-ALL-AROUNDSYMBOL
^SYMBOL^THAT
CONVEX CONTOURSYMBOL
CONVEX CONTOURSYMBOL INDICATES FACEOF WELD TO BE FINISHEDTO CONVEX CONTOUR
FLUSH CONTOURSYMBOLFLUSH CONTOUR SYMBOLM *INDICA TES FACE OF WELD TOBE MADE FLUSH.WHEN USED WITHOUT A FINISHSYMBOL, INDICATES WELD TO BEWELDED FLUSH WITHOUT SUBSEQUENTFINISHING
CONTOURFLUSH
389
SIZE OF SURFACEBUILT UPBY WELDINGSYMBOL
DESIRED WELDUNEQUAL DOUBLEFILLETWELDING SYMBOL
SIZE (LENGTHOF LEG)
DESIRED WELDCHAININTERMITTENTFILLET WELDINGSYMBOL
STAGGEREDINTERMITTENTFILLET WELDINGSYMBOL
LOCATE WELDS ATENDS OF JOINT
LENGTHt2" 5 ^\ K n ^\||h
GOF-5-U-5* WELDDES/RED WELDSLOCATE WELDS ATENDS OF JOINT
OF INCREMENTSPITCH (DISTANCEBETWEEN CENTERS)OF INCREMENTS
SYMBOLLENGTH OF INCREMENTSPITCH (DISTANCEBETWEEN CENTERS)OF INCREMENTSSYMBOL
DESIRED WELD
SINGLE V-GROOVEWELDING SYMBOL
v V\~ROOTOPENINGDESIRED WELD
-ROOT OPENING"GROOVE ANGLE
l-i
SINGLE V-GROOVEWELDING SYMBOLINDICATING ROOTPENETRATION
DOUBLE-BEVELGROOVEWELDING SYMBOL
SIZE.DEPTH OFCHAMFERINGPLUS ROOTGROOVE ANGLE PENETRATION R00 T PENETRA TIONDESIRED WELDSYMBOLOMISSION OFGROO VE ANGLE'-*>|,45OSIZE DIMENSIONJFTMINDICA TES ATOTAL DEPTH OFROOT +CHAMFERINGOPENING EQUAL TOTHICKNESSOF MEMBERSDESIRED WELDSYMBOLSIZE
DEPTH OF FILLINGINCLUDED ANGLEOF COUNTERSINK
PLUGWELDINGSYMBOLDESIRED WELDSLOTWELDINGSYMBOL
SYMBOLORIENTATIONMUST BESHOWN OND RAW ING
DEPTH OF FILLINGOMISSION INDICATESFILLING IS COMPLETE
Appendix 2Simplified notes on the operation of athyristor
ANODE-i
CATHODEV CATHODE CONNECTED\j-CATHODETOnTYPELAYER
GATETHYRISTOROPERATION
CATHODESYMBOLGATE
GATEGATE TERMINALATTACHED TOp LAYER
ANODEp LAYERCONNECTED TOSTUD BASE BYANODE PLATELOW POWER STUD BASETHYRISTOR
Gallium arsenide is now regarded as a suitable material for integrated circuits (IC) andother devices, not supplanting silicon, but being used for high speed and high frequencyapplications where silicon is not suitable.
390
Operation of an SCR
391
C\
\0NEKNOBCURRENTCONTROL
SAW TOOTHEDWA VE FORMSIGNAL FROMMAINS SYNCHRONIZEDRAMP GENERATOR
MAINSFREQUENCY
NOTE.
\.7,Z,AND4FORMPART OF ANINTEGRA TED OPERA TIONALAMPLIFIER CIRCUIT
392
Appendix 2Fig. A2.3
90 18i
(b) FULLRECTIFIEDWAVE(c) GATE PULSE
Thi0Th2
(d) SECTION OFWAVECONDUCTEDBY THYRISTORTHIS SECTION OF THE WA VE IS CONDUCTED
THYRISTORS
AUXILIARYCATHODE
y~~,.-, ,H4---- : ^GATE
CONTROLLEDa.c. OUTPUT
A number of other circuits are available, including three phase and a.c.controllers, the latter producing a regulated alternating output (Fig.A2.4).
Appendix 3Proprietary gases and mixtures
Gas
Cylinder colour
AcetyleneAir (not breathing quality)ArgonCarbon dioxide, commercial vapourwithdrawalCarbon dioxide, commercial liquidwithdrawalHydrogenNitrogenOxygenPropaneArgon/carbon dioxideArgon/heliumArgon/hydrogenArgon/oxygenNitrogen/hydrogen
MaroonGreyBlueBlackBlack with white stripes down lengthof cylinderRed
393
394
Appendix 3Fig. A3.1. Special mixtures.
NON-FLAMMABLENON-FLAMMABLEFLAMMABLEFLAMMABLENON-TOXICTOXICTOXICNON-TOXICPINK SHOULDER RED SHOULDER YELLOW SHOULDER RED AND YELLOWSHOULDER
395
Cylinder contents
Applications
Ar 99.99 %
He
AGA MIX SP Ar 92 %, CO 2 8 %AGA MIX SH Ar 75%, CO 2 25%AGA MIX O2 Ar 98 %, O2 2 %AGAAGAAGAAGAHe30AGAHe70AGAAGA
MIX H5 Ar 95 %,MIX H20 Ar 80%,MIX H35 Ar 65 %,MIXAr 70 %,MIX
H2 5 %H2 20%H 2 35 %He 30 %
Ar 30 %, He 70 %
MIX N 2 Ar 98 %, N 2 %MISON Ar with less than0.03 % NOAGA MIX NH H2 10%, N 2 90%
Argon + (pure)Nitrogen
N2
Cylinder colours
OxygenNitrogenHeliumArgonHydrogenCoogar 5
BlackGrey with black shoulderBrownPeacock blueRed
N2HeArH2Ar 93%, CO 2 5%, O 2 2 %
Coogar 20
Ar 78%, CO2 2 0 % , O 2 2 %
Coogar SG
Ar 83%, CO 2 15%, O 2 2% j
Astec 15
Astec S3
Astec 25
He 75%, A/ 25 %
Astec 30
He 30%, Ar 70%
Astec 50
He 50%, Ar 50%
Quasar
Ar 98%, O 2 2 %
HytecHytecHytecHytec
ArArArAr
13535
99%,97%,95%,65%,
H2H2H2H2
1%3%5%35%
Maroon
AcetyleneApachi-plus
C 3H 8
4 10
BOC Ltd {British Oxygen Co Ltd): Shieldmaster range of gases for welding and cuttingGas
OxygenNitrogen
h6
HeliumArgon
1h
Carbon dioxide
Helium HePure argon Ar (99.997 %purity)High purity argon(99.999% purity)Carbon dioxide CO 2 (toBS 4105 99.8% purity)
BlackGrey with black shoulder; two whitecircles on shoulder indicate the higherpurityBrownBlue
Argoshield 5
hh
Ar 86%, CO 2 12%, O 2 2 %
Argoshield 20
Ar 78 %, CO 2 20%, O 2 2%
Pureshield PI
Ar 98.5%, H 2 1.5%
Pureshield P2
Ar 65%, H 2 3 5 %
Helishield HI
Helishield H2
He 83%, Ar 15%, CO 2 2%and a trace of oxygenHe 75%, Ar 2 5 %
Helishield H3
Helishield H5
He 50 %, Ar 50 %
Helishield H101
Argomix
Argon / Hydrogen
Argonox
Acetylene
PropylenePropane
Ar 93 %, CO 2 5 %, O 2 2 %
Argoshield TC
Special mixtures asrequired99/1, 98/2, 95/5%argon/oxygenAcetylene C 2 H 2Propylene C 3 H 6Propane C 3 H 8 toBS 4250
O2N2
Black
Ar
H2
CO,
PropaneAcetyleneAir (blended)Argon and argon-based
C2H 2Air
Krysal 5
Ar93%
CO,5%
2%
Krysal 20
78 %
20 %
MaroonGrey cylinder and cage
Krysal SM
85 %
13.5 %
1.5 %
Krysal G8
92%
8%
Krysal 155
80 %
15 %
Excellar 8
5%
Argon-based
Ar99%98%
O21% \2% \
97%
3% J
Ar70%50%25 %
He30%50%75 %
Argon-oxygenArgon/oxygen 1 %Argon/oxygen 2%Argon/oxygen 3%
Helium basedStellar 30Stellar 50Stellar 75
CO2
minor majormajorminormajor minorHelium -air
Balloon gas
tracetracetrace
A rgon-hydrogenHylarHylarHylarHylarHylar
123535
Ar99%98%97.595%65%
1%2%1.5%5%35%
Appendix 4Tests for wear-resistant surfaces
TEST SPECIMEN
WHEEL (RUBBER)
RINGTEST SPECIMEN
- OPTIONAL LUBRICATIONa ADHESIVE WEAR
b ABRASIVE WEAR
- GROUND BLOCK
403
Appendix 5Conversion factors
inch
AAt
Ai
0.40.81-62.43.24.04.86.4
Preferredmm
t68
isi__
3456
16i.8_LL161
8.09.511.112.714.416.017.619.022.425.4
8101112
1518202225
SWG
282624222018
0.380.460.560.710.911.22
16141210864
1.62.02.53.254.05.05.9
404
Appendix 6Low hydrogen electrode, downhill pipe welding
A d.c. power source is used as with cellulosic rods (p. 73) and isusually engine driven in thefield,the electrode being connected to the vepole. Weld metal deposition is faster than with cellulosic or uphill lowhydrogen methods and a short arc is used with no 'pumping' of theelectrode. Since shrinkage is important, if internal clamps are used thereshould be more spacers. The preparation of a joint using different diameterpipes is show in Fig. A6.1 and the tack welds should be tapered at each end.For the root run the electrode should lightly touch the joint and the weldshould continue through 6 o'clock about 2 mm towards 7 o'clock tofacilitate link up with the run to be deposited on the other side. There is noweave and keeping a short arc and high travel rate the slag is kept above the
ROOT GAPROOT FACEELECTRODE DIAMETER2.5 mm3.25 mm
ROOT CAPELECTRODE DIAMETER2.5 mm3.25 mm
2.5 mm + 1.0 mm2.5 mm + 1.0 mm
405
406
Appendix 6Fig. A6.2
Fig. A6.3
BREAKING ARC
GROUNDCRATER
V?arc at a distance of about the coating diameter. The arc is broken by turninginto the bevels and the metal is tailed off as shown in Fig. A6.2.Thefinishingcrater should be ground to a pear-shaped taper (Fig. A6.3)and the next electrode is started about 10 mm above the top end of thetapered crater. Slag is removed from each run with power brush andchipping hammer and grinding is used to remove any excess metal generallyfrom 4 to 6 o'clock. The penetration bead may be slightly concave but has asmooth tie-in with the pipe metal and is acceptable. Too much heat givesincreasingly convex penetration and is due to too slow travel or too high acurrent.Avoid burn through between 12 and 1 o'clock when using a leading arc bykeeping the arc as short as possible and directing it alternately to each side ofthe joint. Fig A6.4 shows angles of electrode, electrode diameters andcurrents.For thefillingand capping runs the arc is kept short with a weave not exceeding 3 to 4 times the core wire diameter and the slag-electrode distanceFig. A6.4. Angles of electrode, electrode diameters and currents, root run.2.5 mm, 80 A3.25 mm, 115-120/A
80, 2.5 mm90-110, 3.25 mm
2.5 mm, 90 A3.25 mm, 135 A
80-110
2.5 mm, 80 A3.25 mm, 125-130-4
407
MOVEMENT
80-100ELECTRODE FILLCAPDIAMETER3.25 mm 150 A 135-140 4A mm^80A 180/44.5/77/77230 A
Fig. A6.7
Fig. A6.6MOVEMENT
10/77/77'
ELECTRODE TIP
408
Appendix 6
during use and the joint should be completely free of all moisture. The weldmetal has high resistance to cracking and is of composition C 0.06-0.09%,Mn 1.00-1.40%, Si 0.03-0.07% and classification AWS A5.5 E8018-GBS 639 E5154B 120 90(H).
Appendix 7The manufacture of extruded MM A electrodes
410
Appendix 7side, the wire rods drop into the feed magazine. The extruder pistonis then operated and when the flux flow pressure is reached the wirefeed commences. Accelerator and drive rolls take the rodsdropping from the magazine and push them axially through thepress to the extrusion head where they receive their coating.(7) Concentricity check and brushing. It is important that the core wireshould be centrally placed in the covering (pp. 5-6). This is checkedelectronically and adjustments made if required. A transfer beltthen takes the electrodes to a brushing station where the ends forthe electrode holder and the striking tip are formed, after whichthe number or type of electrode is printed on the coating by aprinting machine.(8) Drying and baking. The electrodes are air dried to prevent crackingof the coating and are then loaded into baking ovens, after whichthey are ready for packing.Fig. A7.1. Simplified diagram of electrode production process.RAWMATERIALSTORES
PREPARATIONANDBLENDING
PRODUCTION
PACKAGING
COLOUR MARKINGLABEL PACKAGEPRINT ON BATCH NO.
STORES
MMA electrodes
411
Appendix 8Notes On fire extinguishing
Fire extinguishing
413
(D) Metals (magnesium, metallic powders). Special powders containing sodium or potassium chloride are required. Such fires shouldbe dealt with by the fire brigade.
Types of extinguishers(1) Carbon dioxide CO2. This contains liquid CO 2 under pressure,which is released as a gas when the trigger or plunger on theextinguisher is operated.(2) Extinguishing powder (gas cartridge). The powder is expelled bythe pressure from a gas cartridge.(3) Extinguishing powder (stored pressure). The powder is expelled bypressure stored within the body of the extinguisher.(4) Foam (chemical). Chemicals stored in the body of the extinguisherare allowed to mix and react, producing foam, which is expelledfrom the extinguisher.(5) Foam (gas cartridge). Foam is expelled from the extinguisher bythe pressure from a gas cartridge.(6) Foam (mechanical stored pressure). Pressure stored in the body ofthe extinguisher expels the foam.(7) Halon (storedpressure). The body of the extinguisher contains ahalon which is expelled by pressure stored within the body.(8) Water (gas cartridge). Water is expelled from the extinguisher bythe pressure from a gas cartridge.(9) Water (stored pressure). Water is expelled by pressure storedwithin the extinguisher body.(10) Water (soda-acid). An acid-alkaline reaction within the bodyproduces the pressure to expel the water.Extinguishers containing dry powder, CO2 and vaporizing liquidsThese extinguishers are suitable for fires involving flammableliquids and live electrical apparatus (as are met with under weldingconditions). For fires in liquids (containers or spillage) the jet or hornshould be directed at the near side of the fire, which should be driven awayfrom the operator to the far side with a side-to-side motion of the jet. Iffalling liquid is alight begin at the bottom and move upwards. On electricalapparatus direct the jet directly at the fire after first switching off the mainssupply. If the latter is not possible, contain the fire and summon the firebrigade.If there is no shut-off valve on the extinguisher continue discharging itover the fire area until empty. If the discharge is controlled, shut off the
414
Appendix 8
extinguisher discharge when the fire is extinguished and hold it ready forany further outbreak which may occur when the atmosphere has cleared.Do not use vaporizing liquid extinguishers in confined spaces wherethere is poor ventilation and a danger of fumes being inhaled.Foam extinguishers give semi-permanent protection against containedfires and will partially extinguish a fire, which will not gain its full intensityuntil the foam covering is destroyed. They may be used on liquids, in tanksto protect them from ignition or from giving off flammable vapours. Drypowder and foam should not be used together unless a specially compatiblepowder/foam are used.BCF extinguishersWhen this type is used the bromochlorodifluoromethane, which isa stable compound, appears as a heavy mist that blankets the fire andexcludes the atmospheric oxygen. It is more efficient than chlorobromomethane (CB), methyl bromide (MB) or carbon tetrachloride (CTC). It doesnot damage normal materials and leaves no deposit. It decomposes slightlyin the heat of a flame but the amount of harmful gas produced (which has apungent smell) has no effect on adjacent personnel even when excess BCF isused. It has high insulating properties and can be used on electricalequipment and is particularly suitable for the welding or fabrication shopsince it can be used on Class A fires in addition to those of Class B and C.
415
416
Appendix 9Table of brazing alloys and fluxes
Nominal composition
BS 1845
Easy-floEasy-flo No. 2DIN Argo-floArgo-floMattibraze 34Argo-swiftMetalfloArgo-bondMetalsilMetalbondMetaloy
50% Ag:Cu:Cd:Zn42% Ag:Cu:Cd:Zn40%Ag:Cu:Cd:Zn38% Ag:Cu:Cd:Zn34% Ag:Cu:Cd:Zn30% Ag:Cu:Cd:Zn25% Ag:Cu:Cd:Zn:Si23% Ag:Cu:Cd:Zn20% Ag:Cu:Cd:Zn:Si17% Ag:Cu:Cd:Zn:Si13% Ag:Cu:Cd:Zn:Si
620608595608612607606616603610605
630617630655668685720735766782795
AG1AG2
AG11AG12
Silver-flo
55% Ag:Cu:Zn:Sn45%Ag:Cu:Zn:Sn45%Ag:Cu:Zn:Sn45% Ag:Cu:Zn44%Ag:Cu:Zn40%Ag:Cu:Zn:Sn38% Ag:Cu:Zn:Sn34%Ag:Cu:Zn:Sn33%Ag:Cu:Zn30%Ag:Cu:Zn:Sn30%Ag:Cu:Zn25%Ag:Cu:Zn24% Ag:Cu:Zn20% Ag:Cu:Zn:Si18%Ag:Cu:Zn:Si16%Ag:Cu:Zn12%Ag:Cu:Zn4% Ag:Cu:Zn1% Ag:Cu:Zn:Si
630640640680675650660630700665695700740776784790820870880
660680680700735710720740740755770800780815816830840890890
AG14
The range of cadmium-free alloys has been developed for applications where the presence ofcadmium is not allowed due to the brazing environment or the service conditions of the assembly, i.e.food-handling equipment.Silver-flo 55 is the lowest melting-point alloy in thegroup and has been widely adopted as a substitutefor Easy-flo No. 2.Silver-flos 30 to 45 are general-purpose alloyssuitable for use on most common engineeringmaterials.The alloys with less than 24% silver are widely usedon copper and steel. They give a good colour matchon brass, but require close temperature control dueto their high melting temperature.Unlike the cadmium-bearing range, this groupcontains low silver content alloys such as Silver-flo33, 24 and 16, with relatively high melting points,which make them ideal for step brazing.
55554524544403834333023025242018161241
AG20
AG21
BS ]
Sil-fosSil-fos 5SilbralloyCopper-floCopper-flo No. 2Copper-flo No. 3
15% Ag:Cu:P5% Ag:Cu:P2% Ag:Cu:P7%P:Cu6%P:Sb:Cu6%P:Cu
644650644714690714
700**710**740**800800850
CP1CP4CP2CP3CP5CP6
Easy-flo No. 3
50% Ag:Cu:Zn:Cd:Ni
Argo-braze 38
38% Ag:Cu:Zn:Cd:Ni
Argo-braze 49H
49% Ag:Cu:Zn:Ni:Mn
680
670
710
Argo-braze 40
40% Ag:Cu:Zn:Ni
780
Argo-braze 25
25% Ag:Cu:Zn:Ni:Mn
810
Easy-flo Tri-foilfcC
620620
Easy-flo Tri-foilkCN'
AB49 Tri-foil
634
656
AG9
615
655
705
Brazing fluxesFluxes are normally selected on the basis of two main criteria: 1. The melting range of the brazing alloy - both solidus and liquidus should fallwell within the quoted working range of the flux. 2. The parent metals to be joined - some alloys, such as aluminium bronze, require specialfluxes. Copper, brass and mild steel are effectively cleaned by all fluxes.Workingrange C
D I N 8511
Availability
Easy-floFlux
550-800
F-SHl
Powder/Paste
Easy-floFluxDippingGrade
550-775
Paste
A general-purpose flux with good fluxing activity and long life at temperature. The powderhas good hot-rodding characteristics.A highly active and fluid flux which exhibits aminimum of bubbling, making it ideal forinduction brazing. This paste is formulated togive a thin, stable consistency suitable fordipping.
Easy-floFluxStainlessSteel GradeEasy-floFluxAluminiumBronzeGrade
F-SHI
Powder
TenacityFlux No. 6
TenacityFlux No. 14TenacityFlux No. 4A
550-750
600-850
F-SH1/2
TenacityFlux No. 5
600-900
TenacityFlux No. 125
750-1200
F-SH2/3
TenacityFlux No. 12Silver-flo
8OCM3OO
F-SH3
Mattiflux 100
Description
* This flux is unsuitable for use on stainless steel where crevice corrosion is likely to be a hazard in service.
Residue removal
Silver-flo 60
60% Ag:Cu:Zn
695
730
AG13
Silver-flo 43Argo-braze 56
43% Ag:Cu:Zn56% Ag:Cu:In:Ni
690600
775711
AG5
Argo-braze 35
35% Ag:Cu:Sn:Ni
685
887
Silver-coppereutectic
72% Ag:Cu
778
AG7 andAG7V
RTSN
60% Ag:Cu:Sn
602
718
15% Manganesesilver
85% Ag:Mn
951
960
AG19
Alloy
Meltingrange (C) BS 1845
Cadmium bearingEasy-flo No. 2DIN Argo-floMattibraze 34Argo-swift
42%40%34%30%
Ag:Cu:Zn:CdAg:Cu:Zn:CdAg:Cu:Zn:CdAg:Cu:Zn:Cd
608-617595-630612-668607-685
Cadmium freeSilver-flo 55
55% Ag:Cu:Zn:Sn
630-660
Silver-flo 40Silver-flo 33
40% Ag:Cu:Zn:Sn33% Ag:Cu:Zn
650-710700-740
Silver-flo 30Silver-flo 20
30% Ag:Cu:Zn20% Ag:Cu:Zn:Si
695-770776-815
AG2
RemarksA very fluid alloy, ideal for small components.A general-purpose alloy with good flow characteristics.Fillet-forming alloys with limited flow characteristics.
A free-flowing alloy generally suitable for all applications where a neat appearance is required.A range of cadmium-free alloys with fillet-formingproperties.An economical alloy suitable for brazing mild steel andcopper.
97% Cu:Ni:B
1081
1101
CU7
965
995
9808901090
10309301100
B' Bronze
' C Bronze
86% Cu:Mn:Ni
86% Cu:Mn:Co58% Cu:Zn:Mn:Co97% Cu:Ni:Si
ArgentelArgentel B
49% Cu:Zn:Ni:Si57% Cu: Zn:Ni: Mn: Si
913890
930910
221235
Plumbsol
2.5% Ag:Sn
P35P5
3.5% Ag:Sn5% Ag:Sn
221221
Ceramic No. 1
9% Ag:Sn:Pb
Comsol
1.5% Ag:Sn:Pb
A25A5LM10A
2.5% Ag:Pb5% Ag:Pb10% Ag:Sn:Cu
304304214
304370275
LM15
5% Ag:Cd:Zn
LM5
5% Ag:Cd
Corrosive - can beremoved with coldwaterNon-corrosive - canbe removed with coldwater
150-400
Appendix 10Latest plant and equipment
Fig. A10.1. For MIG process. See p. 100 for description of unit.
429
430
Appendix 10Fig. A10.2. For MIG, MAG (GMAW), MMA (SMAW), d.c. TIG (GTAW)and pulsed MIG. See p. 103 for description of unit.
431
432
Appendix 10Fig. A10.4. For MMA (SMAW) and MIG (GMAW), dip spray or pulsedmodes. See p. 143 for description of unit.
433
Fig. A10.5. For synergic pulsed MIG (GMAW). See p. 144 for description ofunit.
434
Appendix 10Fig. A10.6. 150 A single phase illustrated (200 A, 300 A and 500 A alsoavailable). For the 300 A unit, phase 50-60 Hz 380^15 V inverter unit for d.c.TIG and MM A. Output MMA 5-250 A TIG 5-300 A; arc volts 30, OCV 62.Up and down slope 0-1.5 sec. Arc spot timer. Low and middle pulsefrequency with adjustment range 15-85%. Stepless control of current. Smoothshift from welding to crater-fill current. Remote control optional. HF or liftstart.
iFig. A10.7 (opposite), (a) NBC (Butters) MIG power sources to BS 5970 andISO 9000 in three outputs, 320 A, 350 A and 450 A. Input 3-phase 415 V,50 Hz. Ratings 10.8 kVA, 13.5 kVA and 17.1 kVA in each case. OCV of each13-43. Outputs at 60% duty cycle 300 A, 375 A, 450 A; at 100% duty cycle250 A, 300 A, 350 A, for each unit. Boom supplied if required, (b) Ultra TIG250 square wave. Electronically chopped d.c. with square wave output; solidstate control; gas pre and post flow; slope up and down current; craterfill;current settings 5-25 A and 5-250 A; frequency selection 25^50 Hz; cleaning(balanced) 99-1 % or 1-99%; latch selector; pulse module optional; digitalmeters.
435
DDD
POSITIVE
LOCAL
AMP SELECT
AMPERESNEGA Tl VE REMO TE
OFF
TIG
ON
MMA
PREGAS UP SLOPE
436
Appendix 10Fig. A10.8. TIGWAVE 250 a.c./d.c. for a.c. adjustable square-wave TIGwelding; d.c. TIG, a.c./d.c. MMA welding with arc force control. Flux coredwire welding with CC CV feeders. Input 220, 240, 415, 500 V, the 415 V modelat 35 A, frequency 50 Hz. Output 80 OCV single output 5-310 A, 250 A at30 V and 40% duty cycle, 200 A at 28 V and 60% duty cycle. Adjustablesquare-wave control. Crater fill control. Arc force control. Trigger hold whichin ' O N ' position enables use of torch button when arc is established.Depressing button second time triggers the crater fill function. Optional spottimer. Pre- and post-flow gas timer. See p. 159 for drawing of this power unit.
437
438
Appendix 10Fig. A10.10. Cyber wave 300 A, a.c. or d.c. rated output 300 A, OCV 80.Input 3-phase, voltages 230/460/575. For a.c. square wave TIG, square wavea.c. and d.c. plasma, a.c. and d.c. MMA (stick). For aluminium, magnesium,steel and stainless steel. Auxiliary power 1 kVA. Arc force control. Balancecontrol d.c.e.n. 60-80 % for maximum penetration; d.c.e.p. maximumcleaning. Single current range. Solid state program module, calibrated for usewith various units, e.g. pulse and arc spot timer, up and down slope, gasprepurge, HF start.
439
Fig. A10.ll. PowCon 300 A power source. Inverter, single and 3-phase;suitable for MIG/MAG (GTAW), dip spray and flux cored (FCAW) TIG(GTAW) d.c, MMA (SMAW) and CO2 processes. Smooth low ripple arc.For 3-phase model, input 380-575 V, with OCV 80. At 100% duty cycle 150 Aat 30 V, at 60 % duty cycle 300 A at 32 V. Optional extras: pulsed MIG,pulsed TIG. Hand or foot remote control. Generator can be engine-driven ifrequired. Weight 45-48 kg, depending on model.(a)
(b)CIRCUIT BREAKER
RANGE SWITCH s
VOLT/AMP METER
PRIMARY LEAD
WELD PROCESSSELECTOR SWITCH REMOTE CONTROLRECEPTACLE
SHORTARCPUDDLE CONTROL'WELD POWER'CONTROL
300 sm SHOWN
QUICK CONNECTOUTPUT TERMINALS
440
Appendix 10Fig. A10.12. Water-cooled diesel unit. Automatic idle, a.c. and d.c. constantcurrent (CC) output for MMA (stick) and d.c. constant voltage (CV) outputfor gas, metal and flux-cored arc welding; a.c. TIG by addition of HF unit;115 and 230 V single-phase auxiliary power for tools etc.
441
Fig. A10.13. Wire feeder, CC/CV with selector switch. The CV operationcontrols the wire-feed speed. The CC operation controls the arc voltage.Increase in arc volts means a decrease in wire-feed speed (wfs), one driven rolland one idler roll. Speed of wire 0.127-15.25 m/min. Spool weight 13.6 kg.Wire: tubular 2.0 mm or smaller, solid 1.3 mm or smaller. Weight of unit11.8 kg. Motor 20 V d.c. permanent magnet motor. Quick connect gunconnection. Optional remote control. Suitable for shipyards, pipe-lines,manufacturing, offshore, power plants etc.
Appendix 11Refraction and reflection
WEAK POLARIZED
REFRACTEDRAY
442
443
Fig. Al 1.1.00INCIDENT RAY
EMERGENT RAYPARALLEL TO INCIDENTRAY BUT DISPLACEDFROM IT
PolarizationWe have seen that a ray of light is an electromagnetic radiationhaving two component fields, one electric and the other magnetic,vibrating or oscillating at random, at right angles to each other and atright angles to the direction of travel of the ray.If the. | https://id.scribd.com/doc/294187826/Welding | CC-MAIN-2020-16 | refinedweb | 67,550 | 53.71 |
November 8, 2016 | Written by: Andrew Ferrier
Categorized: Compute Services | How-tos.
One of the things the IBM Bluemix platform (based on Cloud Foundry) supports is logging to external providers. Takehiko Amano’s excellent article on Splunk integration with Bluemix describes the solution.
Splunk is a popular platform for log aggregation. It provides an easy way to aggregate logs from multiple sources, providing a way to index and search them in multiple ways. You can find additional details on the Splunk website.
Takehiko’s solution is excellent, but still requires somewhere to deploy Splunk. However, Bluemix itself provides the IBM Containers offerings (based on Docker technology) where Splunk can be run. This isn’t suitable for robust production environments, where you’d want the logging to be externalised from the Bluemix infrastructure, but for “quick ‘n’ dirty” testing, it’s really useful. I’ve documented some steps below that you’ll need to follow to get this up and running with Splunk Light (the simpler, lighterweight edition of Splunk).
Prerequisites
- You have a git client installed locally.
- You have signed up for IBM Bluemix (Public) and have a login ID.
- You have installed Docker locally on your machine. This will give you access to the Docker command-line tools.
- You have installed the IBM Bluemix command-line tools, which will require first installing the prerequisite Cloud Foundry command line tools.
Instructions for this tutorial are written assuming you are using OS X, although they can probably be adapted to other operating systems fairly easily.
Build the Splunk Container
You need to build the Docker container for Splunk locally before pushing it up to the Bluemix containers repository. There’s already a well-established GitHub project for a Splunk Docker container, but we need to add the RFC5424 add-on as per Takehiko’s article to get Splunk to recognize the logging format.
I’ve already forked the GitHub repository and added most of the changes required to do that, but you will need to download the add-on itself first.
- Open a terminal and clone my repository, checking out the bluemix branch:
git clone -b bluemix
- Download the RFC 5424 add-on. You’ll need to sign up for a free splunk.com ID if you don’t already have one. Put the
.tgzfile in the splunklight directory inside your checked-out git repository.
- Now build the Docker image (which may take a little while):
cd/splunklight
docker build -t andrewferrier/splunk:latest-light .
(If you wish, you can substitute your own namespace prefix in place of
andrewferrier – as long as you use it consistently below).
Push the Splunk Container up to Bluemix and start running it
First, log into Bluemix and initialize the container runtime:
bx login
bx ic init
You’ll need to specify an organization and space to work within Bluemix.
Next, double-check what your IBM Containers “namespace” is. If you’ve worked with Containers before, you probably already have one specified. You can check it with
bx ic namespace-get. If you haven’t, you’ll need to set one with
bx ic namespace-set (I use
andrewferrier, for example; but you can set it as anything that’s meaningful to you—it will have to be unique across all users using shared Bluemix).
Now, tag your built image to prepare it for upload to the remote registry:
docker tag andrewferrier/splunk:latest-light
registry.ng.bluemix.net/andrewferrier/splunk:latest-light
(Note that the first
andrewferrier above is the prefix we specified previously when we built the image. The second is the namespace on Bluemix itself as just discussed. If you want to work with the UK instance of Bluemix, rather than the US one, change all references to
.ng. to
.eu-gb.)
Now, actually push the image to the remote registry (this may take a little while):
docker push registry.ng.bluemix.net/andrewferrier/splunk:latest-light
Next, we need to create some persistent volumes for both the
/opt/splunk/etc and the
/opt/splunk/var filesystems within the container:
bx ic volume create splunk-etc
bx ic volume create splunk-var
Start running the container. Notice that we’re exposing two TCP ports,
8000 (which will be used over HTTP to access the Splunk console), and
5140 (which will be used to push syslog messages from Bluemix to Splunk).
bx ic create -m 1024 -p 8000 -p 5140 --env SPLUNK_START_ARGS="--accept-license" --volume splunk-etc:/opt/splunk/etc --volume splunk-var:/opt/splunk/var registry.ng.bluemix.net/andrewferrier/splunk:latest-light
Once the container has started running, the Bluemix CLI will print out the container ID. You typically only need the first few characters—enough to uniquely identify it (e.g.
abc1234).
Now check which public IP addresses you have free to assign to the container:
bx ic ips
This should print a list of IPs (probably two if you’re working with a trial Bluemix account)—pick any IP which is not assigned to a container (if you have no unassigned addresses, you’ll either need to pay for more or unbind one from an existing container first). Now bind that IP address to your newly created container:
bx ic ip-bind 1.2.3.4 abc1234
Next, you’ll need to create a user-provided service to stream the logs from your application(s) to Splunk:
bx cf cups splunk -l syslog://1.2.3.4:5140
Setting up a TCP listener within Splunk
Now we need to set up a data listener within Splunk to listen for data on TCP port
5140 (essentially, this is the same procedure as Takehiko’s original article).
Open the Splunk console in a browser using the URL (obviously, change the IP address for the one you picked above). Log in using the default username/password pair
admin/changeme (Splunk will then encourage you to immediately change the password, which you should).
On the home screen, click “Add Data” to add a data source:
Select “Monitor”:
Select “TCP/UDP” to add a TCP-based data listener:
Enter Port
5140 (the same port we exposed from the Splunk Docker container above):
rfc5424_syslog as the source type (which corresponds to the Splunk add-on we installed previously). You may find it easiest to type
rfc into the dropdown box to select this. Also, you may want to create a new index to index data from Bluemix. In this case, I’ve created one called
bluemix:
Review the settings you’ve entered and add the data listener.
Clone and push a demo application
In this article, we’ll clone a sample Node.JS application locally and then push it to Bluemix, so we can bind it to the user-provided service we just defined to use it to test the Splunk integration.
cd <some_temporary_directory>
git clone
cd get-started-node
curl > manifest.yml
Now edit manifest.yml it to change name and host to a unique name (e.g.
TestAppForSplunkAF (note that this name must be unique within the whole of Bluemix, which is why I use my initials to make this unique).
You also need to modify lines of the
server.js file to look like this:
var port = process.env.VCAP_APP_PORT || 8080;
(This ensures that the application will pick up the correct port number from the Bluemix deployed environment).
Now push the application up to Bluemix:
bx cf push
Bind that service to any application you wish:
bx cf bind-service TestAppForSplunkAF splunk
And restage each application:
bx cf restage TestApp
Testing the logging mechanism
Probably, just in the act of re-staging your application, you’ll already have generated some logs. However, to make things a bit more interesting, open the endpoint for your application (e.g. or similar, modify for the name of your application!) in a browser, and refresh it a few times.
Now, you should start to see your logging information appearing through Splunk. Assuming you set Splunk up as shown above, and created a new non-default index called
bluemix, you should simply be able to search for everything in the
bluemix index:
You should see some search results appear like this:
Further steps
The world is now your Oyster! You can use any standard Splunk searching mechanism to find logs.
Any questions or comments, please contact me @andrewferrier on Twitter.
Andrew is a Worldwide Bluemix Solution Architect, taking responsibility for end-to-end adoption of IBM Bluemix and providing guidance in the Bluemix Garage. Previously, he led the IBM Cloud Services Mobile Practice in Europe, working with IBM customers on the IBM MobileFirst platform. Andrew has presented extensively on Mobile, Dojo, REST, and Web APIs, contributing Intellectual Capital to the IBM and WebSphere communities, as well as writing two Redbooks, and numerous posts on IBM Mobile Tips ‘n’ Tricks ‘n’ Tricks and SOA Tips ‘n’ Tricks, both of which co-founded. When not in the Garage, Andrew can be found speaking at conferences, such as IBM InterConnect and the European WebSphere Technical Conference.
Recent Posts
- Promotion extended for IBM Cloud bare metal and virtual servers
- Deploying to IBM Cloud Private 2.1.0.2 with IBM Cloud Developer Tools CLI
- What the stats say about container development
- New fast and flexible Veeam backup solutions to IBM Cloud
- IBM Cloud Garage Method Field Guide
Archives
Deploying to IBM Cloud Private 2.1.0.2.. | https://www.ibm.com/blogs/bluemix/2016/11/using-splunk-docker-container-bluemix/ | CC-MAIN-2018-22 | refinedweb | 1,565 | 59.94 |
Hello C++ World!
At various times during our development cycle here in the C++ IDE, our developers start working on features that we believe can bring a lot of value to customers, but sometimes we just don’t have enough data on our own to figure out whether or not what we came up with works for our users on a broader scale.
Rather than wait until we’ve accounted for every scenario, we’ve decided to make an “Experimental” mechanism in VS2015 Update 1 RC (click here to download!) so that you can easily turn these features on and off when you decide to give them a try. This also alleviates the need to download an extension and restart Visual Studio! You can find this page under Tools –> Options –> Text Editor –> C/C++ –> Experimental (or do Ctrl+Q for Quick Launch and type in “experimental”).
Just to be clear: the features being listed as “experimental” does NOT mean “intentionally low-quality features shoved into the product with no improvement plans.” It simply means we weren’t completely sure if the current quality would sufficiently meet the broad needs of our customers. Think of them as “feature prototypes” as well as great opportunities for you guys try them out, give us feedback, and shape them into quality features that will help your development workflow!
Here’s a brief highlight of each of these experimental features:
- Enable New Database Engine – This should magically speed up database population, with the added effect of making all database operations faster (with no loss in accuracy) for operations such as Go To Definition and Find All References. (Just close and reopen your solution to apply the changes; no VS restart required!)
- Member List Dot-To-Arrow – Replaces ‘.’ with ‘->’ when applicable for Member List.
- Enable Extract Function – (Access via Quick Actions [Ctrl+.]) Extract selected code to its own function and replace code with a call to the new function.
- Enable Change Signature – (Access via Quick Actions [Ctrl+.]) Add, reorder, and delete parameters of a function and propagate the changes to all call sites.
- Enable Expand Scopes – Ever try to surround a code segment with braces, only to have the brace autocompleter insert that closing brace when you didn’t need it? Although admittedly a slight workflow change, you can select code and type an opening brace { to surround the selected code with { }.
- Enable Expand Precedence – Same as the previous, except with parentheses. Select code and type an opening parenthesis ( to surround the selected code with ( ).
That hyperlink at the bottom (“…find other…experimental features”) currently takes you to a search on VS Gallery for our team’s released VS extensions. When Update 1 RTW goes out, it will instead take you to this MSDN page listing all this info, along with specific extensions we think will be good for y’all to try out!
Speaking of “specific extensions good for y’all to try out,” be sure to try out our new C++ Quick Fixes extension (click to download)! This extension currently focuses on addressing fixes for the following scenarios:
- Add missing #include – Suggests relevant #include’s for unknown symbols in your code
- Add using namespace/Fully qualify symbol – Similar to the previous item, but for namespaces
- Add missing semicolon
- MSDN Help – Search MSDN for help on your error message(s)
You can either hover over a squiggle to get on that line.
If any of these features turns out to be awesome, we’ll remove its “experimental label” and put it into the product for good! Hope you’ll find them useful, and definitely, definitely leave us your feedback!
Best regards,
Gabriel Ha
Visual C++ PM
P.S. I know that this post and the nature of the topic will naturally bring up feature requests for other “experiments” for us to do. While I can’t make any promises, request away.
Join the conversationAdd Comment
On the 'other experiments'
Move a class in a namespace to a different namespace:
namespace Bob
{
Class Joe { … };
}
eg moved to Bob2::Joe
Currently there's just no easy way to do this, given that sometimes files will explicitly state Bob::Joe (easy to update), or have Joe forward declared in that namespace (possibly with other things that will remain in that namespace), or be used implicitly within an open Bob namespace (refactored to explicitly specify Bob2::Joe ?).
Moving this one class to a different, or new, namespace is much harder than just updating the name of the namespace.
Of course, if your architecture is well defined up front then this should be a fairly uncommon occurrence ;)
All these minor improvements are nice, but you are missing the most important and urgent need, and that is to fix the help system.
In old versions of Visual Studio you could press F1 on any word and you would instantly have the correct documentation in front of you. That does not work any more. More often than not you just get "Cannot find requested topic on your computer" (if you use Launch in Help Viewer) or are taken to a page "Welcome to Visual Studio 2015" (if you use Launch in Browser). Other times you end up on some topic completely unrelated to C++ development. Sometimes it does work and you find what you are looking for, but it is extremely slow (although this might be a problem only for us folk on the other side of the planet).
As it is now I have given up completely on using the build-in help. I use an off-line copy of cppreference.com to get C++ info. For any info on WIN32 or DirectX I go straight to Google. Needless to say, this is not ideal.
So, please, please, please. Fix the help system. Make it so that you can download the whole thing so that it is fast and work even when you do not have an internet connection. It would also help if you can filter the search results based on the project you are working on. When I work on a native C++ application I do not need info on Visual Basic or .net or whatever.
Absolutely! Still using VS2008 for main work here (need 2003/1998 C++ compatible for porting), and its so much more efficient than later versions.. Help in VS2008 can be local and gets you to the answers with one or two clicks.
Think they presume you will just use stack overflow for C++ questions! They don’t know how to do help properly anymore…..
If "Enable New Database Engine" is True, Execute "Change Signature" nothing happens.
Execute "Change Signature" and delete parameters, not delete comma.
example : "func(1, 2);" to "func(, 2);"
I've had all of them (except the database thing, obviously) for years thanks to Visual Assist and they're really handy. Specially, Extract Function and Change Signature help a lot with refactoring.
How about a convert enum to enum class tool, that inserts all the missing EnumName::'s?
Regarding "Member List Dot-To-Arrow – Replaces ‘.’ with ‘->’ when applicable for Member List", I wonder how many people really appreciate this kind of "help".
I cannot express how much I personally hate it when the editior autonomously interferes when I am writing code so I tend to disable such features very soon. Generally, when I open an editor, I want to be able to quickly open a file and start writing and compiling code. If syntax highlighting is on immediately when file is opened, nice but not necessary. All other tools including Intellisense, Visual Assist, Resharper and the likes should not interfere with their activities. When the tools have been loaded, initialized and are ready, I am happy to use them. But it drives me nuts when I open VS and then have to wait for 10 minutes (we have solutions containing 100s of projects) until the tools are loaded and their initialization (e.g. initializing code database, parsing new files, etc.) prohibits writing code and building software. I appericiated if Intellisense, as first of all, would not block the editor upon VS start (do the job in the background as much as possible). And second, it would be really great if it would not be so eager to autocomplete and provide help unless explicitly told to do so, because it is very important for the tools not to handicap the flow of thoughts and to impede typing. Otherwise, I disable them.
@Marko: I agree with you that the loading shouldn't be blocked and "stuff" being done in the background. However I don't agree with your second point. It's extremely helpful and beneficial to the workflow if e.g. the auto-complete pops up automatically without having to press any additional keys. E.g. just typing "f" and it will suggest "float" or class-names starting with "f". I would hate an additional keypress.
As C++ apps dev the most desirable VC++ feature is CX progressively being replaced by moderncpp (except when moderncpp and CX disagree on membership operator), though experimental editor support to correct misplaced membership "." by "->" as introduced by this post is welcome.
You guys should just buy VisualAssist and integrate it into VisualStudio.
While this isn't strictly C++ feature, please, please, please, make more operations non-blocking.
I don't want to have VS blocked just because it is checking out a folder from TFS, even though I am working with something completely different. Just block/warn if I try to access folder that is being checked out, don't make me wait for an unrelated operation.
I will second the suggest from Danny. Buy Visual Assist (or Whole Tomato) and integrate that into VS. Visual Assist has been able to do some things that are really needed in VS for 5 or 6 years now, and I'm wondering why you folks at MS can't do things like "find all uses of this symbol" (instead of just doing a text search which can return thousands of useless hits).
I agree with Howard, the #1 annoyance is Find All References simply doing a text search and returning comments and symbols from unrelated classes.
These seem like nice features. Thank you. I may go against the grain here but I actually don't like the automatic conversion of . to -> because it will likely introduce bad habits, in my case. I don't think it would measurably increase productivity, anyway. What would be nifty would be a way to automatically convert them all when a pointer variable was changed to a reference variable or vice versa. I hate having to get change them all when I decide to use a reference instead of a pointer.
@rog i like the idea and that sounds like a nice addition to clang-modernize (clang.llvm.org/…/clang-modernize.html) as well ;-)
There's a bug in Expand Scope. It gets confused by macros:
int something, somethingelse;
// try and use the scope tool from here….
something = somethingelse = 1;
if (something == somethingelse)
{
#ifdef SOMETHING
somethingelse++;
#endif
}
else
{
somethingelse–;
}
// …down to here
…currently has this result:
int something, somethingelse;
// try and use the scope tool from here….
{
something = somethingelse = 1;
if (something == somethingelse)
{
#ifdef SOMETHING
somethingelse++;
#endif
}
else
{
somethingelse–;
}
}
// …down to here
Too much already. Any is too much, but this is too much too much.
1) Something like VisualAssist's 'List methods in current file' would be great.
2) In a similar vein, making Edit.NavigateTo prioritise matches in the current file would be nice.
3) Change Signature isn't working for me either right now. But I'm not a fan of the way it's been implemented. Instead of a dialog I'd really love to be able to edit the signature in-situ and then have the tool attempt to make those changes. The option to implement your changes could even live in the LightBulb system.
Time to go through replies one by one =P
@Ninj
I took the time to actually talk to my devs and design that feature, but because of the perceived infrequency of the feature (no matter how tedious) it probably won't get worked on for a while. I have, however, put the design plans into a work item on our backlog, and I enjoyed the mental exercise in designing the feature.
If you come across the scenario in the future, I'd recommend running a Find All References on the class name (if you're not already doing that already) and using that list to make sure you cover all your scenarios. We'd pretty much be doing the same thing in such a feature but just automated to take out the tedium >.< (I guess that's kinda what refactoring is all about.)
@Barnett
I got a similar piece of feedback from another customer via Send-a-Smile/-Frown (yes, we do read everything that goes through there =P) on version issues (i.e. F1 in VS2015 would take you to the VS2013 page) and reported it to our MSDN contacts, who then did some kinda overhaul on the system so at least the version issue should be fixed now.
Since that seems to only address part of your issues, can you give me 2-3 examples of documentation that isn't working for you when you hit F1, and I'll get in touch with my MSDN contact.
We've definitely gotten requests for better offline support. Let me also ask my MSDN contact if there are any solutions for that, and I'll let you know what he says.
The MSDN help feature in the extension mentioned in my post might be able to provide a workaround in the meantime. It will perform a raw MSDN search based on the squiggled error in your code, and it does not use the same (I suppose broken) mechanism as F1.
Let me know, and thanks for your feedback and bringing the issue to our attention.
@ryou
Thanks for the catch! I'm logging both issues as bugs.
@rog
Thanks for the suggestion! Out of curiosity, do you know of any existing tools that currently have this feature? Would be interested in seeing how they choose to handle the scenario.
@Marko Filipović
Thanks for sharing your sentiments. Regarding this comment:
"…it drives me nuts when I open VS and then have to wait for 10 minutes (we have solutions containing 100s of projects) until the tools are loaded and their initialization (e.g. initializing code database, parsing new files, etc.) prohibits writing code and building software."
I found it surprising, as while admittedly writing code can be laggy when a giant solution is initially opened, we shouldn't (at least, any longer =P) have anything preventing users from writing code into the editor. I'd love to follow up on this with you if you can provide any specific scenarios (and/or repros). Contact me at gaha at microsoft dot com if you're available to do so.
@Xarn
My realm of expertise isn't in TFS and source control, but if there are any C++ editor features whose operations are frequently unexpectedly blocking you, do let me know (gaha at microsoft dot com). We do want to ensure that operations used frequently are done in the background or are cancel-able.
@Howard
@gdsuing
I agree that there are a lot of improvements that we can make with Find All References. It does disambiguate whether or not the "text searches it found" are actual matches to your symbol (there are icons that will incrementally populate in the window implicitly containing that info), but yes, much room for improvement.
@Box
What is the result that you're expecting to see? (can you mark the culprit line[s] with a text arrow or comment?)
@Box
Thanks for the suggestions! The Change Signature one is a neat one for sure.
@Gabriel Ha, you asked for examples of the build-in help not working. As I said, I no longer even try to use the build-in help, but doing a few quick tests:
Pressing F1 on the word "INVALID_HANDLE_VALUE" takes me to a page titled "WinVerifyTrust function".
What?!? This is for offline help. The online help takes me to slightly different page titled: "WinVerifyTrustEx function".
Equally unhelpful.
Pressing F1 on the word "HANDLE" takes me directly to a page titled "CAtlTemporaryFile::operator HANDLE".
This is for the offline help. The online help takes me to a much more reasonable page, but I have to wait about 10 seconds for that, presumably because I live on the wrong side of the planet.
Pressing F1 on "WIN32_LEAN_AND_MEAN" just gets me a "Cannot find requested topic on your computer" in offline help.
Online help takes me to a page titled "Welcome to Visual Studio 2015". Thanks for nothing.
Pressing F1 on "IDXGIAdapter1". This time it works and I get the correct help page. But I had to wait 10 seconds for it to come up even in the offline help. I also get a message saying "You are viewing online content. The topic is not available on your computer or in a book that you can download."
Why not?!?
I don't have access right now to an old version of Visual Studio, but I am almost 100% sure all of these would have worked before. How did it all get so terribly broken?
All these new Editor Tools you are building are nice to have, but without quick and easy access to the documentation it is very difficult to be productive.
More examples of F1 help blindly picking a textual match without weighting the importance of the topic, nor providing alternatives in case it guessed wrong.
F1 "string" takes you to
Windows desktop applications> Develop> Desktop technologies> System Services> COM>
Microsoft Interface Definition Language (MIDL)> MIDL Language Reference> string
F1 "vector" takes you to
Windows desktop applications> Develop> Desktop technologies> Graphics and Gaming>
DirectX Graphics and Gaming> Classic DirectX Graphics> Direct3D 9 Graphics>
Reference for Direct3D 9> X File Reference (Legacy)> X File Format Reference> Templates> Vector
F1 "map" takes you to
Windows desktop applications> Develop> Desktop technologies> Diagnostics> Windows Events>
Windows Event Log> Windows Event Log Reference> EventManifest Schema> EventManifest Schema Elements> map (BitMapType) Element
@Barnett
Thanks for the repro cases — I've reported them to the MSDN team
@AndrewDover
I couldn't get yours to repro, either by typing in std::"blah" or even just "blah"; I get taken to the appropriate STL page on MSDN (though, I note, to the VS2013 version of the page, which I reported). Follow up with me at gaha at microsoft dot com so we can investigate further; thanks!
Have to chime in +1 on the MSDN offline being badly broken. Nearly every Win32 API I try will end up in random locations of the documentation much the same as @Barnett reports. I will not use online doc setting. MSDN help viewer used to be sooooo much better.
>Enable Change Signature – (Access via Quick Actions [Ctrl+.]) Add, reorder, and delete parameters of a function
"Create definition" feature in VS2015 RTM ignores SAL annotations in a declaration. Do the new function ignore it too?
@Gabriel Ha, a few more simple WIN32 examples with "Help Preference" set to "Launch in Help Viewer":
Things that work:
::CreateSemaphore()
::WaitForSingleObject()
::CreateEvent()
::InitializeCriticalSection()
Things that does not work:
::CloseHandle() -> Takes you to some "IWorkerThreadClient::CloseHandle()" page.
::SetEvent() -> Takes you to some "CEvent::SetEvent()" page.
::ResetEvent() -> Takes you to some "CEvent::ResetEvent()" page.
CRITICAL_SECTION -> Takes you to some or other "critical_section Class" page.
Things that work, but is only available online:
(ie "You are viewing online content. The topic is not available on your computer or in a book that you can download.")
::ReleaseSemaphore()
::QueryPerformanceCounter(), ::QueryPerformanceFrequency()
LARGE_INTEGER
::DeleteCriticalSection()
The worst of these is "CRITICAL_SECTION". It took about 20 seconds to take me to the wrong page. And why does InitializeCriticalSection() work offline, but for DeleteCriticalSection() you have to be online???
Some of these work better with "Help Preference" set to "Launch in Browser", eg SetEvent(), but others do not work anywhere, eg CloseHandle().
@AndrewDover, I also remember some time ago not even "string" and "vector" would work. But they are working for me now. I recently did a clean install after a hard disk failure, so maybe this is something that got fixed.
@Gabriel — if I want a text search, I can do a control-F. That actually works pretty well. *IF* I want a text search.
I can see that there is a little icon showing the difference between "confirmed reference" and text-match. So, how do I make the text-match-only entries just go away so that I can see only the actual references in context?
The whole reason for the existence of Whole Tomato is a bunch of stuff that MS left out of VS.
@Brigadir
Unfortunately, yes, it "ignores" it as well. I will note it as an improvement we can make. Thanks!
@Howard
It's admittedly embarrassing that there's no way to currently filter out text-only results (or filter at all on that unfortunately antiquated UI). We are planning to make severe usability improvements to Find All References, and I very much look forward to when it happens.
Thanks for the list of F1 issues — there is a known issue with online F1 help, for which a fix is in the works and will take effect Nov 19 when we publish the VS Update 1 docs. The root cause of those problems was a migration from one set of doc tools to another, which broke some of the metadata tagging on the topics that F1 relies on. I'll look at each of your other repro cases and see what the root cause is, and post back here when I have more info.
@Howard
I neglected to mention that, even though there's still no filtering on the Find All References window, there is a "go to next/previous resolved entry" on the toolbar (and it's a normal command so you can assign a shortcut key to them).
But like I said, I look forward to that feature being severely improved.
@Barnett, I was able to reproduce the F1 issues and I agree there are definitely problems with the Win32 API F1 support and the offline help books. I'm reaching out to the Windows content publishing team for more information. Some of the problems appear to be caused by out-of-date or incorrect metadata, but also the offline help books themselves might be missing some of the content that they should have. For example, I did not find the ::CloseHandle function in the offline help book, either in the VS 2013 offline book or the VS 2015 offline book. Offline F1 returns the best match among the locally available help books, which is why it gives a different CloseHandle method. The correct topic is present as expected in its TOC location online, however, it's not being found because the search stops when it find the local "match". In the case of ::ReleaseSemaphore, there's no offline help match, so it goes online and returns the correct topic. In either case, the correct behavior would occur if the correct local topic was there. I'll post more information once I have more from the relevant teams. Unfortunately for these scenarios to work correctly, a lot of moving parts have to be in place from version to version, and if any one of them is incorrect, F1 will fail.
I was reminded by Gabriel & co to download the local help files, and "vector", "map", and "string" now go to useful
places. Thanks!
Enable Expand Scopes, Enable Expand Precedence, and Fully Qualify Symbol, all sound amazingly useful. I spend far too much time doing those manually, and they'll make my life easier.
The C++ Quick Fixes extension is closed source? Eh?
@Gabriel Ha,
Sorry, the tabs were stripped from my first post so it didn't make any sense at all…
I'll try again with spaces, see below.
If you try to use the scope tool on this little snippet:
int something, somethingelse;
// try and use the scope tool from here….
something = somethingelse = 1;
if (something == somethingelse)
{
#ifdef SOMETHING
somethingelse++;
#endif
}
else
{
somethingelse–;
}
// …down to here
…it seems to get confused by the macro and messes up the indentation on the close brace that follows it, I've marked it this time so hopefully it's clearer:
//…currently has this result:
int something, somethingelse;
{
something = somethingelse = 1;
if (something == somethingelse)
{
#ifdef SOMETHING
somethingelse++;
#endif
} // <—- this closing brace is indented one stop too far to the left
else
{
somethingelse–;
}
}
The expand scope tool seems to override the 'Automatic Brace Completion' setting, and I'm one of those strange folks that quite like that feature :0)
So, it would be great if the expand scope tool automatically inserted a closing brace when typing an opening brace, if there is no selection. But only if 'Automatic Brace Completion' is also turned on, so as not to annoy everyone that hates that feature.
Re my request above, to have expand scope insert closing braces if there is no selection….
The old auto brace completion seems to be working again, and existing happily alongside the experimental expand scope. Not sure what happened, maybe I nudged it back into life when I tried toggling the expand scope off and then back on again.
Like Brigadir already mentioned. For us, SAL support is also very important!
thx,
Vertex
@Box
Thanks for the update. I tried it again, and the brace seems to be positioned fine. Perhaps we have some differences in our formatting settings? I'd be glad to help lock this down; contact me at gaha at microsoft dot com if you're interested.
Awesome. Thanks
Expand scope is somewhat buggy, or at least it is annoying half of the time. It expands the whole row instead of the selected text. For example, if I select parameters for a function call try to change them to initializer list, it expends the whole row and not the selected parameters.
@Bob
Thanks for the note! I'll add it to our to-do list for that feature
@Gabriel Ha, thanks for the offer. I can see why you can't reproduce what I'm seeing, it's down to my post getting mangled again – this time the problem is the lines of code have ended up double spaced. For me the problem doesn't show up if I copy and paste straight from my post, but if I remove those extra rogue CRs I can still reproduce the problem. You need a code friendly comment system :0)
I'll email you the code snippet
The new database engine apparently disables ctrl+space from global-scope. So I need put :: before code to see global-scope list.
On status bar the message is: "IntelliSense: 'No additional information available' (See 'Troubleshooting IntelliSense in C++ Projects' for further help.)".
And with :: the message is: "Ready".
When there is a scope operator, it works well, but when there isn't a scope-operator ,nothing happens.
@André
We believe the problem with CTRL+space not activating Member List in unqualified scope is not related to the new database engine, but we were never able to reproduce it in our environment. We suspect however that it might be related to some changes in code snippets. Could you try setting "Disable Member List Code Snippets" to True in Tools > Options > Text Editor > C/C++ > Advanced and checking if CTRL+space works again in all contexts? If so, the fix is ready and will be available in the next release of Update 1.
Please add "navigate through spaces as if they were tabs" option. There's an extension for this (github.com/…/tabsanity-vs), but it's not perfect and it's not easy to fix it.
When spaces are used for indentation I'd like backspace/delete/cursor move to indentation levels instead of individual spaces.
@MikeK
Interesting suggestion; we'll keep that in mind!
@Lukasz
I'm now using Update 1 and everything (including new database) works perfectlly. Nothing to complain about.
@Gabriel Ha
When Jim Springfield or another person will write the Part 3 of Intellisense History?
Like as this post: 2007/12/18/intellisense-history-part-1
@André Poffo
Thanks for the feedback!
I'll pass along the request to Jim ;)
I'm leaving the Member list Dot-to-Arrow Refactor false, as a reminder to me to carry the assumption about the class member with me in my coding, and let the compiler check my thinking of how long my object will be around and if I've taken care of possible leaks. But I understand C# programmers not liking arrows much!
H there’s a flaw in the feature “Member List Dot-To-Arrow”. It doesn’t work for smart pointers (which are heavily used these days). Visual Assist fixed this by adding a feature “Convert dot to-> if operator -> is overloaded”, please do the same. Thanks:) | https://blogs.msdn.microsoft.com/vcblog/2015/11/03/introducing-c-experimental-editor-tools/ | CC-MAIN-2018-09 | refinedweb | 4,860 | 61.06 |
I would guess the instruction inside the loop is being optimized out since it doesn't result in anything.
Printable View
I would guess the instruction inside the loop is being optimized out since it doesn't result in anything.
woah woah, actually debug mode initializes the values in all cases where its not initialized. Invalid test.
Not exactly.... The debugger tries to remove anything that will result in undefined behavior in a way that is still undefined while easier to spot as a programmer. It actually makes spotting errors so much easier.
But I agree that it would be better with Release (I just had trouble convincing the compiler to stop optimizing the entire code away).
Here's another version that can be compiled in Release:
The amazing results I get from this are:The amazing results I get from this are:Code:
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
DWORD dwTick1 = GetTickCount();
for (int i = 0; i < 100; i++)
{
char x[100000];
strcpy(x, "This is a test\n");
cout << x;
}
DWORD dwTick2 = GetTickCount();
DWORD dwTick3 = GetTickCount();
for (int i = 0; i < 100; i++)
{
char x[100000] = {};
strcpy(x, "This is a test\n");
cout << x;
}
cout << "Took " << dwTick2 - dwTick1 << " ms.\n";
cout << "Took " << GetTickCount() - dwTick3 << " ms.\n";
}
Took 203 ms.
Took 188 ms.
Took 234 ms.
Took 235 ms.
Took 281 ms.
Took 281 ms.
Took 172 ms.
Took 375 ms.
Took 187 ms.
Took 234 ms.
Took 375 ms.
Took 250 ms.
These results can be unpredictable and not 100% accurate due to the nasty work of the scheduler, but it shows that they take about roughly the same amount of time.
It's not quite as expensive as you would have everyone believe.
Ah yes... but it is. I base this on experience with clearing out stack space in an embedded system. If you would like I could certainly continue to dispute your "infallible" test program more. Or you can just accept that this is one of those stalemates we always end up at after dozens of posts back and forth with no change in opinion in sight.
It indeed seems that in debug mode looking after uninitialized things is more expensive. In optimized release mode the uninitialized version is slightly faster (and it doesn't seem that MingW optimizes anything out).
Took 4485 ms.
Took 4562 ms.
However the stack is usually not just one variable. Try replacing x with x[10] and 0 with {0}.
Took 4485 ms.
Took 33921 ms.
Heh.. I took it as being directed at me. Not all processors use out of order execution, by the way. Which is one reason that your zeroing may seem completely benign.
Of course, some systems may not be equal in terms of performance for this test. It is by no means a guarantee that it isn't expensive and not real proof, but it is a small test that proves that zeroing may not be as expensive as you claim, at least not on all platforms.
It varies from system to system, but on PCs, I can pretty certainly say it's viable to do so without a big overhead. It's just a matter of the OS builders not choosing to "do so." | http://cboard.cprogramming.com/cplusplus-programming/107792-local-stack-variables-2-print.html | CC-MAIN-2014-41 | refinedweb | 545 | 75.71 |
What are Generics and how can I use them?
Created May 8, 2012
One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their toolbox for years using the STL. A generic type is defined using one or more type variables with it's contained methods using that type variable as a place holder to mark a parameter or return type. For instance the interface List has now been defined as.
public interface List<E>{ public add(E e); Iterator<E> iterator(); } public interface Iterator<E>{ E next(); boolean hasNext(); }
Type Safe Collections
So you might ask. What are Generics and why should I use them? Generics are a way to restrict a data structure to hold only a specific type thus providing compile time type checking. One of the added bonuses is that it is no longer necessary to cast a returned Object to a specific type because the compiler is aware of what type is being held by the Collection and what type is to be returned.
Set s = new SortedSet(); s.add(new String("Java")); String j = (String) s.get(0); // cast required; // java 5 Set<String> s = new SortedSet<String>(); s.addElement(new String("String Type")); String s = s.get(0); // no cast required!
Having a type safe system not only obviates the need to cast to a specific type but shields the programmer against miss-casting or casting to an unrelated type at runtime.
String s = "Java, write once run anywhere"; List l = new ArrayList(); l.add(new String("Java")); Integer i = (Integer)l.get(0); // Runtime exception! ClassCastException! // Using Generics the compiler catches String s = "Java. Write once run anywhere!"; List<String> l = new ArrayList<String>(); l.add(new String("Java")); Integer i = l.get(0);
Generics and Subtyping
Generics do not share some of the things that are commonly held true in the Java language and one of them is subtyping. One would assume the following perfectly legal since it is true that Object is a supertype of String. But the following is in fact illegal and will cause a compile time error.
List<Object> l = new ArrayList<String>();
As a rule. If X is a superclass or superinterface of Y and E is a generic type declaration then it not the case that E<X> is a supertype of E<Y>. So if E<Object> is not a super type of E<String> then what is the super type of E<String>? Read on and find out!
Wild Cards
Wild Cards represent what is called "the unknown type". Essentially they can be thought of as the supertype of any Collection. Wildcards allow some flexibility in certain situations where it is needed that a type be abstracted out. For instance what if we define the following method, printSet(Collection<Object> x). We just saw in the previous example that E<Object> is not the super type of E<String> or any other type for that matter. In this case we can change the printSet's parameter to Collection<?>. This allows us to pass in E<X> where X is any type.
public void printElements(Collection<?> c){ for(Object o: c){ System.out.println(o); } }
When working with wildcards it is always legal to read and assign the contents to an Object type
List<String> l = new ArrayList<String>(); l.add(new String("Java")); Object o = getElement(l, 0); // legal public Object getElement(List<?> l, int index){ Object o = null; try{ o = l.get(0); }catch(IndexOutOfBoundsException e){ //....... } return o; }
assigning values is another matter. The add() method takes an argument of type E which is the type that the Collection is to hold. Any type wishing to be added to the Collection would have to be of the same type. Since<?> represents an unknown type it is impossible to determine what the type parameter of the collection represents.
Bounded Wildcards
A Bounded Wildcard allows as type to be constrained. Bounded Wildcards are useful when there is some type of partial knowledge about the type arguments. While it is still illegal to try and add an element to a unknown Collection with a bounded type they come in handy in other situations. One use is to be able to pass not only types into a method but sub-types also. In doing this we are able to implement polymorphic behavior.
import java.util.*; class Printer{ public void print(String s){ for(int i = 0; i < s.length(); i++){ System.out.print(s.charAt(i)); } } } class ReversePrinter extends Printer{ public void print(String s){ for(int i = s.length() - 1 ; i >= 0; i--){ System.out.print(s.charAt(i)); } } } public class G{ public static void main(String[] args){ String s = "Nothing like a good cup of Java in the morning!"; List<Printer> l = new ArrayList<Printer>(); l.add(new Printer()); printElements(l,s); List<ReversePrinter> rl = new ArrayList<ReversePrinter>(); rl.add(new ReversePrinter()); printElements(rl,s); } public static void printElements(List<? extends Printer> l, String s){ Printer printer = l.get(0); printer.print(s); System.out.println(); } } | https://www.jguru.com/print/faq/view.jsp?EID=1251440 | CC-MAIN-2020-45 | refinedweb | 864 | 66.94 |
-
Constructing a Simple Graph with Boost
If you have to code a graph theory algorithm, you can either build the graph data structures yourself, or use a library. The one I’m using for this article is found in the Boost library. Let’s take a look at a first sample to show you how to use the Boost library’s support for graph theory.
In general, a graph can be represented in a computer as a set of vertices and a set of edges connecting the vertices; the edges are simply pairs of vertices. Further, each vertex and each edge can have additional data attached to it, such as a number representing a weight, in the case of edges. This is essentially how Boost’s Graph library works.
The Boost Graph library exists as templates, which means that you create your own classes and types based on the templates. However, the parameters for the templates all have defaults, so you can create a graph easily without having to do any customization.
Here’s a short piece of code that demonstrates creating a graph and inserting vertices and edges into the graph. This code compiles completely, but it doesn’t really do much other than create the graph:
#include <iostream> #include <stdlib.h> #include <boost/graph/adjacency_list.hpp> using namespace boost; int main(int argc, char *argv[]) { adjacency_list<> mygraph; add_edge(1, 2, mygraph); add_edge(1, 3, mygraph); add_edge(1, 4, mygraph); add_edge(2, 4, mygraph); return 0; }
The mygraph variable is the graph itself. The type is adjacency_list, which is the fundamental graph template type in the Boost Graph library. I used the defaults for the parameters; thus, the parameters are an empty set with angle brackets (<>).
The add_edge function is a template helper function for adding items to the graph. To use it, you pass the values for two vertices. If the vertices don’t already exist in the graph, they’ll be added; then the edge connecting the two vertices will be added. Thus, the preceding code creates a graph with four vertices, numbered 1, 2, 3, and 4, with edges connecting 1 and 2, 1 and 3, 1 and 4, and finally 2 and 4.
This is just a basic example. To create more complex graphs, you’ll need to define more data to associate with your edges and vertices. I take up that task in the next section. | http://www.informit.com/articles/article.aspx?p=673259&seqNum=4 | CC-MAIN-2019-18 | refinedweb | 402 | 69.82 |
How to drag & drop rows within QTableWidget
Hello all,
I want to drag & drop rows in QTableWidget to change order of rows in the table.
I want only move whole rows, not overwrite or delete.
I've tried
@
table->setDragDropOverwriteMode(false);
table->setDragEnabled(true);
table->setDragDropMode(QAbstractItemView::InternalMove);
item->setFlags(item->flags() & ~(Qt::ItemIsDropEnabled));
@
but it doesn't fully enable to move a row.
My question is: is it possible to get requested behavior just by correct setting of some flags or is it necessary to inherit and re-implement something?
Working example is appreciated.
Thanks in advance,
Jarda
The example below allows you to move rows by calling "setMovable(true)": on the header. Does it give you the behavior you want?
@
#include <QtGui>
int main( int argc, char** argv ) {
QApplication a( argc, argv );
QTableWidget table(4,4);
for(int row =0;row<4;row++)
for(int col = 0;col<4;col++)
{
QTableWidgetItem *item = new QTableWidgetItem(QString("Row%1 Col%2").arg(row).arg(col));
item->setFlags(item->flags() | Qt::ItemIsSelectable);
table.setItem(row,col,item);
}
table.verticalHeader()->setMovable(true);
table.show();
return a.exec();
}
@
Thank you for reply. but I also need to change the number of moved row. When I drag the row number 5 to first row I also need it to become row number 1 and reorder the rest (not only the row number 5 displayed as first).
I'm not sure if that is possible within QTableWidget. If you do it with QTableView and a custom model, you would overwrite the drag / drop stuff in the model.
Thank You Gerolf for reply. Can you please give me a hint (or sample code) how to implement it with custom model?
If you look inside the "qt docs": there ios a chapter on model view and also on dnd with MVD. I propose you start reading there.
I wanted the same functionality for my app. So I searched through internet and didnt find anything. So I had to do it.
So, you can do it with QTableWidget by using the cellEntered(int,int); then takeItem(row, col) and then setItem()...
@connect(ui->tableWidget, SIGNAL(cellEntered(int,int)), this, SLOT(cellEnteredSlot(int,int)));@
@void MainWindow::cellEnteredSlot(int row, int column){
int colCount=ui->tableWidget->columnCount(); int rowsel; if(ui->tableWidget->currentIndex().row()<row) rowsel=row-1; //down else if(ui->tableWidget->currentIndex().row()>row) rowsel=row+1; //up else return; QList<QTableWidgetItem*> rowItems,rowItems1; for (int col = 0; col < colCount; ++col) { rowItems << ui->tableWidget->takeItem(row, col); rowItems1 << ui->tableWidget->takeItem(rowsel, col); } for (int cola = 0; cola < colCount; ++cola) { ui->tableWidget->setItem(rowsel, cola, rowItems.at(cola)); ui->tableWidget->setItem(row, cola, rowItems1.at(cola)); }
}@
Warning: I think theres a bug.
Although it works fine by clicking and holding the left mouse button and moving mouse up or down, it also works with Mouse WHEEL Scroll.
I have not figure it out yet on how to check if mouse wheel was triggered so not to move selected row.
The doc says:
bq. This signal is only emitted when mouseTracking is turned on, or when a mouse button is pressed while moving into an item.
BUT when you scroll the mouse wheel is not a mouse button press action.
So I think its a BUG. Should I submit it? | https://forum.qt.io/topic/9692/how-to-drag-drop-rows-within-qtablewidget | CC-MAIN-2017-43 | refinedweb | 551 | 66.74 |
Tax
Have a Tax Question? Ask a Tax Expert
Welcome to Just Answer. I am here to help you resolve your tax and finance concerns. Please feel free to ask anytime you need extra help.
You will be sent the refund. However, if it is be a paper check it will be made payable to him unless you provide a copy of his death certificate and documentation stating that you are the executor of his estate. If you fail to do this the check will be payable to your son. You may, even then, be able to deposit it into your bank account by bringing the paperwork noted above and the check to the bank.
An easier way is to file the return electronically. Doing this you will be able to indicate that the payment should be directly deposited into your account. Free software that will enable you to file the return electronically is available at a number of sites, however, the one I personally recommend is
Either way, be sure you retain a copy of the return (and paper check if that is your preference) for your records. Then, if you are ever questioned, you can substantiate that you did no wrong.
Sir ,
I followed your advise to go to TAXACT.Com However they are not taking any 2010
unitil the 2011 information is available . JUST SO YOU !! | http://www.justanswer.com/tax/5rwg6-son-passed-away-april-told-send.html | CC-MAIN-2016-30 | refinedweb | 229 | 72.97 |
The Tkinter module (“Tk interface”) is the standard Python interface to the Tk GUI toolkit from Scriptics (formerly developed by Sun Labs).
Both Tk and Tkinter are available on most Unix platforms, as well as on Windows and Macintosh systems. Starting with the 8.0 release, Tk offers native look and feel on all platforms.
Tkinter consists of a number of modules. The Tk interface is provided by a binary extension module named _tkinter. This module contains the low-level interface to Tk, and should never be used directly by application programmers. It is usually a shared library (or DLL), but might in some cases be statically linked with the Python interpreter.
The public interface is provided through a number of Python modules. The most important interface module is the Tkinter module itself. To use Tkinter, all you need to do is to import the Tkinter module:
import Tkinter
Or, more often:
from Tkinter import *
The Tkinter module only exports widget classes and associated constants, so you can safely use the from-in form in most cases. If you prefer not to, but still want to save some typing, you can use import-as:
import Tkinter as Tk
[comment on/vote for this article] | http://effbot.org/tkinterbook/tkinter-whats-tkinter.htm | crawl-002 | refinedweb | 204 | 54.63 |
Data Analysis and Visualization with pandas and Jupyter Notebook in Python 3.
In this tutorial, we’ll go over setting up a large data set to work with, the
groupby() and
pivot_table() functions of
pandas, and finally how to visualize data.
To get some familiarity on the
pandas package, you can read our tutorial An Introduction to the pandas Package and its Data Structures in Python 3.
Prerequisites
This guide will cover how to work with data in
pandas.
Setting Up Data
For this tutorial, we’re going to be working with United States Social Security data on baby names that is available from the Social Security website as an 8MB zip file.
Let’s activate our Python 3 programming environment on our local machine, or on our server from the correct directory:
- cd environments
- . my_env/bin/activate
Now let’s create a new directory for our project. We can call it
names and then move into the directory:
- mkdir names
- cd names
Within this directory, we can pull the zip file from the Social Security website with the
curl command:
- curl -O
Once the file is downloaded, let’s verify that we have all the packages installed that we’ll be using:
numpyto support multi-dimensional arrays
matplotlibto visualize data
pandasfor our data analysis
seabornto make our matplotlib statistical graphics more aesthetic
If you don’t have any of the packages already installed, install them with
pip, as in:
- pip install pandas
- pip install matplotlib
- pip install seaborn
The
numpy package will also be installed if you don’t have it already.
Now we can start up Jupyter Notebook:
- jupyter notebook
Once you are on the web interface of Jupyter Notebook, you’ll see the
names.zip file there.
To create a new notebook file, select New > Python 3 from the top right pull-down menu:
This will open a notebook.
Let’s start by importing the packages we’ll be using. At the top of our notebook, we should write the following:
import numpy as np import matplotlib.pyplot as pp import pandas as pd import seaborn
We can run this code and move into a new code block by typing
ALT + ENTER.
Let’s also tell Python Notebook to keep our graphs inline:
matplotlib inline
Let’s run the code and continue by typing
ALT + ENTER.
From here, we’ll move on to uncompress the zip archive, load the CSV dataset into
pandas, and then concatenate
pandas DataFrames.
Uncompress Zip Archive
To uncompress the zip archive into the current directory, we’ll import the
zipfile module and then call the
ZipFile function with the name of the file (in our case
names.zip):
import zipfile zipfile.ZipFile('names.zip').extractall('.')
We can run the code and continue by typing
ALT + ENTER.
Now if you look back into your
names directory, you’ll have
.txt files of name data in CSV format. These files will correspond with the years of data on file, 1881 through 2015. Each of these files follow a similar naming convention. The 2015 file, for example, is called
yob2015.txt, while the 1927 file is called
yob1927.txt.
To look at the format of one of these files, let’s use Python to open one and display the top 5 lines:
open('yob2015.txt','r').readlines()[:5]
Run the code and continue with
ALT + ENTER.
Output['Emma,F,20355\n', 'Olivia,F,19553\n', 'Sophia,F,17327\n', 'Ava,F,16286\n', 'Isabella,F,15504\n']).
With this information, we can load the data into
pandas.
Load CSV Data into
pandas
To load comma-separated values data into
pandas we’ll use the
pd.read_csv() function, passing the name of the text file as well as column names that we decide on. We’ll assign this to a variable, in this case
names2015 since we’re using the data from the 2015 year of birth file.
names2015 = pd.read_csv('yob2015.txt', names = ['Name', 'Sex', 'Babies'])
Type
ALT + ENTER to run the code and continue.
To make sure that this worked out, let’s display the top of the table:
names2015.head()
When we run the code and continue with
ALT + ENTER, we’ll see output that looks like this:
Our table now has information of the names, sex, and numbers of babies born with each name organized by column.
Concatenate
pandas Objects
Concatenating
pandas objects will allow us to work with all the separate text files within the
names directory.
To concatenate these, we’ll first need to initialize a list by assigning a variable to an unpopulated list data type:
all_years = []
Once we’ve done that, we’ll use a
for loop to iterate over all the files by year, which range from 1880-2015. We’ll add
+1 to the end of 2015 so that 2015 is included in the loop.
all_years = [] for year in range(1880, 2015+1):
Within the loop, we’ll append to the list each of the text file values, using a string formatter to handle the different names of each of these files. We’ll pass those values to the
year variable. Again, we’ll specify columns for
Name,
Sex, and the number of
Babies:
all_years = [] for year in range(1880, 2015+1): all_years.append(pd.read_csv('yob{}.txt'.format(year), names = ['Name', 'Sex', 'Babies']))
Additionally, we’ll create a column for each of the years to keep those ordered. This we can do after each iteration by using the index of
-1 to point to them as the loop progresses.
all_years = [] for year in range(1880, 2015+1): all_years.append(pd.read_csv('yob{}.txt'.format(year), names = ['Name', 'Sex', 'Babies'])) all_years[-1]['Year'] = year
Finally, we’ll add it to the
pandas object with concatenation using the
pd.concat() function. We’ll use the variable
all_names to store this information.
all_years = [] for year in range(1880, 2015+1): all_years.append(pd.read_csv('yob{}.txt'.format(year), names = ['Name', 'Sex', 'Babies'])) all_years[-1]['Year'] = year all_names = pd.concat(all_years)
We can run the loop now with
ALT + ENTER, and then inspect the output by calling for the tail (the bottom-most rows) of the resulting table:
all_names.tail()
Our data set is now complete and ready for doing additional work with it in
pandas.
Grouping Data
With
pandas you can group data by columns with the
.groupby() function. Using our
all_names variable for our full dataset, we can use
groupby() to split the data into different buckets.
Let’s group the dataset by sex and year. We can set this up like so:
group_name = all_names.groupby(['Sex', 'Year'])
We can run the code and continue with
ALT + ENTER.
At this point if we just call the
group_name variable we’ll get this output:
Output<pandas.core.groupby.DataFrameGroupBy object at 0x1187b82e8>
This shows us that it is a
DataFrameGroupBy object. This object has instructions on how to group the data, but it does not give instructions on how to display the values.
To display values we will need to give instructions. We can calculate
.size(),
.mean(), and
.sum(), for example, to return a table.
Let’s start with
.size():
group_name.size()
When we run the code and continue with
ALT + ENTER, our output will look like this:
OutputSex Year F 1880 942 1881 938 1882 1028 1883 1054 1884 1172 ...
This data looks good, but it could be more readable. We can make it more readable by appending the
.unstack function:
group_name.size().unstack()
Now when we run the code and continue by typing
ALT + ENTER, the output looks like this:
What this data tells us is how many female and male names there were for each year. In 1889, for example, there were 1,479 female names and 1,111 male names. In 2015 there were 18,993 female names and 13,959 male names. This shows that there is a greater diversity in names over time.
If we want to get the total number of babies born, we can use the
.sum() function. Let’s apply that to a smaller dataset, the
names2015 set from the single
yob2015.txt file we created before:
names2015.groupby(['Sex']).sum()
Let’s type
ALT + ENTER to run the code and continue:
This shows us the total number of male and female babies born in 2015, though only babies whose name was used at least 5 times that year are counted in the dataset.
The
pandas
.groupby() function allows us to segment our data into meaningful groups.
Pivot Table
Pivot tables are useful for summarizing data. They can automatically sort, count, total, or average data stored in one table. Then, they can show the results of those actions in a new table of that summarized data.
In
pandas, the
pivot_table() function is used to create pivot tables.
To construct a pivot table, we’ll first call the DataFrame we want to work with, then the data we want to show, and how they are grouped.
In this example, we’ll work with the
all_names data, and show the Babies data grouped by Name in one dimension and Year on the other:
pd.pivot_table(all_names, 'Babies', 'Name', 'Year')
When we type
ALT + ENTER to run the code and continue, we’ll see the following output:
Because this shows a lot of empty values, we may want to keep Name and Year as columns rather than as rows in one case and columns in the other. We can do that by grouping the data in square brackets:
pd.pivot_table(all_names, 'Babies', ['Name', 'Year'])
Once we type
ALT + ENTER to run the code and continue, this table will now only show data for years that are on record for each name:
OutputName Year Aaban 2007 5.0 2009 6.0 2010 9.0 2011 11.0 2012 11.0 2013 14.0 2014 16.0 2015 15.0 Aabha 2011 7.0 2012 5.0 2014 9.0 2015 7.0 Aabid 2003 5.0 Aabriella 2008 5.0 2014 5.0 2015 5.0
Additionally, we can group data to have Name and Sex as one dimension, and Year on the other, as in:
pd.pivot_table(all_names, 'Babies', ['Name', 'Sex'], 'Year')
When we run the code and continue with
ALT + ENTER, we’ll see the following table:
Pivot tables let us create new tables from existing tables, allowing us to decide how we want that data grouped.
Visualize Data
By using
pandas with other packages like
matplotlib we can visualize data within our notebook.
We’ll be visualizing data about the popularity of a given name over the years. In order to do that, we need to set and sort indexes to rework the data that will allow us to see the changing popularity of a particular name.
The
pandas package lets us carry out hierarchical or multi-level indexing which lets us store and manipulate data with an arbitrary number of dimensions.
We’re going to index our data with information on Sex, then Name, then Year. We’ll also want to sort the index:
all_names_index = all_names.set_index(['Sex','Name','Year']).sort_index()
Type
ALT + ENTER to run and continue to our next line, where we’ll have the notebook display the new indexed DataFrame:
all_names_index
Run the code and continue with
ALT + ENTER, and the output will look like this:
Next, we’ll want to write a function that will plot the popularity of a name over time. We’ll call the function
name_plot and pass
sex and
name as its parameters that we will call when we run the function.
def name_plot(sex, name):
We’ll now set up a variable called
data to hold the table we have created. We’ll also use the
pandas DataFrame
loc in order to select our row by the value of the index. In our case, we’ll want
loc to be based on a combination of fields in the MultiIndex, referring to both the
sex and
name data.
Let’s write this construction into our function:
def name_plot(sex, name): data = all_names_index.loc[sex, name]
Finally, we’ll want to plot the values with
matplotlib.pyplot which we imported as
pp. We’ll then plot the values of the sex and name data against the index, which for our purposes is years.
def name_plot(sex, name): data = all_names_index.loc[sex, name] pp.plot(data.index, data.values)
Type
ALT + ENTER to run and move into the next cell. We can now call the function with the sex and name of our choice, such as
F for female name with the given name
Danica.
name_plot('F', 'Danica')
When you type
ALT + ENTER now, you’ll receive the following output:
Note that depending on what system you’re using you may have a warning about a font substitution, but the data will still plot correctly.
Looking at the visualization, we can see that the female name Danica had a small rise in popularity around 1990, and peaked just before 2010.
The function we created can be used to plot data from more than one name, so that we can see trends over time across different names.
Let’s start by making our plot a little bit larger:
pp.figure(figsize = (18, 8))
Next, let’s create a list with all the names we would like to plot:
pp.figure(figsize = (18, 8)) names = ['Sammy', 'Jesse', 'Drew', 'Jamie']
Now, we can iterate through the list with a
for loop and plot the data for each name. First, we’ll try these gender neutral names as female names:
pp.figure(figsize = (18, 8)) names = ['Sammy', 'Jesse', 'Drew', 'Jamie'] for name in names: name_plot('F', name)
To make this data easier to understand, let’s include a legend:
pp.figure(figsize = (18, 8)) names = ['Sammy', 'Jesse', 'Drew', 'Jamie'] for name in names: name_plot('F', name) pp.legend(names)
We’ll type
ALT + ENTER to run the code and continue, and then we’ll receive the following output:
While each of the names has been slowly gaining popularity as female names, the name Jamie was overwhelmingly popular as a female name in the years around 1980.
Let’s plot the same names but this time as male names:
pp.figure(figsize = (18, 8)) names = ['Sammy', 'Jesse', 'Drew', 'Jamie'] for name in names: name_plot('M', name) pp.legend(names)
Again, type
ALT + ENTER to run the code and continue. The graph will look like this:
This data shows more popularity across names, with Jesse being generally the most popular choice, and being particularly popular in the 1980s and 1990s.
From here, you can continue to play with name data, create visualizations about different names and their popularity, and create other scripts to look at different data to visualize.
Conclusion
This tutorial introduced you to ways of working with large data sets from setting up the data, to grouping the data with
groupby() and
pivot_table(), indexing the data with a MultiIndex, and visualizing
pandas data using the
matplotlib package.
Many organizations and institutions provide data sets that you can work with to continue to learn about
pandas and data visualization. The US government provides data through data.gov, for example.
You can learn more about visualizing data with
matplotlib by following our guides on How to Plot Data in Python 3 Using matplotlib and How To Graph Word Frequency Using matplotlib with Python 3.
1 Comment | https://www.digitalocean.com/community/tutorials/data-analysis-and-visualization-with-pandas-and-jupyter-notebook-in-python-3 | CC-MAIN-2019-26 | refinedweb | 2,567 | 71.34 |
Introduction
hello .....
Due to the construction of the school, I have been rather late in replying, I have also changed my email address to iamar.chieh@gmail.com
Chieh Wu
from Tkinter import * # Importing the Tkinter (tool box) library root = Tk() # Create a background window # Create a list li = 'Carl Patrick Lindsay Helmut Chris Gwen'.split() listb = Listbox(root) # Create a listbox widget for item in li: # Insert each item within li into the listbox listb.insert(0,item) listb.pack() # Pack listbox widget root.mainloop() # Execute the main event handler
lecture3 example 2
from Tkinter import * # Import the Tkinter library root = Tk() # Create a background window object # A simple way to create 2 lists li = ['Carl','Patrick','Lindsay','Helmut','Chris','Gwen'] movie = ['God Father','Beauty and the Beast','Brave heart'] listb = Listbox(root) # Create 2 listbox widgets listb2 = Listbox(root) for item in li: # Insert each item inside li into the listb listb.insert(0,item) for item in movie: # Do the same for the second listbox listb2.insert(0,item) listb.pack() # Pack each listbox into the main window listb2.pack() root.mainloop() # Invoke the main event handling loop
from Tkinter import * def Pressed(): #function print 'buttons are cool' root = Tk() #main window button = Button(root, text = 'Press', command = Pressed) button.pack(pady=20, padx = 20) Pressed() root.mainloop()
lecture4 example 2
#Souce section 1 #mandatory for unix and linux #--------------------------------------------------------------- from Tkinter import * #This library give us windows and buttons from random import * #This library allows us to generate random numbers #import library section 2 # #What not to use??? #--------------------------------------------------------------- def one_to_ten(): ran = uniform(1,10) print ran def GoWork(): # def starts a function, or define a function sum = 3*5 print sum #Function section 3 #---------------------------------------------------------------- #Code section 4 window = Tk() #i am the parent, button = child stacy = Button(window, text = 'yoyo', command = one_to_ten) #A rose with any other name would be just as sweet stacy.pack() #you can name it after your fish (ignored) window.mainloop() #you can use your fish's name
lecture4 example 3
from Tkinter import * def Call(): lab= Label(root, text = 'You pressed\nthe button') lab.pack() button['bg'] = 'blue' button['fg'] = 'white' root = Tk() root.geometry('100x110+350+70') button = Button(root, text = 'Press me', command = Call) button.pack() root.mainloop()
lecture4 example 5
from Tkinter import * #This interface allow us to draw windows def DrawList(): plist = ['Liz','Tom','Chi'] for item in plist: listbox.insert(END,item); root = Tk() #This creates a window, but it won't show up listbox = Listbox(root) button = Button(root,text = "press me",command = DrawList) button.pack() listbox.pack() #this tells the listbox to come out root.mainloop() #This command will tell the window come out
Lecture 5: Stealing is good in programming(10min)
We will program something using other people's code
Your will learn:How to program large programs, how to borrow other people's code(modules), basic concepts to functions
Example Code
lecture5 stacy.py 1
def adder( num1 , num2): return num1 + num2 def multiply( num1 , num2): return num1*num2 print multiply(3,range(2)) # oh what fun it is! print(multiply(3,list(range(2)))) # python 3k.
lecture5 chieh.py
from stacy import * #Find 3 +4 + (3*5) first = adder(3,4) second = multiply(3,5) answer = adder(first,second) print answer
Example Code lecture7_homework.py lecture7_text.py
Lecture 8: Let's make some decisions(7min)
Learn how to use the if statements. Having a program.
--- Hi Chieh, The website only shows
- The website you were trying to reach is temporarily unavailable. Please check back soon. If you are the owner of this website, please contact Technical Support as soon as possible.
Anyone have a copy any of the videos and code? | https://wiki.python.org/moin/Intro%20to%20programming%20with%20Python%20and%20Tkinter | CC-MAIN-2016-36 | refinedweb | 619 | 52.39 |
LE stack does not switch to sleep mode if the fine timer's timeout is set to 12 ms even when the fine timer is stopped.
The current is around 1mA what makes me think that chip is still only in Pause mode.
Solved!
Go to Solution.
Hello madmax
From the developers:
Please see if the following code snippet resolves your issue:
#include "devicelpm.h"
UINT32 app_queryPowersave(LowPowerModePollType type, UINT32 context){ if (type == LOW_POWER_MODE_POLL_TYPE_SLEEP) { // Always allow sleep and let the FW decide actual sleep time. return ~0; }
// Never allow deep sleep/hid-off. return 0;}
void application_create(void){ // Do all other application initialization here.
// Override default implementation of the app queriable: bleprofile_queryPowersaveCb = app_queryPowersave;}
Thanks
JT
View solution in original post
Attached please find a test app that demonstrates this issue.
Hello Lukasz,
Look at the RTC example. Look at P39 for Clear GPIO_Status.
The above answer may apply to other discussion:
Problem with wake up from deep sleep with a timer
but not to this one.
Apologies, Correct.
This issue is being investigated by the development team.
Thanks, | https://community.cypress.com/t5/WICED-Smart-Bluetooth/Problem-with-sleep-mode/td-p/136006 | CC-MAIN-2021-21 | refinedweb | 178 | 56.96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.