qid
int64
1
3.11M
question
stringlengths
10
32.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
33.7k
response_k
stringlengths
3
34.7k
1,010,583
I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable. For example: --- ``` a = (b+c*d)/e ``` *Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:* ``` d = (a*e - b)/c ``` --- As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it. Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. But that is just my opinion, so please point out if I am wrong. Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.
2009/06/18
[ "https://Stackoverflow.com/questions/1010583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83088/" ]
Using [SymPy](http://sympy.org/), your example would go something like this: ``` >>> import sympy >>> a,b,c,d,e = sympy.symbols('abcde') >>> r = (b+c*d)/e >>> l = a >>> r = sympy.solve(l-r,d) >>> l = d >>> r [(-b + a*e)/c] >>> ``` It seems to work for trigonometric functions too: ``` >>> l = a >>> r = b*sympy.sin(c) >>> sympy.solve(l-r,c) [asin(a/b)] >>> ``` And since you are working with a GUI, you'll (probably) want to convert back and forth from strings to expressions: ``` >>> r = '(b+c*d)/e' >>> sympy.sympify(r) (b + c*d)/e >>> sympy.sstr(_) '(b + c*d)/e' >>> ``` or you may prefer to display them as rendered [LaTeX or MathML](http://docs.sympy.org/latest/tutorial/printing.html).
If you want to do this out of the box, without relying on librairies, I think that the problems you will find are not Python related. If you want to find such equations, you have to describe the heuristics necessary to solve these equations. First, you have to represent your equation. What about separating: * operands: + symbolic operands (a,b) + numeric operands (1,2) * operators: + unary operators (-, trig functions) + binary operators (+,-,\*,/) Unary operators will obviously enclose one operand, binary ops will enclose two. What about types? I think that all of these components should derivate from a single common `expression` type. And this class would have a `getsymbols` method to locate quickly symbols in your expressions. And then distinguish between unary and binary operators, add a few basic complement/reorder primitives... Something like: ``` class expression(object): def symbols(self): if not hasattr(self, '_symbols'): self._symbols = self._getsymbols() return self._symbols def _getsymbols(self): """ return type: list of strings """ raise NotImplementedError class operand(expression): pass class symbolicoperand(operand): def __init__(self, name): self.name = name def _getsymbols(self): return [self.name] def __str__(self): return self.name class numericoperand(operand): def __init__(self, value): self.value = value def _getsymbols(self): return [] def __str__(self): return str(self.value) class operator(expression): pass class binaryoperator(operator): def __init__(self, lop, rop): """ @type lop, rop: expression """ self.lop = lop self.rop = rop def _getsymbols(self): return self.lop._getsymbols() + self.rop._getsymbols() @staticmethod def complementop(): """ Return complement operator: op.complementop()(op(a,b), b) = a """ raise NotImplementedError def reorder(): """ for op1(a,b) return op2(f(b),g(a)) such as op1(a,b) = op2(f(a),g(b)) """ raise NotImplementedError def _getstr(self): """ string representing the operator alone """ raise NotImplementedError def __str__(self): lop = str(self.lop) if isinstance(self.lop, operator): lop = '(%s)' % lop rop = str(self.rop) if isinstance(self.rop, operator): rop = '(%s)' % rop return '%s%s%s' % (lop, self._getstr(), rop) class symetricoperator(binaryoperator): def reorder(self): return self.__class__(self.rop, self.lop) class asymetricoperator(binaryoperator): @staticmethod def _invert(operand): """ div._invert(a) -> 1/a sub._invert(a) -> -a """ raise NotImplementedError def reorder(self): return self.complementop()(self._invert(self.rop), self.lop) class div(asymetricoperator): @staticmethod def _invert(operand): if isinstance(operand, div): return div(self.rop, self.lop) else: return div(numericoperand(1), operand) @staticmethod def complementop(): return mul def _getstr(self): return '/' class mul(symetricoperator): @staticmethod def complementop(): return div def _getstr(self): return '*' class add(symetricoperator): @staticmethod def complementop(): return sub def _getstr(self): return '+' class sub(asymetricoperator): @staticmethod def _invert(operand): if isinstance(operand, min): return operand.op else: return min(operand) @staticmethod def complementop(): return add def _getstr(self): return '-' class unaryoperator(operator): def __init__(self, op): """ @type op: expression """ self.op = op @staticmethod def complement(expression): raise NotImplementedError def _getsymbols(self): return self.op._getsymbols() class min(unaryoperator): @staticmethod def complement(expression): if isinstance(expression, min): return expression.op else: return min(expression) def __str__(self): return '-' + str(self.op) ``` With this basic structure set up, you should be able to describe a simple heuristic to solve very simple equations. Just think of the simple rules you learned to solve equations, and write them down. That should work :) And then a very naive solver: ``` def solve(left, right, symbol): """ @type left, right: expression @type symbol: string """ if symbol not in left.symbols(): if symbol not in right.symbols(): raise ValueError('%s not in expressions' % symbol) left, right = right, left solved = False while not solved: if isinstance(left, operator): if isinstance(left, unaryoperator): complementor = left.complement right = complementor(right) left = complementor(left) elif isinstance(left, binaryoperator): if symbol in left.rop.symbols(): left = left.reorder() else: right = left.complementop()(right, left.rop) left = left.lop elif isinstance(left, operand): assert isinstance(left, symbolicoperand) assert symbol==left.name solved = True print symbol,'=',right a,b,c,d,e = map(symbolicoperand, 'abcde') solve(a, div(add(b,mul(c,d)),e), 'd') # d = ((a*e)-b)/c solve(numericoperand(1), min(min(a)), 'a') # a = 1 ```
1,010,583
I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable. For example: --- ``` a = (b+c*d)/e ``` *Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:* ``` d = (a*e - b)/c ``` --- As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it. Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. But that is just my opinion, so please point out if I am wrong. Also, I will be using [SymPy](http://en.wikipedia.org/wiki/SymPy) for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.
2009/06/18
[ "https://Stackoverflow.com/questions/1010583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83088/" ]
Using [SymPy](http://sympy.org/), your example would go something like this: ``` >>> import sympy >>> a,b,c,d,e = sympy.symbols('abcde') >>> r = (b+c*d)/e >>> l = a >>> r = sympy.solve(l-r,d) >>> l = d >>> r [(-b + a*e)/c] >>> ``` It seems to work for trigonometric functions too: ``` >>> l = a >>> r = b*sympy.sin(c) >>> sympy.solve(l-r,c) [asin(a/b)] >>> ``` And since you are working with a GUI, you'll (probably) want to convert back and forth from strings to expressions: ``` >>> r = '(b+c*d)/e' >>> sympy.sympify(r) (b + c*d)/e >>> sympy.sstr(_) '(b + c*d)/e' >>> ``` or you may prefer to display them as rendered [LaTeX or MathML](http://docs.sympy.org/latest/tutorial/printing.html).
Things have sure changed since 2009. I don't know how your GUI application is going, but this is now possible directly in IPython qtconsole (which one could embed inside a custom PyQt/PySide application, and keep track of all the defined symbols, to allow GUI interaction in a separate listbox, etc.) ![enter image description here](https://i.stack.imgur.com/ax15B.png) *(Uses the `sympyprt` extension for IPython*)
2,820,989
I'm looking for ideas on how to take screenshots of websites within a .NET application. This application will be a windows service. Thanks!
2010/05/12
[ "https://Stackoverflow.com/questions/2820989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40337/" ]
Check out the following links: <http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx> <http://www.dotnetspider.com/resources/28436-Code-get-screenshot-webpage.aspx>
You can't show forms with WindowsServices. However, try to create a Form, with WebBrowser component, fill-in URL, browser.OnPageLoaded => myBrowser.DrawToBitmap.. who knows.
2,820,989
I'm looking for ideas on how to take screenshots of websites within a .NET application. This application will be a windows service. Thanks!
2010/05/12
[ "https://Stackoverflow.com/questions/2820989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40337/" ]
Check out the following links: <http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx> <http://www.dotnetspider.com/resources/28436-Code-get-screenshot-webpage.aspx>
You can host the MSHTML component and have it load the page and then print it to a metafile, which can then be player or converted to a bitmap. Note, however, that the MSHTML component may not work correctly when run as service without visual UI (e.g. without desktop interaction).
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
Your regex is **not** the problem. Your regex as well as the one given by Wim works fine. So the problem has to be with the way the input is being handled. Here are some things you can try: Run this with different input, i.e. instead of using this number: ``` -16744193 ``` Use something like this instead: ``` 100 -100 ``` Then print out the value after this line: ``` int fcolor = Int32.Parse(match.Groups[7].Value); ``` And see what it is. Another time-saving thing you should do is print out the values in ``` match.Groups[1].Value match.Groups[2].Value match.Groups[3].Value match.Groups[4].Value match.Groups[5].Value match.Groups[6].Value match.Groups[7].Value match.Groups[8].Value ``` And post them here. This will make it easy for you as well as every at SO to see what the problem is.
I'd set a breakpoint on the line with the error and see what `match.Groups[5].Value` really is. I'm betting it can't be converted to an int.
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
Printing out the match values as suggested elsewhere would be a help, as well as shortening the regexp to make it easier to isolate the problem. But I can suggest one more thing. Here's the last part of the regexp starting from the font size match: ``` ..."(\d+\.\d+)\r\n(-?\d+)" ``` Which is supposed to match against ``` ... 14.0 -55794414 ``` Since you have the match for the newline immediately after the match for the font size digits, the match will fail if you have a space after 14.0. Try with ``` ..."(\d+\.\d+)\s*\r\n(-?\d+)" ``` which should work both with and without trailing spaces. (Depending on your regexp engine, just `"\s*"` may be better than `"\s*\r\n"`.) There are actually a whole bunch of other things that could go wrong. It is generally easier to split up the strings and work with smaller regexps. I suppose you already know the quote? > > Some people, when confronted with a > problem, think "I know, I'll use > regular expressions." Now they have > two problems. > > >
You can use this regex: ``` @"(.+)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)\r\n(-?\d+)" ``` A usage example from which it can be seen that it works: ``` string value = @"Label ""this is a label"" 23, 77 Tahoma 14.0 -55794414 Label ""this is a label"" 23, 77 Tahoma 14.0 -55794415"; MatchCollection lines = Regex.Matches( value, @"(.+)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)\r\n(-?\d+)"); var colors = new List<int>(); foreach (Match match in lines) { colors.Add(Int32.Parse(match.Groups[7].Value)); } CollectionAssert.AreEquivalent(new[] { -55794414, -55794415}, colors); ``` In this example we have 2 labels with different colors, as can be seen the regex matches the colors. The groups of the regex: * **0**: Control * **1**: Text * **2**: X * **3**: Y * **4**: Font * **6**: Size * **7**: Color
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
Your regex is **not** the problem. Your regex as well as the one given by Wim works fine. So the problem has to be with the way the input is being handled. Here are some things you can try: Run this with different input, i.e. instead of using this number: ``` -16744193 ``` Use something like this instead: ``` 100 -100 ``` Then print out the value after this line: ``` int fcolor = Int32.Parse(match.Groups[7].Value); ``` And see what it is. Another time-saving thing you should do is print out the values in ``` match.Groups[1].Value match.Groups[2].Value match.Groups[3].Value match.Groups[4].Value match.Groups[5].Value match.Groups[6].Value match.Groups[7].Value match.Groups[8].Value ``` And post them here. This will make it easy for you as well as every at SO to see what the problem is.
Printing out the match values as suggested elsewhere would be a help, as well as shortening the regexp to make it easier to isolate the problem. But I can suggest one more thing. Here's the last part of the regexp starting from the font size match: ``` ..."(\d+\.\d+)\r\n(-?\d+)" ``` Which is supposed to match against ``` ... 14.0 -55794414 ``` Since you have the match for the newline immediately after the match for the font size digits, the match will fail if you have a space after 14.0. Try with ``` ..."(\d+\.\d+)\s*\r\n(-?\d+)" ``` which should work both with and without trailing spaces. (Depending on your regexp engine, just `"\s*"` may be better than `"\s*\r\n"`.) There are actually a whole bunch of other things that could go wrong. It is generally easier to split up the strings and work with smaller regexps. I suppose you already know the quote? > > Some people, when confronted with a > problem, think "I know, I'll use > regular expressions." Now they have > two problems. > > >
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
`-` is not matched by `\d`. Also, if you do a non-greedy match on `\d+` only the first digit will be captured since that satisfies the regexp. Change your regexp into `(-?\d+)` to match an optional `-` at the start of your number and as many digits as there are in the number, up to (but not including) the character following the number (newline, end-of-string, ...).
Printing out the match values as suggested elsewhere would be a help, as well as shortening the regexp to make it easier to isolate the problem. But I can suggest one more thing. Here's the last part of the regexp starting from the font size match: ``` ..."(\d+\.\d+)\r\n(-?\d+)" ``` Which is supposed to match against ``` ... 14.0 -55794414 ``` Since you have the match for the newline immediately after the match for the font size digits, the match will fail if you have a space after 14.0. Try with ``` ..."(\d+\.\d+)\s*\r\n(-?\d+)" ``` which should work both with and without trailing spaces. (Depending on your regexp engine, just `"\s*"` may be better than `"\s*\r\n"`.) There are actually a whole bunch of other things that could go wrong. It is generally easier to split up the strings and work with smaller regexps. I suppose you already know the quote? > > Some people, when confronted with a > problem, think "I know, I'll use > regular expressions." Now they have > two problems. > > >
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
`-` is not matched by `\d`. Also, if you do a non-greedy match on `\d+` only the first digit will be captured since that satisfies the regexp. Change your regexp into `(-?\d+)` to match an optional `-` at the start of your number and as many digits as there are in the number, up to (but not including) the character following the number (newline, end-of-string, ...).
You have only 4 groups in your regular expressions, but you are trying to access groups 5 to 8 which will be empty strings, and an empty string cannot be parsed as an integer by Int32.Parse.
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
Try this regex and see if it works. (.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]\*)\r\n(\d+.\d+)\r\n(-?\d+) Your regex appeared to be looking for the " after the font size value. Also, your ARGB colour will be in group match 7, not 5.
I'd set a breakpoint on the line with the error and see what `match.Groups[5].Value` really is. I'm betting it can't be converted to an int.
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
`-` is not matched by `\d`. Also, if you do a non-greedy match on `\d+` only the first digit will be captured since that satisfies the regexp. Change your regexp into `(-?\d+)` to match an optional `-` at the start of your number and as many digits as there are in the number, up to (but not including) the character following the number (newline, end-of-string, ...).
Your regex is **not** the problem. Your regex as well as the one given by Wim works fine. So the problem has to be with the way the input is being handled. Here are some things you can try: Run this with different input, i.e. instead of using this number: ``` -16744193 ``` Use something like this instead: ``` 100 -100 ``` Then print out the value after this line: ``` int fcolor = Int32.Parse(match.Groups[7].Value); ``` And see what it is. Another time-saving thing you should do is print out the values in ``` match.Groups[1].Value match.Groups[2].Value match.Groups[3].Value match.Groups[4].Value match.Groups[5].Value match.Groups[6].Value match.Groups[7].Value match.Groups[8].Value ``` And post them here. This will make it easy for you as well as every at SO to see what the problem is.
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
Printing out the match values as suggested elsewhere would be a help, as well as shortening the regexp to make it easier to isolate the problem. But I can suggest one more thing. Here's the last part of the regexp starting from the font size match: ``` ..."(\d+\.\d+)\r\n(-?\d+)" ``` Which is supposed to match against ``` ... 14.0 -55794414 ``` Since you have the match for the newline immediately after the match for the font size digits, the match will fail if you have a space after 14.0. Try with ``` ..."(\d+\.\d+)\s*\r\n(-?\d+)" ``` which should work both with and without trailing spaces. (Depending on your regexp engine, just `"\s*"` may be better than `"\s*\r\n"`.) There are actually a whole bunch of other things that could go wrong. It is generally easier to split up the strings and work with smaller regexps. I suppose you already know the quote? > > Some people, when confronted with a > problem, think "I know, I'll use > regular expressions." Now they have > two problems. > > >
You have only 4 groups in your regular expressions, but you are trying to access groups 5 to 8 which will be empty strings, and an empty string cannot be parsed as an integer by Int32.Parse.
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
I'd set a breakpoint on the line with the error and see what `match.Groups[5].Value` really is. I'm betting it can't be converted to an int.
You can use this regex: ``` @"(.+)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)\r\n(-?\d+)" ``` A usage example from which it can be seen that it works: ``` string value = @"Label ""this is a label"" 23, 77 Tahoma 14.0 -55794414 Label ""this is a label"" 23, 77 Tahoma 14.0 -55794415"; MatchCollection lines = Regex.Matches( value, @"(.+)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)\r\n(-?\d+)"); var colors = new List<int>(); foreach (Match match in lines) { colors.Add(Int32.Parse(match.Groups[7].Value)); } CollectionAssert.AreEquivalent(new[] { -55794414, -55794415}, colors); ``` In this example we have 2 labels with different colors, as can be seen the regex matches the colors. The groups of the regex: * **0**: Control * **1**: Text * **2**: X * **3**: Y * **4**: Font * **6**: Size * **7**: Color
1,512,339
i'm trying to get Color information that i've stored in a text file and then use that color as the forecolor for a label. BUT, at run time when i click the button to do it, it doesnt give me any error messages or anything. the code i have is below: ``` MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]*)\r\n(\d+\.\d+)""\r\n(\d+?)"); foreach (Match match in lines) int color = Int32.Parse(match.Groups[5].Value); ``` I have other regex for other info inn files too, but the other regex isnt the problem. the problem is the regex that i have just added to try and match a color (argb). it's at the end of the string: ``` \r\n(\d+?) ``` So as far as I understand it, the above little regex thing means this: "Find a carriagereturn and newline, and then 1 or more digits but dont be greedy". is that right? can somebody please help me with this. thank you very much. Note: The color info that is saved in the text file is a negative number (ARGB color): ``` -16744193 ``` The file contents is like this: ``` Control Control Text Control Location Control Font Name Control Font Size Control Font Color ``` Explanation: ``` Label "this is a label" 23, 77 Tahoma 14.0 -55794414 ``` So, the regex works, it gets all the other details correctly but it just doesnt get the color information.
2009/10/02
[ "https://Stackoverflow.com/questions/1512339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/152598/" ]
Try this regex and see if it works. (.+?)\r\n""([^""]+)""\r\n(\d+),\s(\d+)\r\n([\w\s]\*)\r\n(\d+.\d+)\r\n(-?\d+) Your regex appeared to be looking for the " after the font size value. Also, your ARGB colour will be in group match 7, not 5.
Your regex is **not** the problem. Your regex as well as the one given by Wim works fine. So the problem has to be with the way the input is being handled. Here are some things you can try: Run this with different input, i.e. instead of using this number: ``` -16744193 ``` Use something like this instead: ``` 100 -100 ``` Then print out the value after this line: ``` int fcolor = Int32.Parse(match.Groups[7].Value); ``` And see what it is. Another time-saving thing you should do is print out the values in ``` match.Groups[1].Value match.Groups[2].Value match.Groups[3].Value match.Groups[4].Value match.Groups[5].Value match.Groups[6].Value match.Groups[7].Value match.Groups[8].Value ``` And post them here. This will make it easy for you as well as every at SO to see what the problem is.
1,287,222
I need to add colour to some text in a PDF document using PDF::API2 - how do I do that?
2009/08/17
[ "https://Stackoverflow.com/questions/1287222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
According [PDF::API2::Content](http://search.cpan.org/dist/PDF-API2/lib/PDF/API2/Content.pm) it looks like you pass hashref option to *text* method (on a PDF::API::Content::Text object). So it "should" work like this (NB. I don't have PDF::API2 installed here so code below is untested): ``` use PDF::API2; use PDF::API2::Util; my $pdf = PDF::API2->new; my $font = $pdf->corefont('Helvetica',-encode=>'latin1'); my $page = $pdf->page; $page->mediabox( 80, 500 ); my $txt = $page->text; $txt->font( $font, 20 ); $txt->translate( 50, 800 ); $txt->text('Hello there!', { color => '#e6e6e6' } ); # <= hashref option $pdf->saveas( "file.pdf" ); $pdf->end(); ``` Hope that helps?
Use something like the following: ``` my $margin = $x; #co-ordinates for page my $margin = $y; #co-ordinates for page my $caption = 'blah blah blah'; my $font=$pdf->corefont('Helvetica-Bold',-encode=>'latin1'); my $font_size = 12; my $page = $pdf->openpage($pageNum); my $gfx = $page->gfx; $gfx->textlabel($margin,$y_pos, $font,$font_size,$caption, -color => '#5E5E5E', ); ``` And obviously change hex colour to whatever you want.
1,287,222
I need to add colour to some text in a PDF document using PDF::API2 - how do I do that?
2009/08/17
[ "https://Stackoverflow.com/questions/1287222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can set the text color by calling the `fillcolor` method before adding the text: ``` use PDF::API2; my $pdf = PDF::API2->new(); # Create a PDF my $font = $pdf->corefont('Helvetica'); # Add a font to the PDF my $page = $pdf->page(); # Create a page to hold your text my $text = $page->text(); # Create a graphics/text object $text->font($font, 12); # Set the font and size for your text $text->fillcolor('#FF0000'); # Set the text color $text->text('This text will be red.'); # Add your text ``` Web-style color names will probably work fine in most cases, but you can give a CMYK color instead by using "%" instead of "#" and passing four values (e.g. `%00FF0000` for magenta). The [PDF::API2::Content](http://search.cpan.org/dist/PDF-API2/lib/PDF/API2/Content.pm) documentation has more details on the various methods that will affect the `$text` object.
According [PDF::API2::Content](http://search.cpan.org/dist/PDF-API2/lib/PDF/API2/Content.pm) it looks like you pass hashref option to *text* method (on a PDF::API::Content::Text object). So it "should" work like this (NB. I don't have PDF::API2 installed here so code below is untested): ``` use PDF::API2; use PDF::API2::Util; my $pdf = PDF::API2->new; my $font = $pdf->corefont('Helvetica',-encode=>'latin1'); my $page = $pdf->page; $page->mediabox( 80, 500 ); my $txt = $page->text; $txt->font( $font, 20 ); $txt->translate( 50, 800 ); $txt->text('Hello there!', { color => '#e6e6e6' } ); # <= hashref option $pdf->saveas( "file.pdf" ); $pdf->end(); ``` Hope that helps?
1,287,222
I need to add colour to some text in a PDF document using PDF::API2 - how do I do that?
2009/08/17
[ "https://Stackoverflow.com/questions/1287222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The only options that `$txt->text` supports are -indent, -underline and -strokecolor, though -strokecolor is only used in combination with -underline to determine the color of the line. Use `$txt->fillcolor('colorname')` or `$txt->fillcolor('#RRGGBB')` to set the color of any text written after the fillcolor command.
Use something like the following: ``` my $margin = $x; #co-ordinates for page my $margin = $y; #co-ordinates for page my $caption = 'blah blah blah'; my $font=$pdf->corefont('Helvetica-Bold',-encode=>'latin1'); my $font_size = 12; my $page = $pdf->openpage($pageNum); my $gfx = $page->gfx; $gfx->textlabel($margin,$y_pos, $font,$font_size,$caption, -color => '#5E5E5E', ); ``` And obviously change hex colour to whatever you want.
1,287,222
I need to add colour to some text in a PDF document using PDF::API2 - how do I do that?
2009/08/17
[ "https://Stackoverflow.com/questions/1287222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can set the text color by calling the `fillcolor` method before adding the text: ``` use PDF::API2; my $pdf = PDF::API2->new(); # Create a PDF my $font = $pdf->corefont('Helvetica'); # Add a font to the PDF my $page = $pdf->page(); # Create a page to hold your text my $text = $page->text(); # Create a graphics/text object $text->font($font, 12); # Set the font and size for your text $text->fillcolor('#FF0000'); # Set the text color $text->text('This text will be red.'); # Add your text ``` Web-style color names will probably work fine in most cases, but you can give a CMYK color instead by using "%" instead of "#" and passing four values (e.g. `%00FF0000` for magenta). The [PDF::API2::Content](http://search.cpan.org/dist/PDF-API2/lib/PDF/API2/Content.pm) documentation has more details on the various methods that will affect the `$text` object.
The only options that `$txt->text` supports are -indent, -underline and -strokecolor, though -strokecolor is only used in combination with -underline to determine the color of the line. Use `$txt->fillcolor('colorname')` or `$txt->fillcolor('#RRGGBB')` to set the color of any text written after the fillcolor command.
1,287,222
I need to add colour to some text in a PDF document using PDF::API2 - how do I do that?
2009/08/17
[ "https://Stackoverflow.com/questions/1287222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can set the text color by calling the `fillcolor` method before adding the text: ``` use PDF::API2; my $pdf = PDF::API2->new(); # Create a PDF my $font = $pdf->corefont('Helvetica'); # Add a font to the PDF my $page = $pdf->page(); # Create a page to hold your text my $text = $page->text(); # Create a graphics/text object $text->font($font, 12); # Set the font and size for your text $text->fillcolor('#FF0000'); # Set the text color $text->text('This text will be red.'); # Add your text ``` Web-style color names will probably work fine in most cases, but you can give a CMYK color instead by using "%" instead of "#" and passing four values (e.g. `%00FF0000` for magenta). The [PDF::API2::Content](http://search.cpan.org/dist/PDF-API2/lib/PDF/API2/Content.pm) documentation has more details on the various methods that will affect the `$text` object.
Use something like the following: ``` my $margin = $x; #co-ordinates for page my $margin = $y; #co-ordinates for page my $caption = 'blah blah blah'; my $font=$pdf->corefont('Helvetica-Bold',-encode=>'latin1'); my $font_size = 12; my $page = $pdf->openpage($pageNum); my $gfx = $page->gfx; $gfx->textlabel($margin,$y_pos, $font,$font_size,$caption, -color => '#5E5E5E', ); ``` And obviously change hex colour to whatever you want.
209,691
Currently we have a table that we use to track inivitations. We have an email field that is indexed but we also have three optional keys that the user can specify when adding new record emails. We don't allow duplicates so we have to query if the email plus the optional keys already exists. Currently the keys are only added to the select statement if they are specified. The normal case is only email is specified and using the index it works fairly quickly. When the keys are added performance drops. Would adding three indexes affect performance for other operations? Keys are probably used infrequently that we wouldn't want to impact performance for this case. * email, key1 * email, key1, key2 * email, key1, key2, key3 The other idea is we add 1 key. * email, key1, key2, key3 Then always use all 3 keys in the lookup (eg. key1 = mykey AND key2 is NULL AND key3 is NULL) **See Also** [Exact duplicate post](https://stackoverflow.com/questions/179085/multiple-indexes-vs-multi-column-indexes)
2008/10/16
[ "https://Stackoverflow.com/questions/209691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27989/" ]
Personally I would recommend this approach. Try the method with the single index that covers everything, if I recall correctly it will still perform well if you only query on the first of the included columns. Once you have the index in place, run the Index Advisor. Then try the other route and repeat. It really depends on your data. I typically have been able to get by with 1 covering index, starting with the most frequently used key first.
It depends on how often the table is updated, and how complex the indexes are. If you go nuts creating indexes, then every time a record is inserted/updated/deleted, every index will have to be modified to reflect that information. If you only put three indexes on, and they are relatively simple, then you shouldn't have a problem.
209,691
Currently we have a table that we use to track inivitations. We have an email field that is indexed but we also have three optional keys that the user can specify when adding new record emails. We don't allow duplicates so we have to query if the email plus the optional keys already exists. Currently the keys are only added to the select statement if they are specified. The normal case is only email is specified and using the index it works fairly quickly. When the keys are added performance drops. Would adding three indexes affect performance for other operations? Keys are probably used infrequently that we wouldn't want to impact performance for this case. * email, key1 * email, key1, key2 * email, key1, key2, key3 The other idea is we add 1 key. * email, key1, key2, key3 Then always use all 3 keys in the lookup (eg. key1 = mykey AND key2 is NULL AND key3 is NULL) **See Also** [Exact duplicate post](https://stackoverflow.com/questions/179085/multiple-indexes-vs-multi-column-indexes)
2008/10/16
[ "https://Stackoverflow.com/questions/209691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27989/" ]
It depends on how often the table is updated, and how complex the indexes are. If you go nuts creating indexes, then every time a record is inserted/updated/deleted, every index will have to be modified to reflect that information. If you only put three indexes on, and they are relatively simple, then you shouldn't have a problem.
I could be wrong, but I believe if you add: * email, key1, key2, key3 as an index, that most databases will use it if your query is using "email", "email/key1", "email/key1/key2", etc... without requiring you to specify Null values for the missing fields.
209,691
Currently we have a table that we use to track inivitations. We have an email field that is indexed but we also have three optional keys that the user can specify when adding new record emails. We don't allow duplicates so we have to query if the email plus the optional keys already exists. Currently the keys are only added to the select statement if they are specified. The normal case is only email is specified and using the index it works fairly quickly. When the keys are added performance drops. Would adding three indexes affect performance for other operations? Keys are probably used infrequently that we wouldn't want to impact performance for this case. * email, key1 * email, key1, key2 * email, key1, key2, key3 The other idea is we add 1 key. * email, key1, key2, key3 Then always use all 3 keys in the lookup (eg. key1 = mykey AND key2 is NULL AND key3 is NULL) **See Also** [Exact duplicate post](https://stackoverflow.com/questions/179085/multiple-indexes-vs-multi-column-indexes)
2008/10/16
[ "https://Stackoverflow.com/questions/209691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27989/" ]
It depends on how often the table is updated, and how complex the indexes are. If you go nuts creating indexes, then every time a record is inserted/updated/deleted, every index will have to be modified to reflect that information. If you only put three indexes on, and they are relatively simple, then you shouldn't have a problem.
As others have said, most databases will use the index "a, b, c" when searching for just a, a and b or a, b and c. And they will often only use one index per table. So adding "email, key1, key2, key3" will probably be the best. That said, use EXPLAIN to find out what's really going on. Check to make sure what indexes, if any, your queries are using. Every database has its quirks.
209,691
Currently we have a table that we use to track inivitations. We have an email field that is indexed but we also have three optional keys that the user can specify when adding new record emails. We don't allow duplicates so we have to query if the email plus the optional keys already exists. Currently the keys are only added to the select statement if they are specified. The normal case is only email is specified and using the index it works fairly quickly. When the keys are added performance drops. Would adding three indexes affect performance for other operations? Keys are probably used infrequently that we wouldn't want to impact performance for this case. * email, key1 * email, key1, key2 * email, key1, key2, key3 The other idea is we add 1 key. * email, key1, key2, key3 Then always use all 3 keys in the lookup (eg. key1 = mykey AND key2 is NULL AND key3 is NULL) **See Also** [Exact duplicate post](https://stackoverflow.com/questions/179085/multiple-indexes-vs-multi-column-indexes)
2008/10/16
[ "https://Stackoverflow.com/questions/209691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27989/" ]
Personally I would recommend this approach. Try the method with the single index that covers everything, if I recall correctly it will still perform well if you only query on the first of the included columns. Once you have the index in place, run the Index Advisor. Then try the other route and repeat. It really depends on your data. I typically have been able to get by with 1 covering index, starting with the most frequently used key first.
I could be wrong, but I believe if you add: * email, key1, key2, key3 as an index, that most databases will use it if your query is using "email", "email/key1", "email/key1/key2", etc... without requiring you to specify Null values for the missing fields.
209,691
Currently we have a table that we use to track inivitations. We have an email field that is indexed but we also have three optional keys that the user can specify when adding new record emails. We don't allow duplicates so we have to query if the email plus the optional keys already exists. Currently the keys are only added to the select statement if they are specified. The normal case is only email is specified and using the index it works fairly quickly. When the keys are added performance drops. Would adding three indexes affect performance for other operations? Keys are probably used infrequently that we wouldn't want to impact performance for this case. * email, key1 * email, key1, key2 * email, key1, key2, key3 The other idea is we add 1 key. * email, key1, key2, key3 Then always use all 3 keys in the lookup (eg. key1 = mykey AND key2 is NULL AND key3 is NULL) **See Also** [Exact duplicate post](https://stackoverflow.com/questions/179085/multiple-indexes-vs-multi-column-indexes)
2008/10/16
[ "https://Stackoverflow.com/questions/209691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27989/" ]
Personally I would recommend this approach. Try the method with the single index that covers everything, if I recall correctly it will still perform well if you only query on the first of the included columns. Once you have the index in place, run the Index Advisor. Then try the other route and repeat. It really depends on your data. I typically have been able to get by with 1 covering index, starting with the most frequently used key first.
As others have said, most databases will use the index "a, b, c" when searching for just a, a and b or a, b and c. And they will often only use one index per table. So adding "email, key1, key2, key3" will probably be the best. That said, use EXPLAIN to find out what's really going on. Check to make sure what indexes, if any, your queries are using. Every database has its quirks.
1,922,651
Now my program generates two data files. a.txt and b.txt Take a.txt as an example, it's content just like this: ``` 0,0 0,1 1,0 -3,1 1,-2 1,3 ...... ``` b.txt is similar with a.txt. Now, I hope to find out average distance between the corresponding content in a and b file. In other words, for example, if b.txt like this: ``` 0,0 1,1 1,2 -3,1 1,-2 1,3 ...... ``` Then the distance is calculated in this way: ``` sqrt[square(0-0)+square(0-0)] +sqrt[square(0-1)+square(1-1)] +sqrt[square(1-1)+square(0-2)] +sqrt[square((-3)-(-3))+square(1-1)] +sqrt[square(1-1)+square((-2)-(-2))] ....... _____________ /Total number(i.e 10,000) ``` to get the average distance between these two files content. Question: how to write a shell script which can carry out the calculation process like above? And output the final average distance? Hint: you may view two groups of coordinates are stored in two files. Need your kind help..Many many Thanks. **Addition:** There are about 10,000 - 100,000 rows for each files.
2009/12/17
[ "https://Stackoverflow.com/questions/1922651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208663/" ]
AWK is really good for doing simple mathematical calculations on files containing rows of delimited data. There is a very good AWK guide here: <http://www.vectorsite.net/tsawk.html> A general structure for this program could be: ``` Store the first row For each additional row, calculate the distance between it and the last row and overwrite the stored values Add the distance to a variable containing the distance sum Divide at the end by the number of rows seen (conveniently stored for you by AWK) Output the result ```
This would be much easier in a scripting language like perl or python. However in a shell script you would probably want to use: * `cut` to split the files up * `bc` to do the calculation * whatever loop construct you prefer in your script language I've left this vague in case it is homework.
1,395,667
I am attempting to insert a row manually into my SQL Server data table. This table has 5 columns, one identity and four data columns. I looked at [this post](https://stackoverflow.com/questions/850327/how-to-insert-into-a-table-with-just-one-identity-column), but when I run the selected answer's query (after replacing 'GroupTable' with my table name of course), my SQL Server 2005 management studio crashes. I have tried variations of the following statements, but obviously no luck thus far: ``` INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (0, 'Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') INSERT INTO MyTable (col1, col2, col3, col4) VALUES ('Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') ``` Any pointers would be greatly appreciated.
2009/09/08
[ "https://Stackoverflow.com/questions/1395667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
Usually, omitting the id column would generate a new automatic ID if the column is set so. In your case, you can use ``` SET IDENTITY_INSERT MyTable ON; INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (4567, 'Value1', 'Value2', 'Value3', 'Value4'); SET IDENTITY_INSERT MyTable OFF; ```
The first time I've heard of mysql having an SQL 2005 management client, but in any case have you tried directly logging to the database from a command line and executing the insert statement from there?
1,395,667
I am attempting to insert a row manually into my SQL Server data table. This table has 5 columns, one identity and four data columns. I looked at [this post](https://stackoverflow.com/questions/850327/how-to-insert-into-a-table-with-just-one-identity-column), but when I run the selected answer's query (after replacing 'GroupTable' with my table name of course), my SQL Server 2005 management studio crashes. I have tried variations of the following statements, but obviously no luck thus far: ``` INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (0, 'Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') INSERT INTO MyTable (col1, col2, col3, col4) VALUES ('Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') ``` Any pointers would be greatly appreciated.
2009/09/08
[ "https://Stackoverflow.com/questions/1395667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
As some others have said, I'm thinking the second one should work for you, but if you're crashing the management studio when you run the query, whether it's broken or not, your problem is bigger than a malformed sql query. The studio shouldn't crash, even if you write some pretty awful sql...it should just give you an error message and move on. You might consider reinstalling the management studio if these kinds of errors are common for you.
The first time I've heard of mysql having an SQL 2005 management client, but in any case have you tried directly logging to the database from a command line and executing the insert statement from there?
1,395,667
I am attempting to insert a row manually into my SQL Server data table. This table has 5 columns, one identity and four data columns. I looked at [this post](https://stackoverflow.com/questions/850327/how-to-insert-into-a-table-with-just-one-identity-column), but when I run the selected answer's query (after replacing 'GroupTable' with my table name of course), my SQL Server 2005 management studio crashes. I have tried variations of the following statements, but obviously no luck thus far: ``` INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (0, 'Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') INSERT INTO MyTable (col1, col2, col3, col4) VALUES ('Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') ``` Any pointers would be greatly appreciated.
2009/09/08
[ "https://Stackoverflow.com/questions/1395667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
Usually, omitting the id column would generate a new automatic ID if the column is set so. In your case, you can use ``` SET IDENTITY_INSERT MyTable ON; INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (4567, 'Value1', 'Value2', 'Value3', 'Value4'); SET IDENTITY_INSERT MyTable OFF; ```
Not sure what you mean by "crashes" but, that second statement should work providing you have the identity specification set correctly on the table. Right-click the table in mangement studio and look at the properties for the id column. isIdentity should be "Yes" and identity increment should be 1.
1,395,667
I am attempting to insert a row manually into my SQL Server data table. This table has 5 columns, one identity and four data columns. I looked at [this post](https://stackoverflow.com/questions/850327/how-to-insert-into-a-table-with-just-one-identity-column), but when I run the selected answer's query (after replacing 'GroupTable' with my table name of course), my SQL Server 2005 management studio crashes. I have tried variations of the following statements, but obviously no luck thus far: ``` INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (0, 'Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') INSERT INTO MyTable (col1, col2, col3, col4) VALUES ('Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') ``` Any pointers would be greatly appreciated.
2009/09/08
[ "https://Stackoverflow.com/questions/1395667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
Usually, omitting the id column would generate a new automatic ID if the column is set so. In your case, you can use ``` SET IDENTITY_INSERT MyTable ON; INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (4567, 'Value1', 'Value2', 'Value3', 'Value4'); SET IDENTITY_INSERT MyTable OFF; ```
As some others have said, I'm thinking the second one should work for you, but if you're crashing the management studio when you run the query, whether it's broken or not, your problem is bigger than a malformed sql query. The studio shouldn't crash, even if you write some pretty awful sql...it should just give you an error message and move on. You might consider reinstalling the management studio if these kinds of errors are common for you.
1,395,667
I am attempting to insert a row manually into my SQL Server data table. This table has 5 columns, one identity and four data columns. I looked at [this post](https://stackoverflow.com/questions/850327/how-to-insert-into-a-table-with-just-one-identity-column), but when I run the selected answer's query (after replacing 'GroupTable' with my table name of course), my SQL Server 2005 management studio crashes. I have tried variations of the following statements, but obviously no luck thus far: ``` INSERT INTO MyTable (id, col1, col2, col3, col4) VALUES (0, 'Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') INSERT INTO MyTable (col1, col2, col3, col4) VALUES ('Column 1 Value', 'Column 2 Value', 'Column 3 Value', 'Column 4 Value') ``` Any pointers would be greatly appreciated.
2009/09/08
[ "https://Stackoverflow.com/questions/1395667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
As some others have said, I'm thinking the second one should work for you, but if you're crashing the management studio when you run the query, whether it's broken or not, your problem is bigger than a malformed sql query. The studio shouldn't crash, even if you write some pretty awful sql...it should just give you an error message and move on. You might consider reinstalling the management studio if these kinds of errors are common for you.
Not sure what you mean by "crashes" but, that second statement should work providing you have the identity specification set correctly on the table. Right-click the table in mangement studio and look at the properties for the id column. isIdentity should be "Yes" and identity increment should be 1.
1,660,912
Can i pass the entire POST array into a function and handle it within the function? such as ``` PostInfo($_POST); function PostInfo($_POST){ $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } ``` or is this the correct way of doing this?
2009/11/02
[ "https://Stackoverflow.com/questions/1660912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115949/" ]
Yes. If you are going to name the local variable `$_POST` though, don't bother. `$_POST` is a 'superglobal', a global that doesn't require the `global` keyword to use it outside normal scope. Your above function would work without the parameter on it. > > **NOTE** You cannot use any superglobal (i.e. `$_POST`) as a function argument in PHP 5.4 or later. It will generate a Fatal error > > >
You can actually pass $\_POST to any function which takes in an array. ``` function process(array $request) { } process($_POST); process($_GET); ``` Great for testing.
1,660,912
Can i pass the entire POST array into a function and handle it within the function? such as ``` PostInfo($_POST); function PostInfo($_POST){ $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } ``` or is this the correct way of doing this?
2009/11/02
[ "https://Stackoverflow.com/questions/1660912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115949/" ]
Yes. If you are going to name the local variable `$_POST` though, don't bother. `$_POST` is a 'superglobal', a global that doesn't require the `global` keyword to use it outside normal scope. Your above function would work without the parameter on it. > > **NOTE** You cannot use any superglobal (i.e. `$_POST`) as a function argument in PHP 5.4 or later. It will generate a Fatal error > > >
The [`$_POST`-array](http://www.php.net/manual/en/reserved.variables.post.php) is an array like every other array in PHP (besides being a so-called [*superglobal*](http://www.php.net/manual/en/language.variables.superglobals.php)), so you can pass it as a function parameter, pass it around and even change it (even though this might not be wise in most situations). Regarding your code, I'd change it a bit to make it more clear: ``` PostInfo($_POST); function PostInfo($postVars) { $item1 = $postVars[0]; $item2 = $postVars[1]; $item3 = $postVars[2]; //do something return $result; } ``` This will visibly separate the function argument from the `$_POST` superglobal. Another option would be to simple remove the function argument and rely on the superglobal-abilities of `$_POST`: ``` PostInfo(); function PostInfo() { $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } ```
1,660,912
Can i pass the entire POST array into a function and handle it within the function? such as ``` PostInfo($_POST); function PostInfo($_POST){ $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } ``` or is this the correct way of doing this?
2009/11/02
[ "https://Stackoverflow.com/questions/1660912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115949/" ]
You can actually pass $\_POST to any function which takes in an array. ``` function process(array $request) { } process($_POST); process($_GET); ``` Great for testing.
The [`$_POST`-array](http://www.php.net/manual/en/reserved.variables.post.php) is an array like every other array in PHP (besides being a so-called [*superglobal*](http://www.php.net/manual/en/language.variables.superglobals.php)), so you can pass it as a function parameter, pass it around and even change it (even though this might not be wise in most situations). Regarding your code, I'd change it a bit to make it more clear: ``` PostInfo($_POST); function PostInfo($postVars) { $item1 = $postVars[0]; $item2 = $postVars[1]; $item3 = $postVars[2]; //do something return $result; } ``` This will visibly separate the function argument from the `$_POST` superglobal. Another option would be to simple remove the function argument and rely on the superglobal-abilities of `$_POST`: ``` PostInfo(); function PostInfo() { $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } ```
675,032
I'm currently running some intensive SELECT queries against a MyISAM table. The table is around 100 MiB (800,000 rows) and it never changes. I need to increase the performance of my script, so I was thinking on moving the table from MyISAM to the MEMORY storage engine, so I could load it completely into the memory. Besides the MEMORY storage engine, what are my options to load a 100 MiB table into the memory?
2009/03/23
[ "https://Stackoverflow.com/questions/675032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81620/" ]
A table with 800k rows shouldn't be any problem to mysql, no matter what storage engine you are using. With a size of 100 MB the full table (data and keys) should live in memory (mysql key cache, OS file cache, or propably in both). First you check the indices. In most cases, optimizing the indices gives you the best performance boost. Never do anything else, unless you are pretty sure they are in shape. Invoke the queries using `EXPLAIN` and watch for cases where no or the wrong index is used. This should be done with real world data and not on a server with test data. After you optimized your indices the queries should finish by a fraction of a second. If the queries are still too slow then just try to avoid running them by using a cache in your application (memcached, etc.). Given that the data in the table never changes there shouldn't be any problems with old cache data etc.
Assuming the data rarely changes, you could potentially boost the performance of queries significantly using [MySql query caching](http://dev.mysql.com/doc/refman/5.1/en/query-cache.html).
675,032
I'm currently running some intensive SELECT queries against a MyISAM table. The table is around 100 MiB (800,000 rows) and it never changes. I need to increase the performance of my script, so I was thinking on moving the table from MyISAM to the MEMORY storage engine, so I could load it completely into the memory. Besides the MEMORY storage engine, what are my options to load a 100 MiB table into the memory?
2009/03/23
[ "https://Stackoverflow.com/questions/675032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81620/" ]
A table with 800k rows shouldn't be any problem to mysql, no matter what storage engine you are using. With a size of 100 MB the full table (data and keys) should live in memory (mysql key cache, OS file cache, or propably in both). First you check the indices. In most cases, optimizing the indices gives you the best performance boost. Never do anything else, unless you are pretty sure they are in shape. Invoke the queries using `EXPLAIN` and watch for cases where no or the wrong index is used. This should be done with real world data and not on a server with test data. After you optimized your indices the queries should finish by a fraction of a second. If the queries are still too slow then just try to avoid running them by using a cache in your application (memcached, etc.). Given that the data in the table never changes there shouldn't be any problems with old cache data etc.
If your table is queried a lot it's probably already cached at the operating system level, depending on how much memory is in your server. MyISAM also allows for preloading MyISAM table indices into memory using a mechanism called the [MyISAM Key Cache](http://dev.mysql.com/doc/refman/5.1/en/myisam-key-cache.html). After you've created a key cache you can load an index into the cache using the [CACHE INDEX](http://dev.mysql.com/doc/refman/5.1/en/cache-index.html) or [LOAD INDEX](http://dev.mysql.com/doc/refman/5.1/en/load-index.html) syntax. I assume that you've analyzed your table and queries and optimized your indices after the actual queries? Otherwise that's really something you should do before attempting to store the entire table in memory.
675,032
I'm currently running some intensive SELECT queries against a MyISAM table. The table is around 100 MiB (800,000 rows) and it never changes. I need to increase the performance of my script, so I was thinking on moving the table from MyISAM to the MEMORY storage engine, so I could load it completely into the memory. Besides the MEMORY storage engine, what are my options to load a 100 MiB table into the memory?
2009/03/23
[ "https://Stackoverflow.com/questions/675032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81620/" ]
A table with 800k rows shouldn't be any problem to mysql, no matter what storage engine you are using. With a size of 100 MB the full table (data and keys) should live in memory (mysql key cache, OS file cache, or propably in both). First you check the indices. In most cases, optimizing the indices gives you the best performance boost. Never do anything else, unless you are pretty sure they are in shape. Invoke the queries using `EXPLAIN` and watch for cases where no or the wrong index is used. This should be done with real world data and not on a server with test data. After you optimized your indices the queries should finish by a fraction of a second. If the queries are still too slow then just try to avoid running them by using a cache in your application (memcached, etc.). Given that the data in the table never changes there shouldn't be any problems with old cache data etc.
If you have enough memory allocated for Mysql's use - in the Innodb buffer pool, or for use by MyIsam, you can read the database into memory (just a 'SELECT \* from tablename') and if there's no reason to remove it, it stays there. You also get better key use, as the MEMORY table only does hash-bashed keys, rather than full btree access, which for smaller, non-unique keys might be fats enough, or not so much with such a large table. As usual, the best thing to do it to benchmark it. Another idea is, if you are using v5.1, to use an ARCHIVE table type, which can be compressed, and may also speed access to the contents, if they are easily compressible. This swaps the CPU time to de-compress for IO/memory access.
675,032
I'm currently running some intensive SELECT queries against a MyISAM table. The table is around 100 MiB (800,000 rows) and it never changes. I need to increase the performance of my script, so I was thinking on moving the table from MyISAM to the MEMORY storage engine, so I could load it completely into the memory. Besides the MEMORY storage engine, what are my options to load a 100 MiB table into the memory?
2009/03/23
[ "https://Stackoverflow.com/questions/675032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81620/" ]
A table with 800k rows shouldn't be any problem to mysql, no matter what storage engine you are using. With a size of 100 MB the full table (data and keys) should live in memory (mysql key cache, OS file cache, or propably in both). First you check the indices. In most cases, optimizing the indices gives you the best performance boost. Never do anything else, unless you are pretty sure they are in shape. Invoke the queries using `EXPLAIN` and watch for cases where no or the wrong index is used. This should be done with real world data and not on a server with test data. After you optimized your indices the queries should finish by a fraction of a second. If the queries are still too slow then just try to avoid running them by using a cache in your application (memcached, etc.). Given that the data in the table never changes there shouldn't be any problems with old cache data etc.
If the data never changes you could easily duplicate the table over several database servers. This way you could offload some queries to a different server, gaining some extra breathing room for the main server. The speed improvement depends on the current database load, there will be no improvement if your database load is very low. PS: You are aware that MEMORY tables forget their contents when the database restarts!
2,636,807
I am retrieving an flashvars object from JSP file. Like `userid = mx.core.Application.application.parameters.userJspid;`like this it is retrieving in IE browser. But not in FF (Mozilla), why it’s not retrieving is there any code i need to add it for Mozilla specially. Please help me in this, Thanks in advance. i am loading in jsp like `<body scroll="no" onload="openWin();"> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="main" width="100%" height="100%" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"> <param name="movie" value="main.swf"/> <param name="quality" value="high"/> <param name="bgcolor" value="#ffffff"/> <param name="allowScriptAccess" value="sameDomain"/> <param name="FlashVars" value="userNid=<%=session.getAttribute("userNid")%>"/> <embed src="main.swf" quality="high" bgcolor="#ffffff"width="100%" height="100%" name="main" align="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"></embed> </object> </body>`like this
2010/04/14
[ "https://Stackoverflow.com/questions/2636807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159237/" ]
With the embe method you are using above, the flashVars are not represented in the portion of the whole embed code. When Firefox is reading this it is only processing attributes associated with , which is why you duplicate things like quality, bgcolor, etc. Try also duplicating the flashVars within and that should work.
I'd try replacing: ``` <param name="FlashVars" value="userNid=<%=session.getAttribute("userNid")%>"/> ``` with ``` <param name="FlashVars" value="userNid=<%=session.getAttribute('userNid')%>"/> ```
2,854,925
Why would there be a "Conversion Errors" table in an MDB? Does this mean there was an attempt to convert the MDB to a different (newer) version of Access?
2010/05/18
[ "https://Stackoverflow.com/questions/2854925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
Yes. [About the Conversion Errors table](http://office.microsoft.com/en-au/access/HP030843301033.aspx)
Seems to me that the only place a Conversion Errors table could reside would be in the *converted* file, not in the original. But I could be wrong on that. I've never seen one myself.
2,854,925
Why would there be a "Conversion Errors" table in an MDB? Does this mean there was an attempt to convert the MDB to a different (newer) version of Access?
2010/05/18
[ "https://Stackoverflow.com/questions/2854925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327528/" ]
my crystal ball tells me that you have opened the file with a newer access version, possibly 2007 or 2010 and you have conversion error on the table saying that some kind of driver is missing... something like > > Missing VBE reference to file MSJETSQL.TLB. > > > but my powers cannot go no further. Be more specific on which errors you have in the table.
Seems to me that the only place a Conversion Errors table could reside would be in the *converted* file, not in the original. But I could be wrong on that. I've never seen one myself.
53,435
I'm doing something bad in my ASP.NET app. It could be the any number of CTP libraries I'm using or I'm just not disposing something properly. But when I redeploy my ASP.NET to my Vista IIS7 install or my server's IIS6 install I crash an IIS worker process. I've narrowed the problem down to my HTTP crawler, which is a multithreaded beast that crawls sites for useful information when asked to. After I start a crawler and redeploy the app over the top, rather than gracefully unloading the appDomain and reloading, an IIS worker process will crash (popping up a crash message) and continue reloading the app domain. When this crash happens, where can I find the crash dump for analysis?
2008/09/10
[ "https://Stackoverflow.com/questions/53435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
Download Debugging tools for Windows: <http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx> Debugging Tools for Windows has has a script (ADPLUS) that allows you to create dumps when a process CRASHES: <http://support.microsoft.com/kb/286350> The command should be something like (if you are using IIS6): ``` cscript adplus.vbs -crash -pn w3wp.exe ``` This command will attach the debugger to the worker process. When the crash occurs it will generate a dump (a \*.DMP file). You can open it in WinDBG (also included in the Debugging Tools for Windows). File > Open Crash dump... By default, WinDBG will show you (next to the command line) the thread were the process crashed. The first thing you need to do in WinDBG is to load the .NET Framework extensions: ``` .loadby sos mscorwks ``` then, you will display the managed callstack: ``` !clrstack ``` if the thread was not running managed code, then you'll need to check the native stack: ``` kpn 200 ``` This should give you some ideas. To continue troubleshooting I recommend you read the following article: <http://msdn.microsoft.com/en-us/library/ee817663.aspx>
A quick search found [IISState](http://www.iisfaq.com/default.aspx?view=P197) - it relies on the [Windows debugging tools](http://www.microsoft.com/whdc/devtools/debugging/default.mspx) and needs to be running when a crash occurs, but given the circumstances you've described, this shouldn't be a problem,
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
No real difference today, but `@import` is not handled correctly by older browsers (Netscape 4, etc.), so the [`@import` hack](https://web.archive.org/web/20140117190832/http://css-discuss.incutio.com/wiki/Import_Hack) can be used to hide CSS 2 rules from these old browsers. Again, unless you're supporting really old browsers, there isn't a difference. If I were you, however, I'd use the `<link>` variant on your HTML pages, because it allows you to specify things like media type (print, screen, etc.).
one html, the other css code If you haven't used saddle html tags then you need to use @import
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In theory, the only difference between them is that `@import` is the CSS mechanism to include a style sheet and `<link>` the HTML mechanism. However, browsers handle them differently, giving `<link>` a clear advantage in terms of performance. Steve Souders wrote an extensive blog post comparing the impact of both `<link>` and `@import` (and all sorts of combinations of them) called "[don’t use @import](http://www.stevesouders.com/blog/2009/04/09/dont-use-import/)". That title pretty much speaks for itself. Yahoo! also mentions it as one of their performance best practices (co-authored by Steve Souders): [Choose `<link>` over @import](https://developer.yahoo.com/performance/rules.html#csslink) Also, using the `<link>` tag allows you to define ["preferred" and alternate stylesheets](https://alistapart.com/article/alternate/). You can't do that with `@import`.
one html, the other css code If you haven't used saddle html tags then you need to use @import
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
@import is generally meant to be used in an external stylesheet rather than inline like in your example. If you *really* wanted to hide a stylesheet from very old browsers you could use that as a hack to prevent them from using that stylesheet.  Overall, the `<link>` tag is processed more quickly than the @import rule (which is apparently somewhat slow as far as the css processing engine is concerned).
one html, the other css code If you haven't used saddle html tags then you need to use @import
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When I use the @import rule, it's generally to import a stylesheet within an existing stylesheet (although I dislike doing it to begin with). But to answer your question, no I don't believe there's any difference. Just make sure to put the URL in double quotes in order to comply with valid XHTML.
one html, the other css code If you haven't used saddle html tags then you need to use @import
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
No real difference today, but `@import` is not handled correctly by older browsers (Netscape 4, etc.), so the [`@import` hack](https://web.archive.org/web/20140117190832/http://css-discuss.incutio.com/wiki/Import_Hack) can be used to hide CSS 2 rules from these old browsers. Again, unless you're supporting really old browsers, there isn't a difference. If I were you, however, I'd use the `<link>` variant on your HTML pages, because it allows you to specify things like media type (print, screen, etc.).
Microsoft Internet Explorer 9 (MSIE9) doesn't seem to handle @import properly. Observe these entries from my Apache log (IP address hidden but `whois` said it was owned by Microsoft itself): the main HTML linked to screen.css which had ``` @import url("print.css") print; @import url("speech.css") aural; ``` which I am now about to change to `link` elements in the HTML, because it seems MSIE9 issues two incorrect requests to the server, getting 404 errors I could do without: ``` [ip] - - [21/Dec/2019:05:49:28 +0000] "GET /screen.css HTTP/1.1" 200 2592 "https://ssb22.user.srcf.net/zhimo/"; "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)" ssb22.user.srcf.net [ip] - - [21/Dec/2019:05:49:28 +0000] "GET /url(%22print.css%22)%20print HTTP/1.1" 404 7498 "https://ssb22.user.srcf.net/zhimo/"; "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)" ssb22.user.srcf.net [ip] - - [21/Dec/2019:05:49:28 +0000] "GET /url(%22speech.css%22)%20aural HTTP/1.1" 404 7498 "https://ssb22.user.srcf.net/zhimo/"; "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)" ssb22.user.srcf.net ``` There *were* proper requests for these files afterwards, but we can do without this "shoot at server first, parse `url` after" logic.
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In theory, the only difference between them is that `@import` is the CSS mechanism to include a style sheet and `<link>` the HTML mechanism. However, browsers handle them differently, giving `<link>` a clear advantage in terms of performance. Steve Souders wrote an extensive blog post comparing the impact of both `<link>` and `@import` (and all sorts of combinations of them) called "[don’t use @import](http://www.stevesouders.com/blog/2009/04/09/dont-use-import/)". That title pretty much speaks for itself. Yahoo! also mentions it as one of their performance best practices (co-authored by Steve Souders): [Choose `<link>` over @import](https://developer.yahoo.com/performance/rules.html#csslink) Also, using the `<link>` tag allows you to define ["preferred" and alternate stylesheets](https://alistapart.com/article/alternate/). You can't do that with `@import`.
You can use the import command to import another CSS inside a css file which is not possible with the link command. Really old browser cannot (IE4, IE5 partially) handle the import functionality. Additionally some libraries parsing your xhtml/html could fail in getting the style sheet import. Please be aware that your import should come before all other CSS declarations.
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the import command to import another CSS inside a css file which is not possible with the link command. Really old browser cannot (IE4, IE5 partially) handle the import functionality. Additionally some libraries parsing your xhtml/html could fail in getting the style sheet import. Please be aware that your import should come before all other CSS declarations.
When I use the @import rule, it's generally to import a stylesheet within an existing stylesheet (although I dislike doing it to begin with). But to answer your question, no I don't believe there's any difference. Just make sure to put the URL in double quotes in order to comply with valid XHTML.
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
@import is generally meant to be used in an external stylesheet rather than inline like in your example. If you *really* wanted to hide a stylesheet from very old browsers you could use that as a hack to prevent them from using that stylesheet.  Overall, the `<link>` tag is processed more quickly than the @import rule (which is apparently somewhat slow as far as the css processing engine is concerned).
Microsoft Internet Explorer 9 (MSIE9) doesn't seem to handle @import properly. Observe these entries from my Apache log (IP address hidden but `whois` said it was owned by Microsoft itself): the main HTML linked to screen.css which had ``` @import url("print.css") print; @import url("speech.css") aural; ``` which I am now about to change to `link` elements in the HTML, because it seems MSIE9 issues two incorrect requests to the server, getting 404 errors I could do without: ``` [ip] - - [21/Dec/2019:05:49:28 +0000] "GET /screen.css HTTP/1.1" 200 2592 "https://ssb22.user.srcf.net/zhimo/"; "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)" ssb22.user.srcf.net [ip] - - [21/Dec/2019:05:49:28 +0000] "GET /url(%22print.css%22)%20print HTTP/1.1" 404 7498 "https://ssb22.user.srcf.net/zhimo/"; "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)" ssb22.user.srcf.net [ip] - - [21/Dec/2019:05:49:28 +0000] "GET /url(%22speech.css%22)%20aural HTTP/1.1" 404 7498 "https://ssb22.user.srcf.net/zhimo/"; "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)" ssb22.user.srcf.net ``` There *were* proper requests for these files afterwards, but we can do without this "shoot at server first, parse `url` after" logic.
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In theory, the only difference between them is that `@import` is the CSS mechanism to include a style sheet and `<link>` the HTML mechanism. However, browsers handle them differently, giving `<link>` a clear advantage in terms of performance. Steve Souders wrote an extensive blog post comparing the impact of both `<link>` and `@import` (and all sorts of combinations of them) called "[don’t use @import](http://www.stevesouders.com/blog/2009/04/09/dont-use-import/)". That title pretty much speaks for itself. Yahoo! also mentions it as one of their performance best practices (co-authored by Steve Souders): [Choose `<link>` over @import](https://developer.yahoo.com/performance/rules.html#csslink) Also, using the `<link>` tag allows you to define ["preferred" and alternate stylesheets](https://alistapart.com/article/alternate/). You can't do that with `@import`.
No real difference today, but `@import` is not handled correctly by older browsers (Netscape 4, etc.), so the [`@import` hack](https://web.archive.org/web/20140117190832/http://css-discuss.incutio.com/wiki/Import_Hack) can be used to hide CSS 2 rules from these old browsers. Again, unless you're supporting really old browsers, there isn't a difference. If I were you, however, I'd use the `<link>` variant on your HTML pages, because it allows you to specify things like media type (print, screen, etc.).
1,022,714
Is it possible to use the: ``` [NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething]; ``` In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file? for example: I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array. ``` NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:@"One",@"Two",nil]; [arrayToWrite writeToURL: [NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"] atomically:YES]; ``` And at runtime: ``` NSMutableArray *arrayToRead = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:@"mywebsite.atwebpages.com/myArray.plist"]]; ``` Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly. A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
2009/06/20
[ "https://Stackoverflow.com/questions/1022714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use the import command to import another CSS inside a css file which is not possible with the link command. Really old browser cannot (IE4, IE5 partially) handle the import functionality. Additionally some libraries parsing your xhtml/html could fail in getting the style sheet import. Please be aware that your import should come before all other CSS declarations.
one html, the other css code If you haven't used saddle html tags then you need to use @import
1,883,090
I have a problem with my jsp file... inside it I have a form and in that form I have an onsubmit method that is basically calling a javascript... the problem is that whenever I click on a button it always redirects me to the page, whether it's true or false
2009/12/10
[ "https://Stackoverflow.com/questions/1883090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229054/" ]
You probably need to **return false** after the javascript processing which is bound on the button click.
I guess, you are using "Submit" button and thus form gets submitted anyway. Use a normal button set onclick event for that and write form submitting code in java script function. May this help.
1,883,090
I have a problem with my jsp file... inside it I have a form and in that form I have an onsubmit method that is basically calling a javascript... the problem is that whenever I click on a button it always redirects me to the page, whether it's true or false
2009/12/10
[ "https://Stackoverflow.com/questions/1883090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229054/" ]
what cherouvim said. also, in the case that the onsubmit handler already should be returning false, if there's any javascript error in the handler, then the return statement may never get evaluated and the form will submit.
I guess, you are using "Submit" button and thus form gets submitted anyway. Use a normal button set onclick event for that and write form submitting code in java script function. May this help.
1,883,090
I have a problem with my jsp file... inside it I have a form and in that form I have an onsubmit method that is basically calling a javascript... the problem is that whenever I click on a button it always redirects me to the page, whether it's true or false
2009/12/10
[ "https://Stackoverflow.com/questions/1883090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229054/" ]
You likely have something like: ``` <form onsubmit="someFunction()"> ``` instead of ``` <form onsubmit="return someFunction()"> ``` Fix it accordingly.
I guess, you are using "Submit" button and thus form gets submitted anyway. Use a normal button set onclick event for that and write form submitting code in java script function. May this help.
2,222,511
Is there a way to inspect HTTPS traffic from Flex applications compiled to SWF files? I'm trying to use Fiddler for this, have added `DO_NOT_TRUST_FiddlerRoot` to my *Trusted Root Certification Authorities* so my IE now can access other HTML sites that would normally complain about untrusted certificate. However, the HTTPS traffic from the SWF file still doesn't appear in Fiddler and, in fact, the Flex app wouldn't work (HTTPS with a self-signed certificate is not supported by Flex apps I believe). Is there a way around it? **Update**: To be clear, I am interested in the traffic between the SWF file running under Flash Player and the server (typically, Flex components like HTTPService will be used for this). The SWF file itself can be served via HTTP or HTTPS, it doesn't really matter. **Clarification 2**: Don't assume that the source code is available for the SWF file. If it was, Flash Builder 4's Network Monitor could be used. (I am assessing possible security risks for my client just to be clear about my intentions.)
2010/02/08
[ "https://Stackoverflow.com/questions/2222511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21728/" ]
Try [Charles Proxy](http://www.charlesproxy.com/) it works with both HTTPS and AMF. There's a free version with some minor annoyances. To get it working with ssl you need to go to Proxy->Proxy Settings->SSL and add the domain which traffic you want to monitor. ---- From the comment ---- If you have the original certificate, you can set it up in Proxy->SSL Certificate, and it will be ued by Charles, which should lead to no more errors (as the proxy will have the proper certificate).
Adobe's Flash Builder 4 Beta has a built in Network Monitor. Learn more here: [Flash Builder 4 beta](http://labs.adobe.com/technologies/flashbuilder4/) According to the documentation: ([Support for HTTPS protocol](http://tinyurl.com/yfh2k2g)) ``` The Network Monitor supports monitoring HTTPS calls to a server certified by a certificate authority (CA) or that has a self-signed certificate. To monitor calls over the HTTPS protocol, modify the default preference for the Network Monitor to ignore SSL security checks. Open the Preferences dialog and navigate to Flash Builder > Network Monitor. ```
2,222,511
Is there a way to inspect HTTPS traffic from Flex applications compiled to SWF files? I'm trying to use Fiddler for this, have added `DO_NOT_TRUST_FiddlerRoot` to my *Trusted Root Certification Authorities* so my IE now can access other HTML sites that would normally complain about untrusted certificate. However, the HTTPS traffic from the SWF file still doesn't appear in Fiddler and, in fact, the Flex app wouldn't work (HTTPS with a self-signed certificate is not supported by Flex apps I believe). Is there a way around it? **Update**: To be clear, I am interested in the traffic between the SWF file running under Flash Player and the server (typically, Flex components like HTTPService will be used for this). The SWF file itself can be served via HTTP or HTTPS, it doesn't really matter. **Clarification 2**: Don't assume that the source code is available for the SWF file. If it was, Flash Builder 4's Network Monitor could be used. (I am assessing possible security risks for my client just to be clear about my intentions.)
2010/02/08
[ "https://Stackoverflow.com/questions/2222511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21728/" ]
Try [Charles Proxy](http://www.charlesproxy.com/) it works with both HTTPS and AMF. There's a free version with some minor annoyances. To get it working with ssl you need to go to Proxy->Proxy Settings->SSL and add the domain which traffic you want to monitor. ---- From the comment ---- If you have the original certificate, you can set it up in Proxy->SSL Certificate, and it will be ued by Charles, which should lead to no more errors (as the proxy will have the proper certificate).
Interestingly, Fiddler started to show HTTPS requests today. The Flex app behaves like it couldn't access the server side (which is probably because the response from Fiddler is signed with a self-signed certificate which Flash Player correctly recognizes as different than the target site certificate) but still, the HTTP request has been sent already and is visible via Fiddler. Also, Robert Bak suggested that **Charles Proxy can use the target site's certificate** which I guess would be by far the best method (I didn't try it as the Fiddler experiment already proved enough for us).
2,222,511
Is there a way to inspect HTTPS traffic from Flex applications compiled to SWF files? I'm trying to use Fiddler for this, have added `DO_NOT_TRUST_FiddlerRoot` to my *Trusted Root Certification Authorities* so my IE now can access other HTML sites that would normally complain about untrusted certificate. However, the HTTPS traffic from the SWF file still doesn't appear in Fiddler and, in fact, the Flex app wouldn't work (HTTPS with a self-signed certificate is not supported by Flex apps I believe). Is there a way around it? **Update**: To be clear, I am interested in the traffic between the SWF file running under Flash Player and the server (typically, Flex components like HTTPService will be used for this). The SWF file itself can be served via HTTP or HTTPS, it doesn't really matter. **Clarification 2**: Don't assume that the source code is available for the SWF file. If it was, Flash Builder 4's Network Monitor could be used. (I am assessing possible security risks for my client just to be clear about my intentions.)
2010/02/08
[ "https://Stackoverflow.com/questions/2222511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21728/" ]
Interestingly, Fiddler started to show HTTPS requests today. The Flex app behaves like it couldn't access the server side (which is probably because the response from Fiddler is signed with a self-signed certificate which Flash Player correctly recognizes as different than the target site certificate) but still, the HTTP request has been sent already and is visible via Fiddler. Also, Robert Bak suggested that **Charles Proxy can use the target site's certificate** which I guess would be by far the best method (I didn't try it as the Fiddler experiment already proved enough for us).
Adobe's Flash Builder 4 Beta has a built in Network Monitor. Learn more here: [Flash Builder 4 beta](http://labs.adobe.com/technologies/flashbuilder4/) According to the documentation: ([Support for HTTPS protocol](http://tinyurl.com/yfh2k2g)) ``` The Network Monitor supports monitoring HTTPS calls to a server certified by a certificate authority (CA) or that has a self-signed certificate. To monitor calls over the HTTPS protocol, modify the default preference for the Network Monitor to ignore SSL security checks. Open the Preferences dialog and navigate to Flash Builder > Network Monitor. ```
1,622,559
I created a very very basic iPhone app with File/New Projet/View-Based application. No NIB file there. Here is my appDelegate .h ``` @interface MyAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; MyViewController *viewController; } ``` .m ``` - (void)applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after app launch [window addSubview:viewController.view]; [window makeKeyAndVisible]; } ``` And here is my loadView method in my controller ``` - (void)loadView { CGRect mainFrame = [[UIScreen mainScreen] applicationFrame]; UIView *contentView = [[UIView alloc] initWithFrame:mainFrame]; contentView.backgroundColor = [UIColor redColor]; self.view = contentView; [contentView release]; } ``` Now, in order to catch the touchesBegan event, I created a new subclass of UIView: .h ``` @interface TouchView : UIView { } ``` .m ``` - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSLog(@"Touch detected"); } ``` and modified the second line in my loadView into this : ``` TouchView *contentView = [[UIView alloc] initWithFrame:mainFrame]; ``` Why is touchesBegan never called?
2009/10/26
[ "https://Stackoverflow.com/questions/1622559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196359/" ]
If you change the loadView into this: ``` TouchView *contentView = [[TouchView alloc] initWithFrame:mainFrame]; ``` You should have no problem catching the touches in TouchView. In your code, you didn't create a TouchView instance, you created a UIView instance.
Found the solution : touchesBegan gets called on the viewController, not on the view...
775,474
Other than MongoDB and Memcached, what key-value stores run on Windows? Most of the ones I've seen seem to only run on Linux (Hypertable, Redis, Lightcloud). Related links: [Is there a business proven cloud store / Key=>Value Database? (Open Source)](https://stackoverflow.com/questions/639545/is-there-a-business-proven-cloud-store-keyvalue-database-open-source) <http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/>
2009/04/22
[ "https://Stackoverflow.com/questions/775474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
[Berkeley DB](http://en.wikipedia.org/wiki/Berkeley_DB) is [available](http://www.oracle.com/technology/products/berkeley-db/index.html). I'm surprised no-one has mentioned it yet. You can build it on Windows either with a native or Cygwin toolchain, but it's probably best with MSVC if you're going to be linking it with `C#`.
Redis is C99 (Posix). It should be trivial to build and run it on cygwin.
775,474
Other than MongoDB and Memcached, what key-value stores run on Windows? Most of the ones I've seen seem to only run on Linux (Hypertable, Redis, Lightcloud). Related links: [Is there a business proven cloud store / Key=>Value Database? (Open Source)](https://stackoverflow.com/questions/639545/is-there-a-business-proven-cloud-store-keyvalue-database-open-source) <http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/>
2009/04/22
[ "https://Stackoverflow.com/questions/775474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
I would take a look at this article from [highscalability.com](http://highscalability.com/drop-acid-and-think-about-data). It describes a few options that you may want to consider, including [Tokyo Cabinet/Tyrant](http://tokyocabinet.sourceforge.net/), [CouchDB](http://couchdb.apache.org/) and [MongoDB](http://www.mongodb.org/display/DOCS/Home).
[Berkeley DB](http://en.wikipedia.org/wiki/Berkeley_DB) is [available](http://www.oracle.com/technology/products/berkeley-db/index.html). I'm surprised no-one has mentioned it yet. You can build it on Windows either with a native or Cygwin toolchain, but it's probably best with MSVC if you're going to be linking it with `C#`.
775,474
Other than MongoDB and Memcached, what key-value stores run on Windows? Most of the ones I've seen seem to only run on Linux (Hypertable, Redis, Lightcloud). Related links: [Is there a business proven cloud store / Key=>Value Database? (Open Source)](https://stackoverflow.com/questions/639545/is-there-a-business-proven-cloud-store-keyvalue-database-open-source) <http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/>
2009/04/22
[ "https://Stackoverflow.com/questions/775474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
[Berkeley DB](http://en.wikipedia.org/wiki/Berkeley_DB) is [available](http://www.oracle.com/technology/products/berkeley-db/index.html). I'm surprised no-one has mentioned it yet. You can build it on Windows either with a native or Cygwin toolchain, but it's probably best with MSVC if you're going to be linking it with `C#`.
Here is the CouchDb installer for Windows <http://people.apache.org/~mhammond/dist/0.11.0/>
775,474
Other than MongoDB and Memcached, what key-value stores run on Windows? Most of the ones I've seen seem to only run on Linux (Hypertable, Redis, Lightcloud). Related links: [Is there a business proven cloud store / Key=>Value Database? (Open Source)](https://stackoverflow.com/questions/639545/is-there-a-business-proven-cloud-store-keyvalue-database-open-source) <http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/>
2009/04/22
[ "https://Stackoverflow.com/questions/775474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
I would take a look at this article from [highscalability.com](http://highscalability.com/drop-acid-and-think-about-data). It describes a few options that you may want to consider, including [Tokyo Cabinet/Tyrant](http://tokyocabinet.sourceforge.net/), [CouchDB](http://couchdb.apache.org/) and [MongoDB](http://www.mongodb.org/display/DOCS/Home).
Redis is C99 (Posix). It should be trivial to build and run it on cygwin.
775,474
Other than MongoDB and Memcached, what key-value stores run on Windows? Most of the ones I've seen seem to only run on Linux (Hypertable, Redis, Lightcloud). Related links: [Is there a business proven cloud store / Key=>Value Database? (Open Source)](https://stackoverflow.com/questions/639545/is-there-a-business-proven-cloud-store-keyvalue-database-open-source) <http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/>
2009/04/22
[ "https://Stackoverflow.com/questions/775474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16605/" ]
I would take a look at this article from [highscalability.com](http://highscalability.com/drop-acid-and-think-about-data). It describes a few options that you may want to consider, including [Tokyo Cabinet/Tyrant](http://tokyocabinet.sourceforge.net/), [CouchDB](http://couchdb.apache.org/) and [MongoDB](http://www.mongodb.org/display/DOCS/Home).
Here is the CouchDb installer for Windows <http://people.apache.org/~mhammond/dist/0.11.0/>
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
There's no native support for this. I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post: <http://www.west-wind.com/Weblog/posts/698097.aspx> I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.
I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good. ``` using System.Collections; using System.Linq; using System.Resources; using System.Web.Mvc; using System.Web.Script.Serialization; public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript(string resxFileName) { var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx")) .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json); return JavaScript(javaScript); } } // In the RegisterRoutes method in Global.asax: routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" }); ``` So I can do ``` <script src="/resources/Foo.js"></script> ``` and then my scripts can reference e.g. `window.Resources.Foo.Bar` and get a string.
Add the function in the BasePage class: ``` protected string GetLanguageText(string _key) { System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources")); return _resourceTemp.GetString(_key); } ``` Javascript: ``` var _resurceValue = "<%=GetLanguageText("UserName")%>"; ``` --- or direct use: ``` var _resurceValue = "<%= Resources.Language.UserName %>"; ``` Note: The Language is my resouce name. Exam: Language.resx and Language.en-US.resx
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
whereas "Common" is the name of the resource file and Msg1 is the fieldname. This also works for culture changes. ``` Partial Javascript...: messages: { <%=txtRequiredField.UniqueID %>:{ required: "<%=Resources.Common.Msg1 %>", maxlength: "Only 50 character allowed in required field." } } ```
use a hidden field to hold the resource string value and then access the field value in javascript for example : " /> var todayString= $("input[name=TodayString][type=hidden]").val();
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good. ``` using System.Collections; using System.Linq; using System.Resources; using System.Web.Mvc; using System.Web.Script.Serialization; public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript(string resxFileName) { var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx")) .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json); return JavaScript(javaScript); } } // In the RegisterRoutes method in Global.asax: routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" }); ``` So I can do ``` <script src="/resources/Foo.js"></script> ``` and then my scripts can reference e.g. `window.Resources.Foo.Bar` and get a string.
If you have your resources in a separate assembly you can use the `ResourceSet` instead of the filename. Building on @Domenics great answer: ``` public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript() { // This avoids the file path dependency. ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); // Create dictionary. var resourceDictionary = resourceSet .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json); return JavaScript(javaScript); } } ``` **The downside is that this will not enable more than one resource-file per action. In that way @Domenics answer is more generic and reusable.** You may also consider using `OutputCache`, since the resource won't change a lot between requests. ``` [OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)] public ActionResult GetResourcesJavaScript() { // Logic here... } ``` <http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs>
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
If you have your resources in a separate assembly you can use the `ResourceSet` instead of the filename. Building on @Domenics great answer: ``` public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript() { // This avoids the file path dependency. ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); // Create dictionary. var resourceDictionary = resourceSet .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json); return JavaScript(javaScript); } } ``` **The downside is that this will not enable more than one resource-file per action. In that way @Domenics answer is more generic and reusable.** You may also consider using `OutputCache`, since the resource won't change a lot between requests. ``` [OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)] public ActionResult GetResourcesJavaScript() { // Logic here... } ``` <http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs>
I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
There's no native support for this. I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post: <http://www.west-wind.com/Weblog/posts/698097.aspx> I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.
In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to: 1) Clear out all the ASP.NET stuff and make it look like a JS file. 2) Set the content-type to "text/javascript" in the codebehind. Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good. ``` using System.Collections; using System.Linq; using System.Resources; using System.Web.Mvc; using System.Web.Script.Serialization; public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript(string resxFileName) { var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx")) .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json); return JavaScript(javaScript); } } // In the RegisterRoutes method in Global.asax: routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" }); ``` So I can do ``` <script src="/resources/Foo.js"></script> ``` and then my scripts can reference e.g. `window.Resources.Foo.Bar` and get a string.
use a hidden field to hold the resource string value and then access the field value in javascript for example : " /> var todayString= $("input[name=TodayString][type=hidden]").val();
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to: 1) Clear out all the ASP.NET stuff and make it look like a JS file. 2) Set the content-type to "text/javascript" in the codebehind. Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.
Add the function in the BasePage class: ``` protected string GetLanguageText(string _key) { System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources")); return _resourceTemp.GetString(_key); } ``` Javascript: ``` var _resurceValue = "<%=GetLanguageText("UserName")%>"; ``` --- or direct use: ``` var _resurceValue = "<%= Resources.Language.UserName %>"; ``` Note: The Language is my resouce name. Exam: Language.resx and Language.en-US.resx
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
If you have your resources in a separate assembly you can use the `ResourceSet` instead of the filename. Building on @Domenics great answer: ``` public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript() { // This avoids the file path dependency. ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); // Create dictionary. var resourceDictionary = resourceSet .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json); return JavaScript(javaScript); } } ``` **The downside is that this will not enable more than one resource-file per action. In that way @Domenics answer is more generic and reusable.** You may also consider using `OutputCache`, since the resource won't change a lot between requests. ``` [OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)] public ActionResult GetResourcesJavaScript() { // Logic here... } ``` <http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs>
use a hidden field to hold the resource string value and then access the field value in javascript for example : " /> var todayString= $("input[name=TodayString][type=hidden]").val();
940,769
How would one get resx resource strings into javascript code stored in a .js file? If your javascript is in a script block in the markup, you can use this syntax: ``` <%$Resources:Resource, FieldName %> ``` and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed. I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active. One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser? Or does anyone have any other suggestions?
2009/06/02
[ "https://Stackoverflow.com/questions/940769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12975/" ]
If you have your resources in a separate assembly you can use the `ResourceSet` instead of the filename. Building on @Domenics great answer: ``` public class ResourcesController : Controller { private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer(); public ActionResult GetResourcesJavaScript() { // This avoids the file path dependency. ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); // Create dictionary. var resourceDictionary = resourceSet .Cast<DictionaryEntry>() .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString()); var json = Serializer.Serialize(resourceDictionary); var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json); return JavaScript(javaScript); } } ``` **The downside is that this will not enable more than one resource-file per action. In that way @Domenics answer is more generic and reusable.** You may also consider using `OutputCache`, since the resource won't change a lot between requests. ``` [OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)] public ActionResult GetResourcesJavaScript() { // Logic here... } ``` <http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs>
I the brown field application I'm working on we have an xslt that transforms the resx file into a javascript file as part of the build process. This works well since this is a web application. I'm not sure if the original question is a web application.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Ryan Barrett wrote up his findings on [his blog](http://snarfed.org/space/synchronizing_mp3_playback). His solution involved using [NTP](http://en.wikipedia.org/wiki/Network_Time_Protocol) as a method to keep all the clocks in-sync: > > Seriously, though, there's only one > trick to p4sync, and that is how it > uses NTP. One host acts as the p4sync > server. The other p4sync clients > synchronize their system clocks to the > server's clock, using SNTP. When the > server starts playing a song, it > records the time, to the millisecond. > The clients then retrieve that > timestamp, calculate the difference > between current time from that > timestamp, and seek forward that far > into the song. > > >
"...as long as it is perceived to be in sync by a human listener" - Very hard to do because the ear is less forgiving than the eye. Especially if you want to do this over a wireless network. I would experiment first with web based technologies, flash audio players remote controlled by a server via Javascript. If that gave bad results then I would try to get more control by using something like python (with pygame). If progress was being made I would also try using [ChucK](http://chuck.cs.princeton.edu/) and try some low level programming with the ALSA audio library. If nothing satisfactory comes out I would come and revisit this post and actually read something sensible by an expert audio programming guru and, if my livelihood depended on it, probably end up forking the 14 English pounds for the commercial NetChorus application or something similar.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Hard problem, but possible. Use NTP or [tictoc](http://datatracker.ietf.org/wg/tictoc/) to get yourself a synchronised clock with a known rate in terms of your system's time source. Also keep an estimator running as to the rate of your sound clock; the usual way of doing this is to record with the same sound device that is playing, recording over a buffer preloaded with a magic number, and see where the sound card gets to in a measured time by the synchronised clock (or vice versa, see how long it takes to do a known number of samples on the synchronised clock). You need to keep doing this, the clock will drift relative to network time. So now you know exactly how many samples per second by your soundcard's clock you need to output to match the rate of the synchronised clock. So you then interpolate the samples received from the network at that rate, plus or minus a correction if you need to catch up or fall back a bit from where you got to on the last buffer. You will need to be extremely careful about doing this interpolation in such a way that it does not introduce audio artifacts; there is example code [here](http://www.musicdsp.org/) for the algorithms you will need, but it's going to be quite a bit of reading before you get up to speed on that. If your source is a live recording, of course, you're going to have to measure the sample rate of that soundcard and interpolate into network time samples before sending it.
"...as long as it is perceived to be in sync by a human listener" - Very hard to do because the ear is less forgiving than the eye. Especially if you want to do this over a wireless network. I would experiment first with web based technologies, flash audio players remote controlled by a server via Javascript. If that gave bad results then I would try to get more control by using something like python (with pygame). If progress was being made I would also try using [ChucK](http://chuck.cs.princeton.edu/) and try some low level programming with the ALSA audio library. If nothing satisfactory comes out I would come and revisit this post and actually read something sensible by an expert audio programming guru and, if my livelihood depended on it, probably end up forking the 14 English pounds for the commercial NetChorus application or something similar.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Check out the paper [An Internet Protocol Sound System](http://research.microsoft.com/apps/pubs/default.aspx?id=65146) by Tom Blank of Microsoft Research. He solves the exact problem you are working on. His solution involves synchronizing the clocks across machines and using timestamps to let them each play at the same time. The downside of this approach is latency. To get all of the clocks synchronized requires stamping the time at the largest latency on the network.
"...as long as it is perceived to be in sync by a human listener" - Very hard to do because the ear is less forgiving than the eye. Especially if you want to do this over a wireless network. I would experiment first with web based technologies, flash audio players remote controlled by a server via Javascript. If that gave bad results then I would try to get more control by using something like python (with pygame). If progress was being made I would also try using [ChucK](http://chuck.cs.princeton.edu/) and try some low level programming with the ALSA audio library. If nothing satisfactory comes out I would come and revisit this post and actually read something sensible by an expert audio programming guru and, if my livelihood depended on it, probably end up forking the 14 English pounds for the commercial NetChorus application or something similar.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Depending on the size and shape of the venue, getting everything to *be* in sync is the easy part, getting everything to *sound* correct is an art-form in itself, if possible at all. From the technical side, the most difficult part is finding out the delay from your synchronized timeline to actual sound output. Having identical hardware and low latency software framework (ASIO, JACK) certainly helps here, as does calibration. Either ahead of time or active. Otherwise it's just synchronizing the timeline with NTP and using a closed loop feedback to the audio pitch to synchronize the output to the agreed timeline. The larger problem is that sound takes a considerable amount of time to propagate. 10m of difference in distance is already 30ms of delay - enough to screw up sound localization. Double that and you get into the annoying echo territory. Professional audio setups actually purposefully introduce delays, use a higher number of tweeters and play with reverberations to avoid a cacophony of echoes that wears the listener out.
"...as long as it is perceived to be in sync by a human listener" - Very hard to do because the ear is less forgiving than the eye. Especially if you want to do this over a wireless network. I would experiment first with web based technologies, flash audio players remote controlled by a server via Javascript. If that gave bad results then I would try to get more control by using something like python (with pygame). If progress was being made I would also try using [ChucK](http://chuck.cs.princeton.edu/) and try some low level programming with the ALSA audio library. If nothing satisfactory comes out I would come and revisit this post and actually read something sensible by an expert audio programming guru and, if my livelihood depended on it, probably end up forking the 14 English pounds for the commercial NetChorus application or something similar.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Ryan Barrett wrote up his findings on [his blog](http://snarfed.org/space/synchronizing_mp3_playback). His solution involved using [NTP](http://en.wikipedia.org/wiki/Network_Time_Protocol) as a method to keep all the clocks in-sync: > > Seriously, though, there's only one > trick to p4sync, and that is how it > uses NTP. One host acts as the p4sync > server. The other p4sync clients > synchronize their system clocks to the > server's clock, using SNTP. When the > server starts playing a song, it > records the time, to the millisecond. > The clients then retrieve that > timestamp, calculate the difference > between current time from that > timestamp, and seek forward that far > into the song. > > >
Hard problem, but possible. Use NTP or [tictoc](http://datatracker.ietf.org/wg/tictoc/) to get yourself a synchronised clock with a known rate in terms of your system's time source. Also keep an estimator running as to the rate of your sound clock; the usual way of doing this is to record with the same sound device that is playing, recording over a buffer preloaded with a magic number, and see where the sound card gets to in a measured time by the synchronised clock (or vice versa, see how long it takes to do a known number of samples on the synchronised clock). You need to keep doing this, the clock will drift relative to network time. So now you know exactly how many samples per second by your soundcard's clock you need to output to match the rate of the synchronised clock. So you then interpolate the samples received from the network at that rate, plus or minus a correction if you need to catch up or fall back a bit from where you got to on the last buffer. You will need to be extremely careful about doing this interpolation in such a way that it does not introduce audio artifacts; there is example code [here](http://www.musicdsp.org/) for the algorithms you will need, but it's going to be quite a bit of reading before you get up to speed on that. If your source is a live recording, of course, you're going to have to measure the sample rate of that soundcard and interpolate into network time samples before sending it.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Ryan Barrett wrote up his findings on [his blog](http://snarfed.org/space/synchronizing_mp3_playback). His solution involved using [NTP](http://en.wikipedia.org/wiki/Network_Time_Protocol) as a method to keep all the clocks in-sync: > > Seriously, though, there's only one > trick to p4sync, and that is how it > uses NTP. One host acts as the p4sync > server. The other p4sync clients > synchronize their system clocks to the > server's clock, using SNTP. When the > server starts playing a song, it > records the time, to the millisecond. > The clients then retrieve that > timestamp, calculate the difference > between current time from that > timestamp, and seek forward that far > into the song. > > >
Check out the paper [An Internet Protocol Sound System](http://research.microsoft.com/apps/pubs/default.aspx?id=65146) by Tom Blank of Microsoft Research. He solves the exact problem you are working on. His solution involves synchronizing the clocks across machines and using timestamps to let them each play at the same time. The downside of this approach is latency. To get all of the clocks synchronized requires stamping the time at the largest latency on the network.
2,795,031
I'm in startup of designing a client/server audio system which can stream audio arbitrarily over a network. One central server pumps out an audio stream and x number of clients receives the audio data and plays it. So far no magic needed and I have even got this scenario to work with VLC media player out of the box. However, the tricky part seems to be synchronizing the audio playback so that all clients are in audible synch (actual latency can be allowed as long as it is perceived to be in sync by a human listener). **My question is** if there's any known method or algorithm to use for this type of synchronization problem (video is likely solved the same way). My own initial thoughts centers around synchronizing clocks between physical machines and thereby creating a virtual "main timer" and somehow aligning audio data packets against it. Some products already solving the problem (however still not sufficient for my overall use-case): <http://www.sonos.com> <http://netchorus.com/> Any pointers are most welcome. Thanks. PS: [This related question](https://stackoverflow.com/questions/598778/how-to-synchronize-media-playback-over-an-unreliable-network) seems to have died long ago.
2010/05/08
[ "https://Stackoverflow.com/questions/2795031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
Ryan Barrett wrote up his findings on [his blog](http://snarfed.org/space/synchronizing_mp3_playback). His solution involved using [NTP](http://en.wikipedia.org/wiki/Network_Time_Protocol) as a method to keep all the clocks in-sync: > > Seriously, though, there's only one > trick to p4sync, and that is how it > uses NTP. One host acts as the p4sync > server. The other p4sync clients > synchronize their system clocks to the > server's clock, using SNTP. When the > server starts playing a song, it > records the time, to the millisecond. > The clients then retrieve that > timestamp, calculate the difference > between current time from that > timestamp, and seek forward that far > into the song. > > >
Depending on the size and shape of the venue, getting everything to *be* in sync is the easy part, getting everything to *sound* correct is an art-form in itself, if possible at all. From the technical side, the most difficult part is finding out the delay from your synchronized timeline to actual sound output. Having identical hardware and low latency software framework (ASIO, JACK) certainly helps here, as does calibration. Either ahead of time or active. Otherwise it's just synchronizing the timeline with NTP and using a closed loop feedback to the audio pitch to synchronize the output to the agreed timeline. The larger problem is that sound takes a considerable amount of time to propagate. 10m of difference in distance is already 30ms of delay - enough to screw up sound localization. Double that and you get into the annoying echo territory. Professional audio setups actually purposefully introduce delays, use a higher number of tweeters and play with reverberations to avoid a cacophony of echoes that wears the listener out.
766,936
First of all, sorry for my english. It's not my native language. Here is the problem: I'm writing client-server application based on .net remoting. The application is some kind of calculator. Client application has some field(number A and number B, and label for result) and some possible actions, represented by the buttons: Add, Substract, Multiply, Divide, etc.. Server application is a console application, that should habe following functions: * make this calculations * detect, what actions are done by the specific client. Eg of output: ``` Server started Client A(IP: 192.168.0.133) connected<br> Client A Add 18 to 12<br> Client A disconnected ``` The main problem is - how to get actions on server and how can i detect, what clients do. Thx for help.
2009/04/20
[ "https://Stackoverflow.com/questions/766936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I know 2 *common* ways for tracing with .NET Remoting: * Turn on trace in app.config * Use [Remoting Analyzator Studio](http://www.codeproject.com/KB/IP/remotingprobe.aspx), an open-source project from Codeproject.com.
We modified Mono TCP remoting channel to do this. It takes like 30 minutes and you can add information about the method call being invoked, time to execute and so on. It turns out to be a extremely good tool to measure performance on real servers. You can parse the output and learn which methods are taking more time, sending or receiving more data and so on. Really helpful.
766,936
First of all, sorry for my english. It's not my native language. Here is the problem: I'm writing client-server application based on .net remoting. The application is some kind of calculator. Client application has some field(number A and number B, and label for result) and some possible actions, represented by the buttons: Add, Substract, Multiply, Divide, etc.. Server application is a console application, that should habe following functions: * make this calculations * detect, what actions are done by the specific client. Eg of output: ``` Server started Client A(IP: 192.168.0.133) connected<br> Client A Add 18 to 12<br> Client A disconnected ``` The main problem is - how to get actions on server and how can i detect, what clients do. Thx for help.
2009/04/20
[ "https://Stackoverflow.com/questions/766936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This may not be ideal, but you can create a custom sink that hooks into the remoting channel which logs all remoting traffic. You can learn how to create a custom sink from Ingo Rammer's [Advanced .NET Remoting](https://rads.stackoverflow.com/amzn/click/com/1590594177) book. I've used his book to create custom sinks in the past.
We modified Mono TCP remoting channel to do this. It takes like 30 minutes and you can add information about the method call being invoked, time to execute and so on. It turns out to be a extremely good tool to measure performance on real servers. You can parse the output and learn which methods are taking more time, sending or receiving more data and so on. Really helpful.
930,168
If I have some files that are especially important, can they be SVN committed to two repositories? I can set up two SVN repositories on 2 different machines so that if there is problem with one machine, then there is always a back up. (will be best if it can be Tortoise or command line). thanks.
2009/05/30
[ "https://Stackoverflow.com/questions/930168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/325418/" ]
You can use **svnsync** on the server to create a mirror of your original repository. More info: <http://svn.apache.org/repos/asf/subversion/trunk/notes/svnsync.txt>
Well, you could use a post-commit-hook and commit the whole repository (or just the important files) to another repository. This will take away the pain of remembering to commit everything to two repositories and is an elegant solution.
930,168
If I have some files that are especially important, can they be SVN committed to two repositories? I can set up two SVN repositories on 2 different machines so that if there is problem with one machine, then there is always a back up. (will be best if it can be Tortoise or command line). thanks.
2009/05/30
[ "https://Stackoverflow.com/questions/930168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/325418/" ]
You can use **svnsync** on the server to create a mirror of your original repository. More info: <http://svn.apache.org/repos/asf/subversion/trunk/notes/svnsync.txt>
Extending from activa's idea (using [svnsync](http://svn.apache.org/repos/asf/subversion/trunk/notes/svnsync.txt)), you could get svnsync to run after each commit by triggering it in an SVN hook script, for example, [post-commit](http://svnbook.red-bean.com/en/1.4/svn-book.html#svn.ref.reposhooks.post-commit). This way, after each commit, your secondary copy would be synchronised with your primary copy, thereby always keeping your backup up to date.
930,168
If I have some files that are especially important, can they be SVN committed to two repositories? I can set up two SVN repositories on 2 different machines so that if there is problem with one machine, then there is always a back up. (will be best if it can be Tortoise or command line). thanks.
2009/05/30
[ "https://Stackoverflow.com/questions/930168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/325418/" ]
You can use **svnsync** on the server to create a mirror of your original repository. More info: <http://svn.apache.org/repos/asf/subversion/trunk/notes/svnsync.txt>
If you're worried about losing repository data, then doing automated backups is a possible solution. The "svnadmin dump" command is ideal for that. I use this script to create dumps of all my repositories: ``` #!/bin/bash DATE=`date "+%F"` BACKUPDIR=/var/backup # dump subversion repos. # all subversion projects are in /usr/local/svn for REPODIR in /usr/local/svn/* do REPONAME=`basename $REPODIR` TARGET=svndump-$REPONAME-$DATE.gz echo backing up svn repository $REPODIR to $TARGET svnadmin dump $REPODIR | gzip > $BACKUPDIR/$TARGET || exit 1 done ``` This script is run from a cron job. You can add an rsync command to copy these dumps to a different server.
2,868,432
I am developing some private projects on Github, and I would like to add nightly cronjobs to my deployments servers to pull the latest version from github. I am currently doing this by generating keypairs on every deployment server and adding the public key to the github project as 'Deployment key'. However, I recently found out that these deployment keys actually do have write access to the project. Hence, every of the server administrators could potentially start editing. Furthermore I can add every deployment key to only one repository, whereas I would like to be able to deploy multiple repositories on one and the same deployment server. Is there a way to provide read-only access for private repositories to selected users on Github?
2010/05/19
[ "https://Stackoverflow.com/questions/2868432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318752/" ]
I [have it on good authority](https://twitter.com/defunkt/status/1678391086419969) that the (relatively new) ["Organizations"](https://github.com/blog/674-introducing-organizations) feature allows you to add people with read-only access to a private repository.
For anyone else finding this question, know that nowadays you can in fact create read-only deploy keys: <https://github.com/blog/2024-read-only-deploy-keys> You can still create deploy keys with write access, but have to explicitly grant that permission when adding the key.
2,868,432
I am developing some private projects on Github, and I would like to add nightly cronjobs to my deployments servers to pull the latest version from github. I am currently doing this by generating keypairs on every deployment server and adding the public key to the github project as 'Deployment key'. However, I recently found out that these deployment keys actually do have write access to the project. Hence, every of the server administrators could potentially start editing. Furthermore I can add every deployment key to only one repository, whereas I would like to be able to deploy multiple repositories on one and the same deployment server. Is there a way to provide read-only access for private repositories to selected users on Github?
2010/05/19
[ "https://Stackoverflow.com/questions/2868432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318752/" ]
I [have it on good authority](https://twitter.com/defunkt/status/1678391086419969) that the (relatively new) ["Organizations"](https://github.com/blog/674-introducing-organizations) feature allows you to add people with read-only access to a private repository.
For Organizations: I suggest creating a new team specifically for the user. This team can then grant read-only access to the repositories you specify. I hope this helps!
2,868,432
I am developing some private projects on Github, and I would like to add nightly cronjobs to my deployments servers to pull the latest version from github. I am currently doing this by generating keypairs on every deployment server and adding the public key to the github project as 'Deployment key'. However, I recently found out that these deployment keys actually do have write access to the project. Hence, every of the server administrators could potentially start editing. Furthermore I can add every deployment key to only one repository, whereas I would like to be able to deploy multiple repositories on one and the same deployment server. Is there a way to provide read-only access for private repositories to selected users on Github?
2010/05/19
[ "https://Stackoverflow.com/questions/2868432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318752/" ]
I [have it on good authority](https://twitter.com/defunkt/status/1678391086419969) that the (relatively new) ["Organizations"](https://github.com/blog/674-introducing-organizations) feature allows you to add people with read-only access to a private repository.
I know that the questions is about github but maybe for some readers it would be nice to know that this is possible in gitlab and for free. Check <https://gitlab.com/help/user/permissions>. I spend some time using github without fully serving my purposes. If I knew then I would have started this particular project with gitlab.
2,868,432
I am developing some private projects on Github, and I would like to add nightly cronjobs to my deployments servers to pull the latest version from github. I am currently doing this by generating keypairs on every deployment server and adding the public key to the github project as 'Deployment key'. However, I recently found out that these deployment keys actually do have write access to the project. Hence, every of the server administrators could potentially start editing. Furthermore I can add every deployment key to only one repository, whereas I would like to be able to deploy multiple repositories on one and the same deployment server. Is there a way to provide read-only access for private repositories to selected users on Github?
2010/05/19
[ "https://Stackoverflow.com/questions/2868432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318752/" ]
For anyone else finding this question, know that nowadays you can in fact create read-only deploy keys: <https://github.com/blog/2024-read-only-deploy-keys> You can still create deploy keys with write access, but have to explicitly grant that permission when adding the key.
For Organizations: I suggest creating a new team specifically for the user. This team can then grant read-only access to the repositories you specify. I hope this helps!
2,868,432
I am developing some private projects on Github, and I would like to add nightly cronjobs to my deployments servers to pull the latest version from github. I am currently doing this by generating keypairs on every deployment server and adding the public key to the github project as 'Deployment key'. However, I recently found out that these deployment keys actually do have write access to the project. Hence, every of the server administrators could potentially start editing. Furthermore I can add every deployment key to only one repository, whereas I would like to be able to deploy multiple repositories on one and the same deployment server. Is there a way to provide read-only access for private repositories to selected users on Github?
2010/05/19
[ "https://Stackoverflow.com/questions/2868432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318752/" ]
For anyone else finding this question, know that nowadays you can in fact create read-only deploy keys: <https://github.com/blog/2024-read-only-deploy-keys> You can still create deploy keys with write access, but have to explicitly grant that permission when adding the key.
I know that the questions is about github but maybe for some readers it would be nice to know that this is possible in gitlab and for free. Check <https://gitlab.com/help/user/permissions>. I spend some time using github without fully serving my purposes. If I knew then I would have started this particular project with gitlab.
264,832
I am using attribute\_fu to render a nice block of rows for a particular table. ``` <%= f.render_associated_form(@foo.bars, :new => 5) %> ``` I would like to have the `bar` partial have some notion of a bit of state. (Because the notion is specific to the view, I do not want to externalize this to the `Bar` model itself and calculate it in the controller.) For simplicity's sake, pretend it is the index of the `bar` in the `@foo.bars` list. (I am aware that if this was the case I could use the :collection => @foo.bars to enable bar\_counter... this doesn't appear to function in my tests but I have seen docs for it.) My question -- how do I pass a variable into the partial such that I can keep and edit the state? Naively, I assumed that doing something like ``` <% @tmp = {:index => 1} %> %= f.render_associated_form(@foo.bars, :new => 5, :locals => {:tmp => @tmp}) %> #goes in the view <%= tmp[:index] += 1 %> ``` would work. `tmp` gets passed appropriately but calling [] throws "Uh oh, you just called a method on nil". Surprisingly to me, I can do tmp.inspect, tmp.class, etc to look at the Hash, and these have the results I would expect. But tmp[:index] or tmp[:anything\_I\_want] cause it to blow up. Making `tmp` an array had similar results. Any ideas?
2008/11/05
[ "https://Stackoverflow.com/questions/264832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15046/" ]
I ended up solving this in a thoroughly Rails fashion -- patching :attribute\_fu to meet my needs. Hopefully I'll be able to release my patches to the community fairly soon.
The behavior you describe above seems like it must be a bug in attribute\_fu, since the local isn't getting properly passed along, which it definitely should. I'd be interested to know what you did to patch it.
2,209,207
Does anyone know if there is a way to produce a 2D array from a 1D array, where the rows in the 2D are generated by repeating the corresponding elements in the 1D array. I.e.: ``` 1D array 2D array |1| |1 1 1 1 1| |2| |2 2 2 2 2| |3| -> |3 3 3 3 3| |4| |4 4 4 4 4| |5| |5 5 5 5 5| ```
2010/02/05
[ "https://Stackoverflow.com/questions/2209207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266922/" ]
You can do this using the [REPMAT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html) function: ``` >> A = (1:5).' A = 1 2 3 4 5 >> B = repmat(A,1,5) B = 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 ``` **EDIT: BONUS ANSWER! ;)** For your example, [REPMAT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html) is the most straight-forward function to use. However, another cool function to be aware of is [KRON](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/kron.html), which you could also use as a solution in the following way: ``` B = kron(A,ones(1,5)); ``` For small vectors and matrices [KRON](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/kron.html) may be *slightly* faster, but it is quite a bit slower for larger matrices.
[repmat](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html)(a, [1 n]), but you should also take a look at [meshgrid](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html).
2,209,207
Does anyone know if there is a way to produce a 2D array from a 1D array, where the rows in the 2D are generated by repeating the corresponding elements in the 1D array. I.e.: ``` 1D array 2D array |1| |1 1 1 1 1| |2| |2 2 2 2 2| |3| -> |3 3 3 3 3| |4| |4 4 4 4 4| |5| |5 5 5 5 5| ```
2010/02/05
[ "https://Stackoverflow.com/questions/2209207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266922/" ]
You can do this using the [REPMAT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html) function: ``` >> A = (1:5).' A = 1 2 3 4 5 >> B = repmat(A,1,5) B = 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 ``` **EDIT: BONUS ANSWER! ;)** For your example, [REPMAT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html) is the most straight-forward function to use. However, another cool function to be aware of is [KRON](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/kron.html), which you could also use as a solution in the following way: ``` B = kron(A,ones(1,5)); ``` For small vectors and matrices [KRON](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/kron.html) may be *slightly* faster, but it is quite a bit slower for larger matrices.
You could try something like: ``` a = [1 2 3 4 5]' l = size(a) for i=2:5 a(1:5, i) = a(1:5) ``` The loop just keeps appending columns to the end.
2,209,207
Does anyone know if there is a way to produce a 2D array from a 1D array, where the rows in the 2D are generated by repeating the corresponding elements in the 1D array. I.e.: ``` 1D array 2D array |1| |1 1 1 1 1| |2| |2 2 2 2 2| |3| -> |3 3 3 3 3| |4| |4 4 4 4 4| |5| |5 5 5 5 5| ```
2010/02/05
[ "https://Stackoverflow.com/questions/2209207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266922/" ]
[repmat](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html)(a, [1 n]), but you should also take a look at [meshgrid](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html).
You could try something like: ``` a = [1 2 3 4 5]' l = size(a) for i=2:5 a(1:5, i) = a(1:5) ``` The loop just keeps appending columns to the end.
2,209,207
Does anyone know if there is a way to produce a 2D array from a 1D array, where the rows in the 2D are generated by repeating the corresponding elements in the 1D array. I.e.: ``` 1D array 2D array |1| |1 1 1 1 1| |2| |2 2 2 2 2| |3| -> |3 3 3 3 3| |4| |4 4 4 4 4| |5| |5 5 5 5 5| ```
2010/02/05
[ "https://Stackoverflow.com/questions/2209207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266922/" ]
In the spirit of bonus answers, here are some of my own: Let `A = (1:5)'` 1. Using indices [faster than repmat]: ``` B = A(:, ones(5,1)) ``` 2. Using matrix outer product: ``` B = A*ones(1,5) ``` 3. Using bsxfun() [not the best way of doing it] ``` B = bsxfun(@plus, A, zeros(1,5)) %# or B = bsxfun(@times, A, ones(1,5)) ```
[repmat](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html)(a, [1 n]), but you should also take a look at [meshgrid](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/meshgrid.html).
2,209,207
Does anyone know if there is a way to produce a 2D array from a 1D array, where the rows in the 2D are generated by repeating the corresponding elements in the 1D array. I.e.: ``` 1D array 2D array |1| |1 1 1 1 1| |2| |2 2 2 2 2| |3| -> |3 3 3 3 3| |4| |4 4 4 4 4| |5| |5 5 5 5 5| ```
2010/02/05
[ "https://Stackoverflow.com/questions/2209207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266922/" ]
In the spirit of bonus answers, here are some of my own: Let `A = (1:5)'` 1. Using indices [faster than repmat]: ``` B = A(:, ones(5,1)) ``` 2. Using matrix outer product: ``` B = A*ones(1,5) ``` 3. Using bsxfun() [not the best way of doing it] ``` B = bsxfun(@plus, A, zeros(1,5)) %# or B = bsxfun(@times, A, ones(1,5)) ```
You could try something like: ``` a = [1 2 3 4 5]' l = size(a) for i=2:5 a(1:5, i) = a(1:5) ``` The loop just keeps appending columns to the end.
2,284,860
I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else. Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right? --- I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not).
2010/02/17
[ "https://Stackoverflow.com/questions/2284860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172387/" ]
OK kiddies, time for the pros.... This is one of my biggest complaints with inexperienced software engineers. They come in calculating transcendental functions from scratch (using Taylor's series) as if nobody had ever done these calculations before in their lives. Not true. This is a well defined problem and has been approached thousands of times by very clever software and hardware engineers and has a well defined solution. Basically, most of the transcendental functions use Chebyshev Polynomials to calculate them. As to which polynomials are used depends on the circumstances. First, the bible on this matter is a book called "Computer Approximations" by Hart and Cheney. In that book, you can decide if you have a hardware adder, multiplier, divider, etc, and decide which operations are fastest. e.g. If you had a really fast divider, the fastest way to calculate sine might be P1(x)/P2(x) where P1, P2 are Chebyshev polynomials. Without the fast divider, it might be just P(x), where P has much more terms than P1 or P2....so it'd be slower. So, first step is to determine your hardware and what it can do. Then you choose the appropriate combination of Chebyshev polynomials (is usually of the form cos(ax) = aP(x) for cosine for example, again where P is a Chebyshev polynomial). Then you decide what decimal precision you want. e.g. if you want 7 digits precision, you look that up in the appropriate table in the book I mentioned, and it will give you (for precision = 7.33) a number N = 4 and a polynomial number 3502. N is the order of the polynomial (so it's p4.x^4 + p3.x^3 + p2.x^2 + p1.x + p0), because N=4. Then you look up the actual value of the p4,p3,p2,p1,p0 values in the back of the book under 3502 (they'll be in floating point). Then you implement your algorithm in software in the form: (((p4.x + p3).x + p2).x + p1).x + p0 ....and this is how you'd calculate cosine to 7 decimal places on that hardware. Note that most hardware implementations of transcendental operations in an FPU usually involve some microcode and operations like this (depends on the hardware). Chebyshev polynomials are used for most transcendentals but not all. e.g. Square root is faster to use a double iteration of Newton raphson method using a lookup table first. Again, that book "Computer Approximations" will tell you that. If you plan on implmementing these functions, I'd recommend to anyone that they get a copy of that book. It really is the bible for these kinds of algorithms. Note that there are bunches of alternative means for calculating these values like cordics, etc, but these tend to be best for specific algorithms where you only need low precision. To guarantee the precision every time, the chebyshev polynomials are the way to go. Like I said, well defined problem. Has been solved for 50 years now.....and thats how it's done. Now, that being said, there are techniques whereby the Chebyshev polynomials can be used to get a single precision result with a low degree polynomial (like the example for cosine above). Then, there are other techniques to interpolate between values to increase the accuracy without having to go to a much larger polynomial, such as "Gal's Accurate Tables Method". This latter technique is what the post referring to the ACM literature is referring to. But ultimately, the Chebyshev Polynomials are what are used to get 90% of the way there. Enjoy.
There's nothing like hitting the source and seeing how someone has actually done it in a library in common use; let's look at one C library implementation in particular. I chose uLibC. Here's the sin function: <http://git.uclibc.org/uClibc/tree/libm/s_sin.c> which looks like it handles a few special cases, and then carries out some argument reduction to map the input to the range [-pi/4,pi/4], (splitting the argument into two parts, a big part and a tail) before calling <http://git.uclibc.org/uClibc/tree/libm/k_sin.c> which then operates on those two parts. If there is no tail, an approximate answer is generated using a polynomial of degree 13. If there is a tail, you get a small corrective addition based on the principle that `sin(x+y) = sin(x) + sin'(x')y`
2,284,860
I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else. Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right? --- I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not).
2010/02/17
[ "https://Stackoverflow.com/questions/2284860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172387/" ]
For `sin` specifically, using Taylor expansion would give you: sin(x) := x - x^3/3! + x^5/5! - x^7/7! + ... (1) you would keep adding terms until either the difference between them is lower than an accepted tolerance level or just for a finite amount of steps (faster, but less precise). An example would be something like: ``` float sin(float x) { float res=0, pow=x, fact=1; for(int i=0; i<5; ++i) { res+=pow/fact; pow*=-1*x*x; fact*=(2*(i+1))*(2*(i+1)+1); } return res; } ``` Note: (1) works because of the aproximation sin(x)=x for small angles. For bigger angles you need to calculate more and more terms to get acceptable results. You can use a while argument and continue for a certain accuracy: ``` double sin (double x){ int i = 1; double cur = x; double acc = 1; double fact= 1; double pow = x; while (fabs(acc) > .00000001 && i < 100){ fact *= ((2*i)*(2*i+1)); pow *= -1 * x*x; acc = pow / fact; cur += acc; i++; } return cur; } ```
They are typically implemented in software and will not use the corresponding hardware (that is, aseembly) calls in most cases. However, as Jason pointed out, these are implementation specific. Note that these software routines are not part of the compiler sources, but will rather be found in the correspoding library such as the clib, or glibc for the GNU compiler. See <http://www.gnu.org/software/libc/manual/html_mono/libc.html#Trig-Functions> If you want greater control, you should carefully evaluate what you need exactly. Some of the typical methods are interpolation of look-up tables, the assembly call (which is often slow), or other approximation schemes such as Newton-Raphson for square roots.
2,284,860
I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else. Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right? --- I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not).
2010/02/17
[ "https://Stackoverflow.com/questions/2284860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172387/" ]
In GNU libm, the implementation of `sin` is system-dependent. Therefore you can find the implementation, for each platform, somewhere in the appropriate subdirectory of [sysdeps](http://sourceware.org/git/?p=glibc.git;a=tree;f=sysdeps;hb=HEAD). One directory includes an implementation in C, contributed by IBM. Since October 2011, this is the code that actually runs when you call `sin()` on a typical x86-64 Linux system. It is apparently faster than the `fsin` assembly instruction. Source code: [sysdeps/ieee754/dbl-64/s\_sin.c](https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/dbl-64/s_sin.c;hb=HEAD#l194), look for `__sin (double x)`. This code is very complex. No one software algorithm is as fast as possible and also accurate over the whole range of *x* values, so the library implements several different algorithms, and its first job is to look at *x* and decide which algorithm to use. * When *x* is very *very* close to 0, `sin(x) == x` is the right answer. * A bit further out, `sin(x)` uses the familiar Taylor series. However, this is only accurate near 0, so... * When the angle is more than about 7°, a different algorithm is used, computing Taylor-series approximations for both sin(x) and cos(x), then using values from a precomputed table to refine the approximation. * When |*x*| > 2, none of the above algorithms would work, so the code starts by computing some value closer to 0 that can be fed to `sin` or `cos` instead. * There's yet another branch to deal with *x* being a NaN or infinity. This code uses some numerical hacks I've never seen before, though for all I know they might be well-known among floating-point experts. Sometimes a few lines of code would take several paragraphs to explain. For example, these two lines ``` double t = (x * hpinv + toint); double xn = t - toint; ``` are used (sometimes) in reducing *x* to a value close to 0 that differs from *x* by a multiple of π/2, specifically `xn` × π/2. The way this is done without division or branching is rather clever. But there's no comment at all! --- Older 32-bit versions of GCC/glibc used the `fsin` instruction, which is surprisingly inaccurate for some inputs. There's a [fascinating blog post illustrating this with just 2 lines of code](http://randomascii.wordpress.com/2014/10/09/intel-underestimates-error-bounds-by-1-3-quintillion/). fdlibm's implementation of `sin` in pure C is much simpler than glibc's and is nicely commented. Source code: [fdlibm/s\_sin.c](http://www.netlib.org/fdlibm/s_sin.c) and [fdlibm/k\_sin.c](http://www.netlib.org/fdlibm/k_sin.c)
For `sin` specifically, using Taylor expansion would give you: sin(x) := x - x^3/3! + x^5/5! - x^7/7! + ... (1) you would keep adding terms until either the difference between them is lower than an accepted tolerance level or just for a finite amount of steps (faster, but less precise). An example would be something like: ``` float sin(float x) { float res=0, pow=x, fact=1; for(int i=0; i<5; ++i) { res+=pow/fact; pow*=-1*x*x; fact*=(2*(i+1))*(2*(i+1)+1); } return res; } ``` Note: (1) works because of the aproximation sin(x)=x for small angles. For bigger angles you need to calculate more and more terms to get acceptable results. You can use a while argument and continue for a certain accuracy: ``` double sin (double x){ int i = 1; double cur = x; double acc = 1; double fact= 1; double pow = x; while (fabs(acc) > .00000001 && i < 100){ fact *= ((2*i)*(2*i+1)); pow *= -1 * x*x; acc = pow / fact; cur += acc; i++; } return cur; } ```
2,284,860
I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else. Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right? --- I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not).
2010/02/17
[ "https://Stackoverflow.com/questions/2284860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172387/" ]
Use [Taylor series](http://en.wikipedia.org/wiki/Taylor_series) and try to find relation between terms of the series so you don't calculate things again and again Here is an example for cosinus: ``` double cosinus(double x, double prec) { double t, s ; int p; p = 0; s = 1.0; t = 1.0; while(fabs(t/s) > prec) { p++; t = (-t * x * x) / ((2 * p - 1) * (2 * p)); s += t; } return s; } ``` using this we can get the new term of the sum using the already used one (we avoid the factorial and x2p) [![explanation](https://i.stack.imgur.com/2t9wW.jpg)](https://i.stack.imgur.com/2t9wW.jpg)
As many people pointed out, it is implementation dependent. But as far as I understand your question, you were interested in a real **software** implemetnation of math functions, but just didn't manage to find one. If this is the case then here you are: * Download glibc source code from <http://ftp.gnu.org/gnu/glibc/> * Look at file `dosincos.c` located in *unpacked glibc root*\sysdeps\ieee754\dbl-64 folder * Similarly you can find implementations of the rest of the math library, just look for the file with appropriate name You may also have a look at the files with the `.tbl` extension, their contents is nothing more than huge tables of *precomputed* values of different functions in a binary form. That is why the implementation is so fast: instead of computing all the coefficients of whatever series they use they just do a quick lookup, which is *much* faster. BTW, they do use Tailor series to calculate sine and cosine. I hope this helps.