Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a java-application using JDBC for database interaction. I want to do a search based on a series of regular-expressions, however the application should be generic, we do not know if the database-engine will by mysql,oracle,sql server etc, but we are pretty sure it's gonna be either mysql or oracle. Will regular-expressions limit my application to a specific database or can i use them without worrying about compatibility?
Well, using regular expressions will limit you to DBMS that support them :-). That said, at least Oracle, MySQL, PostgreSQL and MS-SQL support some sort of regexp, so it should not be a problem in principle. You might still run into compatibility problems, of course. Your best bet probably is to confine the use of regular expressions to some defined parts of the application, such as a few stored procedures or one module in your app that generates the SQL queries. That is good practice anyway, and will make later changes doable.
While in theory I believe both [MySQL](http://dev.mysql.com/doc/refman/5.1/en/regexp.html) and [Oracle](http://www.regular-expressions.info/oracle.html) are meant to support POSIX ERE, MySQL uses REGEXP where Oracle uses REGEXP\_LIKE, and regular-expressions.info notes quirks with Oracle's implementation (there are likely similar ones for MySQL). So, you probably can't use this.
Regular expressions in JDBC
[ "", "java", "mysql", "database", "oracle", "jdbc", "" ]
I'm trying to use templates to get std:list of items, where each item has a pointer to the list which contains it, but I keep hitting a compiler message. Here's a very stripped down version of the code. ``` template <class E> class Item { public: E* owner; // pointer to list that owns us. }; template <class E> class BaseList: public std::list<E> { protected: typedef std::list<E> inherited; public: void push_back(const E &e) { E tmp(e); tmp.owner = this; // This line gives the error. inherited::push_back(tmp); } }; class MyList; class MyItem : public Item<MyList> { }; class MyList : public BaseList<MyItem> { }; void foo() // test code to instantiate template { MyList l; MyItem m; l.push_back(m); } ``` However, my compiler barfs at the line:- ``` tmp.owner = this; ``` Error is: ``` [BCC32 Error] Unit7.cpp(30): E2034 Cannot convert 'BaseList<MyItem> * const' to 'MyList *' ``` It's like "this" has somehow become const, but I can't see why. Compiler is Codegear C++Builder 2009. I admit I'm not 100% happy using templates, so I'm unsure if this is my problem or the compilers. The same code without template use compiles fine, but obviously that's not what I want, as I have several item/list classes that want to work this way. Also, is there a better technique that would avoid having all the "owner" pointers in each item? **EDIT:** I think I stripped the example down too far: "MyList" actually introduces new methods, which "MyItem" must then access through the "owner" pointer. **SUMMARY:** Thanks for all comments and answers. As the accepted answer says, the problem is simply one of type incompatibility between pointer to a BaseList vs. MyList. The issues raised about deriving from STL containers and alternative designs are also helpful, but the solution I've used is essentially identical to Luc Touraille's one below.
At line 30, "this" is a pointer to a `BaseList<MyIteM>`, not a MyList. You can substitute a class with a derived one, but not the other way around. You can either typedef MyList to be a `BaseList<MyItem>`, like so: ``` typedef BaseList<MyItem> MyList ``` or let MyItem derive from `Item<BaseList<MyItem> >` instead. When you derive from a type, you create a different type. When you typedef, you create an alias for that type. So when you typedef the compiler will accept this.
In addition to the answers you already have, I would also point out that the standard library collection classes are not intended to be derived from, as they do not have virtual destructors, and none of their member functions is virtual.
C++ Templates: Coding error or compiler bug?
[ "", "c++", "templates", "stl", "c++builder", "" ]
I'm currently working in an application that has to navigate a webpage and recollect data about products, prices, ... with webbrowser object in .net 3.5. The problem is that the page has some fields with a suggest script in ajax, and I can't simply modify the innerText property because the script also saves codes in a hidden input field. I need a way to simulate the typing in that field and then send the "Enter" key, or launch the ajax script and then send the "Enter" key, or any better ways to do this.
Use [Watin](http://watin.sourceforge.net/) Then you can [use this solution](https://stackoverflow.com/questions/856766/can-i-pass-a-key-stroke-i-e-enter-key-into-application-using-watin-scripts/857953#857953).
To submit a form or run a script you can do this: If you know the script name you can use InvoekScript of Document object: ``` myWebBrowser.Document.InvokeScript("script-name",null); ``` the second argument is an array of objects to pass parameters values. if you know the name of an element that it's click event fires the script you can do this: ``` HtmlElement element=myWebBrower.Document.GetElementById("element-name")[0]; element.InvokeMember("click"); ```
Simulate keypress in a non-visible webbrowser object C#
[ "", "c#", ".net", "html", "ajax", "browser", "" ]
I really can't work out how to best do this, I can do fairly simple regex expressions, but the more complex ones really stump me. The following appears in specific HTML documents: ``` <span id="label"> <span> <a href="http://variableLink">Joe Bloggs</a> now using </span> <span> ' <a href="/variableLink/">Important Data</a> ' </span> <span> on <a href="/variableLink">Important data 2</a> </span> </span> ``` I need to extract the two 'important data' points and could spend hours working out the regex to do it.(I'm using the .net Regex Library in C# 3.5)
As often stated befor, regular expressions are usually not the right tool for parsing HTML, XML, and friends - think about using HTML or XML parsing libraries. If you really want to or have to use regular expressions, the following will match the content of the tags in many cases, but might still fail in some cases. ``` <a href="[^"]*">(?<data>[^<]*)</a> ``` This expression will match all links not starting with `http://` - this is the only obviouse difference I can see between the links. ``` <a href="(?!http://)[^"]*">(?<data>[^<]*)</a> ```
The below uses [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack). It prints any text within a second-or-later link within the "label" id. Of course, it's relatively simple to modify the XPath to do something a little different. ``` HtmlDocument doc = new HtmlDocument(); doc.Load(new StringReader(@"<span id=""label""> <span> <a href=""http://variableLink"">Joe Bloggs</a> now using </span> <span> ' <a href=""/variableLink/"">Important Data</a> ' </span> <span> on <a href=""/variableLink"">Important data 2</a> </span> </span> ")); HtmlNode root = doc.DocumentNode; HtmlNodeCollection anchors; anchors = root.SelectNodes("//span[@id='label']/span[position()>=2]/a/text()"); IList<string> importantStrings; if(anchors != null) { importantStrings = new List<string>(anchors.Count); foreach(HtmlNode anchor in anchors) importantStrings.Add(((HtmlTextNode)anchor).Text); } else importantStrings = new List<string>(0); foreach(string s in importantStrings) Console.WriteLine(s); ```
What is the REGEX to match this pattern in a html document in C#?
[ "", "c#", ".net", "regex", "" ]
I want a `ListBox` full of items. Although, each item should have a different value. So when the user selects an item and presses a button, a method will be called which will use the value the select item has. I don't want to reveal the item values to the user. **EDIT:** This is not for ASP.NET, it's for a Windows Forms application. I just thought the HTML example would be easy to read. I have the inspiration from HTML: ``` <form> <input type="radio" name="sex" value="Value1" /> Male <br /> <input type="radio" name="sex" value="Value2" /> Female </form> ``` This also allows me to use different values than what the user sees.
You can choose what do display using the DisplayMember of the ListBox. ``` List<SomeData> data = new List<SomeData>(); data.Add(new SomeData() { Value = 1, Text= "Some Text"}); data.Add(new SomeData() { Value = 2, Text = "Some Other Text"}); listBox1.DisplayMember = "Text"; listBox1.DataSource = data; ``` When the user selects an item, you can read the value (or any other property) from the selected object: ``` int value = (listBox1.SelectedItem as SomeData).Value; ``` Update: note that DisplayMember works only with properties, not with fields, so you need to alter your class a bit: ``` public class SomeData { public string Value { get; set; }; public string Text { get; set; }; } ```
items have a property called 'Tag', which you can use to store any information you want (hidden from the user) ``` ListViewItem myItem = new ListViewItem(); myItem.Text = "Users see this"; myItem.Tag = "Users don't see this"; ``` (or set the appropriate properties in the property explorer)
Make ListBox items have a different value than item text
[ "", "c#", "winforms", "" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
You can use [PyPNG](https://github.com/drj11/pypng/). It's a pure Python (no dependencies) open source PNG encoder/decoder and it [supports](https://pypng.readthedocs.io/en/latest/ex.html#numpy) writing NumPy arrays as images.
Using [`PIL`](https://pillow.readthedocs.io/en/stable/), save a NumPy array `arr` by doing: ``` from PIL import Image im = Image.fromarray(arr) im.save("your_file.jpeg") ``` See the docs for [available data formats](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html), including JPEG, PNG, and so on.
Saving a Numpy array as an image
[ "", "python", "image", "numpy", "" ]
I'm working on programming a Tetris game in Visual C# 2005. This is the most extensive program I have designed yet. I create a shape class and a block class to control the location, movement, and display of the different Tetris pieces. I have moveDown(), moveLeft(), and moveRight() functions for each shape (and corresponding canMoveDown(), canMoveLeft(), canMoveRight() boolean functions that verify it's ok to move). This is all working beautifully. I want to use the down, right, and left arrow keys to let the user move the block around, in addition to using a timer to have the shape automatically fall one row every so many milliseconds. I am using the KeyDown event handler to check when the user presses the down, left, and right arrow key. This isn't so hard. The problem is that I want to allow for diagonal motion, and I want it work as smoothly possible. I have tried a bunch of different ways of approaching this problem, with varying levels of success. But I can't get it quite right... My most successful approach was to use three boolean variables to keep track of when the down, left, and right arrow keys are being held down. I would set the booleans to true in the KeyDown event, and to false in the KeyUp event. In the KeyDown event I would also tell the block how to move, using the boolean variables to check which combination was currently being pressed. It worked really well, except for one thing. If I pressed one of the arrow keys and held, then pressed a second arrow key and then released the second key, the block would stop moving altogether, instead of continuing to move in the direction of the first arrow key which hasn't been released yet. I think this is because the second key triggered the KeyDown event, and upon its release the KeyUp event was fired, and the KeyDown event stopped firing completely, even though the first key is fired. I cannot for the life me of find a satisfactory solution to this problem. Any help would be greatly appreciated =)
Most games don't wait for events. They poll the input device when neccessary and act accodringly. In fact, if you ever take a look at XNA, you'll see that there's a Keyboard.GetState() method (or Gamepad.GetState()) that you'll call in your update routine, and update your game logic based on the results. When working with Windows.Forms, there's nothing out of the box to do this, however you can P/Invoke the GetKeyBoardState() function to take advantage of this. The good thing about this is, that you can poll multiple keys at once, and you can therefore react to more than one key press at a time. Here's a simple class I found online that helps with this: <http://sanity-free.org/17/obtaining_key_state_info_in_dotnet_csharp_getkeystate_implementation.html> To demonstrate, I wrote a simple windows app that basically moves a ball around based on keyboard input. It uses the class I linked you to, to poll the keyboard's state. You'll notice that if you hold down two keys at a time, it'll move diagonally. First, Ball.cs: ``` public class Ball { private Brush brush; public float X { get; set; } public float Y { get; set; } public float DX { get; set; } public float DY { get; set; } public Color Color { get; set; } public float Size { get; set; } public void Draw(Graphics g) { if (this.brush == null) { this.brush = new SolidBrush(this.Color); } g.FillEllipse(this.brush, X, Y, Size, Size); } public void MoveRight() { this.X += DX; } public void MoveLeft() { this.X -= this.DX; } public void MoveUp() { this.Y -= this.DY; } public void MoveDown() { this.Y += this.DY; } } ``` Really nothing fancy at all.... Then here's the Form1 code: ``` public partial class Form1 : Form { private Ball ball; private Timer timer; public Form1() { InitializeComponent(); this.ball = new Ball { X = 10f, Y = 10f, DX = 2f, DY = 2f, Color = Color.Red, Size = 10f }; this.timer = new Timer(); timer.Interval = 20; timer.Tick += new EventHandler(timer_Tick); timer.Start(); } void timer_Tick(object sender, EventArgs e) { var left = KeyboardInfo.GetKeyState(Keys.Left); var right = KeyboardInfo.GetKeyState(Keys.Right); var up = KeyboardInfo.GetKeyState(Keys.Up); var down = KeyboardInfo.GetKeyState(Keys.Down); if (left.IsPressed) { ball.MoveLeft(); this.Invalidate(); } if (right.IsPressed) { ball.MoveRight(); this.Invalidate(); } if (up.IsPressed) { ball.MoveUp(); this.Invalidate(); } if (down.IsPressed) { ball.MoveDown(); this.Invalidate(); } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (this.ball != null) { this.ball.Draw(e.Graphics); } } } ``` Simple little app. Just creates a ball and a timer. Every 20 milliseconds, it checks the keyboard state, and if a key is pressed it moves it and invalidates so that it can repaint.
If you're relying on key repeat to repeatedly send key down events to make the block move, I don't think this is the way you want to do it. The block should move consistently independent of key repeat. Therefore you should not be moving the block during the key events. You should only be tracking the state of the keys during the keydown and keyup events, and handle movement elsewhere. The actual movement should take place either in some sort of timer event (a timer control fires events at regular intervals even if nothing is going on) or you should have a main loop constantly checking the state of everything and moving objects when appropriate. If you use the second option, you will need to look into "DoEvents" because if you have code that's constantly running without ever finishing the function, the program will not process any other events such as keyup and keydown events. So you would want to call DoEvents within each loop to process the key events (among other things like moving the window). You might also want to call System.Threading.Thread.Sleep if you don't need to be processing things quite so constantly. If you use a timer control, you shouldn't have to worry about any of that.
C# - Tetris clone - Can't get block to respond properly to arrow key combinations
[ "", "c#", "keydown", "arrow-keys", "" ]
1)how can i find out the Windows Installation drive in which the user is working.? I need this to navigate to the **ApplicationData** in DocumentsandSettings. 2)Also how can i get the **user name** too so that i can goto ApplicaitionData.? Eg: "D:\Documents and Settings\user\Application Data".
Look at combining [Environment.GetFolderPath](http://msdn.microsoft.com/en-us/library/system.environment.getfolderpath.aspx) and [Environment.SpecialFolder](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx) to do this. ``` Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) ```
Depending on what you are doing you might also want to look at ``` Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) ``` If the user is on a domain it will only be stored in their local `AppData` folder and not synced with their roaming profile.
How can i get the path of the current user's "Application Data" folder?
[ "", "c#", "path", "appdata", "" ]
I have a Canvas which I would need to animate the RenderTransform property of. The start and end matrices will be abitrary, so I can't pre write the storyboard in XAML, so I'm trying to do it in code, I can't find any example of how to do this, below is my best try which does not work (it compiles and runs, but the rendertransform does not change). Any suggestions on how this should be done? ``` MatrixAnimationUsingKeyFrames anim = new MatrixAnimationUsingKeyFrames(); MatrixKeyFrameCollection keyframes = new MatrixKeyFrameCollection(); DiscreteMatrixKeyFrame start = new DiscreteMatrixKeyFrame(fromMatrix, KeyTime.FromPercent(0)); DiscreteMatrixKeyFrame end = new DiscreteMatrixKeyFrame(toMatrix, KeyTime.FromPercent(1)); keyframes.Add(start); keyframes.Add(end); anim.KeyFrames = keyframes; Storyboard.SetTarget(anim, World.RenderTransform); Storyboard.SetTargetProperty(anim, new PropertyPath("Matrix")); Storyboard sb = new Storyboard(); sb.Children.Add(anim); sb.Duration = TimeSpan.FromSeconds(4); sb.Begin(); ```
I bumped into this problem this morning, although the solution I used won't cope with rotations or shearing. [link](https://stackoverflow.com/questions/1988421/smooth-animation-using-matrixtransform/2666702#2666702)
I have implemented MatrixAnimation class which supports smooth translation, scaling and rotation animations. It also supports easing functions! Find at <http://pwlodek.blogspot.com/2010/12/matrixanimation-for-wpf.html>
Animating a MatrixTransform in WPF from code
[ "", "c#", "wpf", "animation", "matrix", "transform", "" ]
And I know there's `std::cin`, but that requires the user to enter a string, then press ENTER. Is there a way to simply get the next key that is pushed without needing to press ENTER to confirm
You can use ``` #include <conio.h> ``` and then catch char with cases such as this ``` char c; if (_kbhit()) { c = getch(); switch(c) { case ‘\0H’ : cout << "up arrow key!" << endl; break; } } ``` **Beware**: I have not tried it... and remember to put the whole thing into a "while(true)" to test.
What you're looking for is related to manipulating the console, and is OS-dependent. If you're in a UNIX-based OS, check out the [curses library](http://en.wikipedia.org/wiki/Curses_(programming_library)), and in Windows, there are `getch()` and `kbhit()` functions from `<conio.h>`.
Is there a way to read input directly from the keyboard in standard C++?
[ "", "c++", "input", "console", "keyboard", "" ]
In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respectively. Currently I have the below code but was wondering if there was more of an elegant solution? So for pdr = 20090521-20090523 would get "20090521 00:00:00" and "20090523 23:59:59" ``` private void ValidateDatePeriod(string pdr, out DateTime startDate, out DateTime endDate) { string[] dates = pdr.Split('-'); if (dates.Length != 2) { throw new Exception("Date period is of incorrect format"); } if (dates[0].Length != 8 || dates[1].Length != 8) { throw new Exception("Split date periods are of incorrect format"); } startDate = DateTime.ParseExact(dates[0] + " 00:00:00", "yyyyMMdd HH:mm:ss", null); endDate = DateTime.ParseExact(dates[1] + "23:59:59", "yyyyMMdd HH::mm:ss", null); } ```
I am surprised to see how an [***incorrect answer***](https://stackoverflow.com/a/903365/437979) received so many upvotes: ![Wrong value](https://i.stack.imgur.com/8fzzp.png) The correct version would be as follows: ``` public static DateTime StartOfDay(this DateTime theDate) { return theDate.Date; } public static DateTime EndOfDay(this DateTime theDate) { return theDate.Date.AddDays(1).AddTicks(-1); } ```
You could define two extension methods somewhere, in a utility class like so : ``` public static DateTime EndOfDay(this DateTime date) { return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999); } public static DateTime StartOfDay(this DateTime date) { return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0); } ``` And then use them in code like so : ``` public DoSomething() { DateTime endOfThisDay = DateTime.Now.EndOfDay(); } ```
How to get the start and end times of a day
[ "", "c#", "datetime", "" ]
I have a C++ class `MyObject` and I want to be able to feed this data like I would to a osstream (but unlike a direct sstream, have the incoming data be formatted a special way). I can't seem to figure out how to overload a operator for MyObject to eat input given to it. ``` class MyObject { public: ostringstream s; FEEDME }; int main() { MyObject obj; obj.FEEDME << "Hello" << 12345; // I want obj.s == ":Hello::12345:" } ``` I want it so every item fed in be surrounded by : : So in the given example, s = ":Hello::12345" should be the final outcome. What my question is, how can I tell the object that when ever a `<<something`, put : : around the something. Is this possible?
try this: ``` class MyObject { public: template <class T> MyObject &operator<<(const T &x) { s << ':' << x << ':'; return *this; } std::string to_string() const { return s.str(); } private: std::ostringstream s; }; MyObject obj; obj << "Hello" << 12345; std::cout << obj.to_string() << std::endl; ``` There are certain things you won't be able to shove into the stream, but it should work for all the basics.
You may find the answers for [How do I create my own ostream/streambuf?](https://stackoverflow.com/questions/524641/how-do-i-create-an-ostream-streambuf) helpful.
Have a C++ Class act like a custom ostream, sstream
[ "", "c++", "operator-overloading", "ostream", "sstream", "" ]
I use this code to update data in database table. Can reuse same code to update a dataset? Thanks. ``` using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString)) { string sql = "UPDATE tbh_Categories SET Title = @Title, Description = @Description WHERE CategoryID = @CategoryID"; SqlCommand cmd = new SqlCommand(sql, cn); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@CategoryID", SqlDbType.Int).Value = category.ID; cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = category.Title; cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = category.Description; cn.Open(); int ret = cmd.ExecuteNonQuery(); return (ret == 1); } ```
The answer is no. But, you can use [DataTable.Select](http://msdn.microsoft.com/en-us/library/system.data.datatable.select.aspx) to identify the rows in the DataTable that you want to update. But then you will have to modify the actual table itself "by hand". I must ask what you are trying to do ... are you trying, for example, to cache some data using an updatable DataSet? Or are you trying to avoid extra database trips? There may be a better way to do what you are trying to do if you let us know. If you want an In Memory Database, there [are lots out there](http://en.wikipedia.org/wiki/In-memory_database). Per comment: Check out [SQLite](http://www.sqlite.org/). There are [.NET Wrappers](http://jclement.ca/devel/dotnet/sqlite.html) that might let you do what you want.
The same exact code? No. SqlConnection (and SqlCommand) is specific to SqlServer. DataSet exists outside of that context, so you would have to rewrite your code to accomodate updating a DataSet.
Is it possible to update/insert data into dataset with SqlCommand?
[ "", "asp.net", "sql", "dataset", "" ]
I never did any serious Java coding before, but I learned the syntax, libraries, and concepts based on my existing skills (Delphi & C#). One thing I hardly understand is that I've seen so much code that silently consume exceptions after `printStackTrace` like this: ``` public void process() { try { System.out.println("test"); } catch(Exception e) { e.printStackTrace(); } } ``` There is similar code like this one in almost every Java article & project I ran into. Based on my knowledge this is very bad. The exception should almost always be forwarded to the outer context like this: ``` public void process() { try { System.out.println("test"); } catch(Exception e) { e.printStackTrace(); throw new AssertionError(e); } } ``` Most of the time the exception should end up being handled at the outermost loop which belongs to the underlying framework (Java Swing for example). Why does it look like the norm to code like this in the Java world? I'm puzzled. Based on my background, I'd prefer to remove printStackTrace *entirely*. I would simply rethrow as an unhandled aka `RuntimeException` (or, even better, `AssertionError`), then catch and log it at the most appropriate place: the framework outermost loop. ``` public void process() { try { System.out.println("test"); } catch(Exception e) { throw new AssertionError(e); } } ```
I have always thought, that's similar to the following scenario: > *"A man gets shot.* > > *He holds his breath and has enough strength to take a bus.* > > *10 miles later the man gets off of the bus, walks a couple of blocks and dies."* When the police gets to the body, they don't have a clue of what has just happened. They may have eventually but it is much harder. Better is: > *"A man gets shot and he dies instantly, and the body lies exactly where the murder just happened."* When the police arrives, all the evidence is in place. If a system is to fail, better is to [fail fast](http://en.wikipedia.org/wiki/Fail-fast) Addressing the question: 1. Ignorance. + 2. Sloth **EDIT:** Of course, the catch section is useful. If something can be done with the exception, that's where it should be done. Probably that is NOT an exception for the given code, probably it is something that is expected ( and in my analogy is like a bulletproof jacket, and the man was waiting for the shot in first place ). And yes, the catch could be used to [Throw exceptions appropriate to the abstraction](http://www.google.com/search?q=Effective+Java+Throw+exceptions+appropriate+to+the+abstraction)
Usually that is due to the IDE offering a helpful 'quick fix' that wraps the offending code in a try-catch block with that exception handling. The idea is that you actually DO something, but lazy developers don't. This is bad form, no doubt.
Why do Java people frequently consume exceptions silently?
[ "", "java", "exception", "" ]
I need to echo entire content of included file. I have tried the below: ``` echo "<?php include ('http://www.example.com/script.php'); ?>"; echo "include (\"http://www.example.com/script.php\");"; ``` But neither works? Does PHP support this?
Just do: ``` include("http://www.mysite.com/script.php"); ``` Or: ``` echo file_get_contents("http://www.mysite.com/script.php"); ``` Notes: * This may slow down your page due to network latency or if the other server is slow. * This requires `allow_url_fopen` to be on for your PHP installation. Some hosts turn it off. * This will not give you the PHP code, it'll give you the HTML/text output.
Shortest way is: ``` readfile('http://www.mysite.com/script.php'); ``` That will directly output the file.
Include whole content of a file and echo it
[ "", "php", "echo", "" ]
Something strange is going on with ObservableCollection. I have the following code: ``` private readonly ObservableCollection<DisplayVerse> _display; private readonly ListBox _box; private void TransferToDisplay() { double elementsHeight = 0; _display.Clear(); for (int i = 0; i < _source.Count; i++) { DisplayVerse verse = _source[i]; _display.Add(verse); elementsHeight += CalculateItemsHeight(i); if (elementsHeight + Offset > _box.ActualHeight) { _display.RemoveAt(_display.Count - 1); break; } } MessageBox.Show(elementsHeight.ToString()); } private double CalculateItemsHeight(int index) { ListBoxItem lbi = _box.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem; return lbi != null ? lbi.ActualHeight : 0; } ``` What I am trying to do here is control how many items go into the ObservableCollection \_display. Now, within this for loop you can see that elements are added until the total elements height (+offset) is greater than the listbox itself. Now, this is strange, the elementsHeight equals 0 after this for loop. (CalculateItemsHeight returns 0 in all for loop iterations even though the lbi is not null) It seems that the UI elements defined in the datatemplate are not created... Yet. Now, if I put some MessageBoxes after the \_display.Add(verse) you can see that the CalculateItemsHeight actually returns the height of an item. ``` for (int i = 0; i < _source.Count; i++) { DisplayVerse verse = _source[i]; _display.Add(verse); MessageBox.Show("pause"); // <----- PROBLEM? elementsHeight += CalculateItemsHeight(i); if (elementsHeight + Offset > _box.ActualHeight) { _display.RemoveAt(_display.Count - 1); break; } } MessageBox.Show(elementsHeight.ToString()); ``` After I modify the for loop as shown, the last MessageBox **actually shows** the actual height for all processed elements. My question is - **when are the UI elements actually created**? It seems that it was done somewhere during the MessageBox display. This behaviour is pretty strange for me, maybe it has something to do with threading, not sure. Adding to the \_display ObservableCollection obviously creates an item immediately, but not its visual elements (they are however added afterwards, I just don't know exactly when). How can I do this same behaviour without having to pop the message box up?
**SOLVED** This creates somewhat flickering effect for a fraction of second (as if loading items one by one), but actually suits my needs. The point is to refresh the UI for an item before retrieving its height. I have created an extension method: ``` public static void RefreshUI(this DependencyObject obj) { obj.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Loaded, (Action)delegate { }); } ``` And then before retrieving the height, I refresh the UI. ``` private double CalculateItemsHeight(int index) { ListBoxItem lbi = _box.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem; if (lbi != null) { lbi.RefreshUI(); return lbi.ActualHeight; } return 0; } ```
Actually, I was trying to get this to work and I found the ".UpdateLayout()" function, which works perfectly for me. I realize that you're doing vertical and I'm doing horizontal, but here's my code, it's pretty simple: ``` for (int i = 0; i < listOfItems.ItemsIn.Count; ++i) { //CalculateItemsHeight(i); ListBoxItem abc = (lb.ItemContainerGenerator.ContainerFromItem(lb.Items[i]) as ListBoxItem); abc.UpdateLayout(); totalWidth += abc.ActualWidth; } ``` Hopefully this helps!
ObservableCollection and ListBoxItem DataTemplate generation problem
[ "", "c#", "wpf", "observablecollection", "listboxitem", "" ]
I was wondering if it was possible to grab the username of the account logged into the computer. I wanted to print the username of the person that is printing out the pdf file. I was thinking about trying to grab the %username% environment variable. Does not seem to be possible.
In Acrobat JavaScript, many local system parameters are considered privileged. The user's login name is one of these. In order to access the "identity" object the JavaScript code has to be executed from a trusted context. Code inside a PDF doesn't qualify. Or at least it doesn't normally. If the local system user has given explicit permission to the PDF, then it can access privileged data. But obviously this isn't a general purpose solution. Typically the "identity" object is only accessible to Folder Level Automation scripts. Thom Parker www.pdfscripting.com
take a look a the identity object. ``` name = identity.name; //gives you the user name that the user entered in the Identity preferences panel userName = identity.loginName; //login name as registered by the operating system ```
Get username using javascript in pdf
[ "", "javascript", "pdf", "" ]
I have the following HTML: ``` <span id="UnitCost5">$3,079.95 to $3,479.95</span> ``` And i want to use Javascript and Regex to get all number matches. So i want my script function to return: 3,079.95 AND 3,479.95 Note the text may be different so i need the solution as generic as posible, may be it will be like this: ``` <span id="UnitCost5">$3,079.95 And Price $3,479.95</span> ```
All the numbers would be matched by: ``` \.?\d[\d.,]* ``` This assumes the numbers you look for can start with a decimal dot. If they cannot, this would work (and maybe produce less false positives): ``` \d[\d.,]* ``` Be aware that different local customs exist in number formatting. I assume that you use appropriate means to get hold of the text value of the HTML nodes you wish to process, and that HTML parsing is not part of the excercise.
You don't want to capture *all* numbers, otherwise you would get the 5 in the id, too. I would guess, what you're looking for is numbers looking like this: `$#,###.##` Here goes the expression for that: ``` /\$[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?/ ``` * **`\$`** The dollar sign * **`[0-9]{1,3}`** One to three digits * **`(,[0-9]{3})*`** [Optional]: Digit triplets, preceded by a comma * **`(\.[0-9]+)?`** [Optional]: Even more digits, preceded by a period
How to match with javascript and regex?
[ "", "javascript", "html", "regex", "" ]
I have a simple question, but I'm about 80% sure that the answer to the question will be accompanied by "you're doing it wrong," so I'm going to ask the not-simple question too. The simple question: I have a public method of a public class. I want it to throw an exception if it's called on the UI thread. How can I do this? The much-less-simple question is: is there an easier way to refactor this design? **Background:** I've developed a desktop program that interoperates with a legacy application via its API. The API is not remotely thread-safe. I've built a class library that encapsulates interoperation with the API (which involves marshalling and unmarshalling data in an enormous byte[] buffer and then calling an external function loaded from a DLL) so that as many implementation details of the legacy API are hidden from my code as possible. Because I knew that making multiple instances of the core API object would be a catastrophe, I implemented it as a static class. I've also built a set of classes for running tasks in the background of my app. The `TaskManager` maintains a queue of `Task` objects and runs them using a `BackgroundWorker`. Using a background thread allows the desktop app's UI to remain responsive while interoperation with the turgid legacy app is going on; using a queue insures that only one task is calling the API at any given time. Unfortunately, I never thought to build certain safeguards into this design. I've recently discovered places in the code where I was directly calling the API on the UI thread. I believe I've fixed all of them, but I'd like to guarantee I don't do this again. If I'd designed this properly from the beginning, I'd have made the API wrapper class non-static, hidden its constructor from everything except the `TaskManager`, and then passed the instance of the API class to each `Task` when it gets created. Any method the `Task` called that talked to the API would need to be passed the API object. This would make it impossible to use the API on the foreground thread. The thing is, there's a *lot* of code that talks to the API. Implementing this change (which I think is ultimately the right thing to do) will touch all of it. So in the meantime, I'd like to modify the API's `Call` method so that it throws an exception if it's being called on the foreground thread. I know I'm solving the wrong problem. I can feel it in my bones. But I'm also pretty wrapped up in it right now and can't quite see the right solution. **Edit:** I clearly framed the question the wrong way, which is why it was hard to answer. I shouldn't be asking "How can this method know if it is running on the UI thread?" The real question is: "How can this method know if it is running on the *wrong* thread?" There could (in theory) be a thousand threads running. As JaredPar points out, there could be more than one UI thread. Only one thread is the right thread, and its thread ID is easy to find. In fact, even after I refactor this code so that it's properly designed (which I mostly did today), it'll be worth having a mechanism in the API that checks to make sure it's being run on the appropriate thread.
Part of the problem with determining if you're on the UI thread or not is that there can be more than one UI thread. In WPF and WinForms it's quite possible to create more than one thread for displaying UI. In this case though, it sounds like you have a fairly constrained scenario. The best bet is to record the Id of the UI thread or background thread in a shared location and then use Thread.CurrentThread.ManagedThreadId to ensure you're on the correct thread. ``` public class ThreadUtil { public static int UIThreadId; public static void EnsureNotUIThread() { if ( Thread.CurrentThread.ManagedThreadId == UIThreadId ) { throw new InvalidOperationException("Bad thread"); } } } ``` This approach has a couple of caveats. You must set the UIThreadId in a atomic manner and must do so before any background code runs. The best way is to probably add the following lines to your program startup ``` Interlocked.Exchange(ref ThreadUtil.UIThreadID, Thread.CurrentThread.ManagedThreadId); ``` Another trick is to look for a SynchronizationContext. Both WinForms and WPF will setup a SynchronizationContext on their UI threads in order to allow communication with background threads. For a background created and controlled by your program (i really want to stress that point) there will not be a SynchronizationContext installed unless you actually install one. So the following code can be used in that very limited circumstance ``` public static bool IsBackground() { return null == SynchronizationContext.Current; } ```
I'd reverse the ISynchronizeInvoke use case, and throw an exception if `ISynchronizeinvoke.InvokeRequired == false`. That lets WinForms take care of the gory work of finding the UI thread. Performance will suck a bit, but this is a debugging scenario - so it really doesn't matter. You could even hide the check behind an `#IF DEBUG` flag to only check on debug builds. You do need to give your API a reference to an ISynchronizeInvoke - but you can easily do that at startup (just pass your main Form), or let it use the static Form.ActiveForm call.
How can a method know if it's running on the UI thread?
[ "", "c#", ".net", "multithreading", "" ]
Quick question about the Dijit.Form.DateTextBox <http://docs.dojocampus.org/dijit/form/DateTextBox> This page contains the following: "also validates against developer-provided constraints like min, max, valid days of the week, etc." I can't seem to find documentation allowing me to provide a constraint on the days of the week. For instance, i need to have a DateTextBox which only allows users to choose a date that occurs on a Sunday. I'd appreciate any help with this. Thanks!
I looked heavily into the source code for this, and I think the manual may be misleading you a bit - there's no way to do this using the object's constraints. The following quote from their user forums seems to back up my findings: > DateTextBox doesn't let you customize > isDisabledDate at this time. It only > lets you set min/max. You would > probably have to patch or subclass > DateTextBox to provide your own > isDisabledDate implementation and > check during validation. You can see an example of such a subclass of DateTextBox at <http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/datetextbox-mondays-only-selectable#comment-19508>. If that's too much work for you, DateTextBox DOES descend from dijit.form.ValidationTextBox, so we can use this widget's regExpGen to create a validator - it won't prevent us from selecting invalid dates, but it will cause dijit to mark the widget as invalid and give the user a 'The value entered is not valid'. ``` dijit.byId('toDate').regExpGen = function() { if (dojo.date.locale.format(this.value, {datePattern: "E", selector: "date"}) == 6) return ".*"; return "0"; } ```
As it happens, the `isDisabledDate` function on the `Calendar` object inside a `DateTextBox` just calls `rangeCheck` on the `DateTextBox` itself. So, for your purposes, this will work: ``` dijit.byId('toDate').rangeCheck = function(date,constraints) { var day=date.getDay(); return day===0; } ``` You'd have to add the constraint logic back in if you ALSO wanted the min/max stuff, but this solves the problem as stated, and it's pretty short.
Constraints on Dijit DateTextBox [Valid days of the week]
[ "", "javascript", "constraints", "widget", "dojo", "" ]
``` Directory.GetFiles(targetDirectory); ``` Using the above code we get the names(**i.e full path)** of all the files in the directory. but i need to get only the name of the file and not the path. So how can I get the name of the files alone excluding the path? Or do I need to do the string operations in removing the unwanted part? EDIT: ``` TreeNode mNode = new TreeNode(ofd.FileName, 2, 2); ``` Here `ofd` is a `OpenFileDialog` and `ofd.FileName` is giving the the filename along with it's Path but I need the file name alone.
You could use: ``` Path.GetFileName(fullPath); ``` or in your example: ``` TreeNode mNode = new TreeNode(Path.GetFileName(ofd.FileName), 2, 2); ```
Use DirectoryInfo and FileInfo if you want to get only the filenames without doing any manual string editing. ``` DirectoryInfo dir = new DirectoryInfo(dirPath); foreach (FileInfo file in dir.GetFiles()) Console.WriteLine(file.Name); ```
How to get the name of File in a directory in C#
[ "", "c#", "" ]
We are currently going through the long process of writing some coding standards for C#. I've written a method recently with the signature ``` string GetUserSessionID(int UserID) ``` `GetUserSession()` returns null in the case that a session is not found for the user. in my calling code... I say... ``` string sessionID = GetUserSessionID(1) if (null == sessionID && userIsAllowedToGetSession) { session = GetNewUserSession(1); } ``` In a recent code review, the reviewer said "you should never return null from a method as it puts more work on the calling method to check for nulls." Immediately I cried shenanigans, as if you return string.Empty you still have to perform some sort of check on the returned value. ``` if (string.Empty == sessionID) ``` However, thinking about this further I would never return null in the case of a `Collection`/`Array`/`List`. I would return an empty list. The solution to this (I think) would be to refactor this in to 2 methods. ``` bool SessionExists(int userID); ``` and ``` string GetUserSessionID(int UserID); ``` This time, `GetUserSessionID()` would throw a `SessionNotFound` exception (as it should not return null) now the code would look like... ``` if(!SessionExists(1) && userIsAllowedToGetSession)) { session = GetNewUserSession(1); } else { session = GetUserSessionID(1); } ``` This now means that there are no nulls, but to me this seems a bit more complicated. This is also a very simple example and I was wondering how this would impact more complicated methods. There is plenty of best-practice advise around about when to throw exceptions and how to handle them, but there seems to be less information regarding the use of null. Does anyone else have any solid guidelines (or even better standards) regarding the use of nulls, and what does this mean for nullable types (should we be using them at all?) Thanks in advance, Chris. --- **Thanks everyone! LOTS of very interesting discussion there.** I've given the answer to egaga as I like thier suggestion of Get vs Find as a coding guideline, but all were interesting answers.
A possible practice is to use **get** prefix for methods that throw an exception if result is not found, and **find** prefix, if null is possible. Thus it's easy to see in client side whether the code could have a problem dealing with null. Of course one should avoid nulls, and Andrej Heljsberg has said in an interview that if C# was created now, it would have better ways dealing with nullability. <http://www.computerworld.com.au/article/261958/-z_programming_languages_c?pp=3&fp=&fpid=>
nulls are definitely better, i.e., more honest, than "magic values". But they should not be returned when an error has happened - that's what exceptions are made for. When it comes to returning collections... better an empty collection than null, I agree.
Never use Nulls?
[ "", "c#", "null", "" ]
When I create a new VARCHAR column in Microsoft SQL Server Manager Studio, it defaults to 50 length. Does this length have some special meaning? If theoretically I have the option to choose for a length between 30 and 70, is isn't it better to go for defaults that are power of 2 (like 32, or 64 in this case)?
Because its a nice small round number... Seriously I would think that its pretty arbitrary decision that was made.
Powers of 2 are meaningless when it comes to the possible lengths of strings.
SQL: Why is varchar(50) the default?
[ "", "sql", "varchar", "" ]
Is there a php function that someone can use to automatically detect if an array is an associative or not, apart from explictly checking the array keys?
quoted from the official site: > The indexed and associative array > types are the same type in PHP, So the best solution I can think of is running on all the keys, or using array\_keys,implode,is\_numeric
My short answer: YES Quicker and easier, IF you make the assumption that a "non-associative array" is indexed starting at 0: ``` if ($original_array == array_values($original_array)) ```
PHP: Getting array type
[ "", "php", "arrays", "" ]
I recently got the requirement for a person to receive a daily summary alert for any change within a SharePoint site; each site has an owner who is in charge of the content on their site. The current way we have something working is to automatically set up alerts for every list/library within the site. ``` // Get the Lists on this Site SPListCollection siteLists = currentSite.Lists; foreach (SPList list in siteLists) { if (!list.ToString().Equals("Master Page Gallery")) { if (list.ReadSecurity == 1) // user has read access to all items { // Create an Alert for this List Guid alertID = currentUser.Alerts.Add(list, SPEventType.All, SPAlertFrequency.Daily); // Set any additional properties SPAlert newAlert = currentUser.Alerts[alertID]; } } } ``` This creates two problems: 1. The user has a lot of different alerts created. Ideal: Only ONE email with the daily summary. 2. Some sort of monitor would have to be set up to check for new lists or libraries in the site and automatically set up alerts for the user. **Q: How can I create a daily summary alert for all changes in a site?**
I believe the solution you're looking for is available through the auditing framework. Auditing is very robust in SP, unfortunately it's easy to get overwhelmed by the output. The Audit is a property available on the SPSite, SPWeb, SPList, and SPItem properties. Adjust the specific audit flags (using the .Audit.AuditFlags properties) using this property to suite your needs (the specifics will depend on how you define "change" but almost anything you can think of is available). Details about the [SPAudit object](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spaudit.aspx) are available on MSDN. Once you've defined what/where you want to audit, you'll have to get that information back to your users. By default, SP sets up some nice reports that available at the site collection level ([url of site collection]/\_layouts/Reporting.aspx?Category=Auditing). These may meet your needs. Your initial solution mentioned alerts via email for the users. Given that most users want to centralize their information in email (though their MySite is great place to put a link to the reports!) you'll have a little more work to do. You can pull the required audit information through the object model using the SPAuditQuery and SPAuditEntryCollection objects. Again, [MSDN has some information](http://msdn.microsoft.com/en-us/library/bb466223.aspx) on how to use these objects. I would recommend setting up a custom SPJobDefinition that runs at the end of the day to email the users the audit report for their site. Andrew Connell has a great explaination of [how to setup a custom job](http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx) on his blog. **To summarize:** * enable auditing for the SPWeb's in question * create a report using SPAuditQuery and SPAuditEntryCollection for each SPWeb * create an SPJobDefinition that runs each night to email the report to each SPWeb owner
A thing to consider before enabling auditing policy on a site, is the performance overhead you add. I would recommend keeping the footprint as little as possible here! By that i mean if its only a certain content type or a certain list that you want this information from, be sure to only enable the information policy on these CT's or lists! Also keep the logging to a minimum. Eg if you are only interested in views, not deletion or restore, only log these events! On large sites i have seen auditing really trash performance! Also be aware of some caveats here: even though you can enable auditing on lists (as in not document libraries), alot of events (for example view events) is not logged specifically for list items! This is not described anywhere (in fact i have even seen Ted Pattison mention item level audit in an MSDN article) but i have it directly from CSS and product team that item level audit is not implemented in SP2007 because of performance issues. Instead you just get a list event in the log specifying that the list has been touched. Documents is tracked fairly ok, but i have seen problems with auditing view events on publishing page (which in the API is considered a document not a list item) depending on how and where auditing was set (for example if audit policies were implemented with inherited CT's) so thats something to be aware of. [edit: did some testing around this yesterday and its even worse: In fact **publishing pages** is **only** tracked if you set on site level audit policy! If you set a policy on a list or a content type (or even a content type that inherits from a content type with a policy) you will get **no** SPAuditItemType.Document level events at all. Set it on a site and you will get too many audits! Eg. a view will trigger x2 view events, and same with updates, so you end up with too much being logged. It definetely looks like a bug that nothing is audited when policies are put on lists and CT's...] The main message here is: careful what you log, since it will affect your sites performance TEST that what you expect to log is really logged! hth Anders Rask
How to create a daily summary alert for any change in a SharePoint site
[ "", "c#", "sharepoint", "sharepoint-2007", "alert", "alerts", "" ]
Following the suggestions of FxCop and my personal inclination I've been encouraging the team I'm coaching to use ReadOnlyCollections as much possible. If only so that recipients of the lists can't modify their content. In their theory this is bread & butter. The problem is that the List<> interface is much richer exposing all sorts of useful methods. Why did they make that choice? Do you just give up and return writable collections? Do you return readonly collections and then wrap them in the writable variety? Ahhhhh. --- Update: Thanks I'm familiar with the Framework Design Guideline and thats why the team is using FxCop to enforce it. However this team is living with VS 2005 (I know, I know) and so telling them that LINQ/Extension methods would solve their problems just makes them sad. They've learned that List.FindAll() and .FindFirst() provide greater clarity than writing a foreach loop. Now I'm pushing them to use ReadOnlyCollections they lose that clarity. Maybe there is a deeper design problem that I'm not spotting. -- Sorry the original post should have mentioned the VS2005 restriction. I've lived with for so long that I just don't notice.
Section 8.3.2 of the [.NET Framework Design Guidelines Second Edition](http://www.moserware.com/2008/12/private-life-of-public-api.html): > **DO** use `ReadOnlyCollection<T>`, a subclass of `ReadOnlyCollection<T>`, or in rare cases `IEnumerable<T>` for properties or return values representing read-only collections. We go with ReadOnlyCollections to express our intent of the collection returned. The `List<T>` methods you speak of were added in .NET 2.0 for convenience. In C# 3.0 / .NET 3.5, you can get all those methods back on `ReadOnlyCollection<T>` (or any `IEnumerable<T>`) using extension methods (and use LINQ operators as well), so I don't think there's any motivation for adding them natively to other types. The fact that they exist at all on List is just a historical note due to the presence of extension methods being available now but weren't in 2.0.
First off, `ReadOnlyCollection<T>` does implement `IEnumerable<T>` and `IList<T>`. With all of the extension methods in .NET 3.5 and LINQ, you have access to nearly all of the functionality from the original `List<T>` class in terms of querying, which is all you should do with a `ReadOnlyCollection<T>` anyways. That being said, your initial question leads me to make some suggestions... Returning `List<T>` is bad design, so it shouldn't be a point of comparison. `List<T>` should be used for implementation, but for the interface, `IList<T>` should be returned. The [Framework Design Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/) specifically state: "**DO NOT** use `ArrayList` or `List<T>` in public APIs." (Page 251) If you take that into consideration, there is absolutely no disadvantage to `ReadOnlyCollection<T>` when compared to `List<T>`. Both of these classes implement `IEnumerable<T>` and `IList<T>`, which are the interfaces that should be returned anyways.
Why doesn't ReadOnlyCollection<> include methods like FindAll(), FindFirst(),
[ "", "c#", "collections", "readonly-collection", "" ]
I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.: `monk, konm, nkom, bbc, cbb, dell, ledl, llde` The output should be categorised into rows: ``` 1. monk konm, nkom; 2. bbc cbb; 3. dell ledl, llde; ``` I already sorted them into alphabetical order and put them into an array. i.e.: `kmno kmno bbc bbc dell dell` However I am stuck in comparing and finding the matching anagram within the array. Any help will be greatly appreciated.
Javascript objects are excellent for this purpose, since they are essentially key/value stores: ``` // Words to match var words = ["dell", "ledl", "abc", "cba"]; // The output object var anagrams = {}; for (var i in words) { var word = words[i]; // sort the word like you've already described var sorted = sortWord(word); // If the key already exists, we just push // the new word on the the array if (anagrams[sorted] != null) { anagrams[sorted].push(word); } // Otherwise we create an array with the word // and insert it into the object else { anagrams[sorted] = [ word ]; } } // Output result for (var sorted in anagrams) { var words = anagrams[sorted]; var sep = ","; var out = ""; for (var n in words) { out += sep + words[n]; sep = ""; } document.writeln(sorted + ": " + out + "<br />"); } ```
Here is my take: ``` var input = "monk, konm, bbc, cbb, dell, ledl"; var words = input.split(", "); for (var i = 0; i < words.length; i++) { var word = words[i]; var alphabetical = word.split("").sort().join(""); for (var j = 0; j < words.length; j++) { if (i === j) { continue; } var other = words[j]; if (alphabetical === other.split("").sort().join("")) { console.log(word + " - " + other + " (" + i + ", " + j + ")"); } } } ``` where the output would be (the word, the match and the index of both): ``` monk - konm (0, 1) konm - monk (1, 0) bbc - cbb (2, 3) cbb - bbc (3, 2) dell - ledl (4, 5) ledl - dell (5, 4) ``` To get the characters in the in alphabetical order, I used split("") ot get an array, called sort() and used join("") to get a string from the array.
Anagrams finder in javascript
[ "", "javascript", "string", "function", "comparison", "anagram", "" ]
``` /** The following function checks the red black tree black height * @param n the root node is inputed then a traversal is done to calculate the black-height * @return Return an error message / mesages informing the user whether or not the black height was maintained * @author Ferron Smith */ public static void getCount (SkaRedBlackTreeNode skaRedBlackTreeNode) { VizRedBlackTreeNode n = skaRedBlackTreeNode.getVizRep(); if (validRoot(n)) { static int lcount = leftCount(n); static int rcount = rightCount(n); if (rcount == lcount) { n.displayMsg("Black height maintained"); } else // n.displayWarning("rcount " + rcount + " lcount " + lcount); n.displayError("Red Black Tree is unbalanced"); } } /** The following function counts all the black node of the left side of the tree * @param n the left child is inputed and a traversal is done to count all the black nodes * */ public static int leftCount (VizRedBlackTreeNode n) { if (n == null) return 0; else if (n.getrbtColr() == Color.black) return 1 + leftCount(n.getLeft()); else leftCount(n.getLeft()); } /** The following function counts all the black node of the right side of the tree * @param n the right child is inputed and a traversal is done to count all the black nodes * */ public static int rightCount (VizRedBlackTreeNode n) { if (n == null) return 0; else if (n.getrbtColr() == Color.black) { return 1 + rightCount (n.getRight()); else rightCount(n.getRight()); } } ``` This is redraft, do you think this one will work, i've tested it on certain conditions and as not failed me yet
As far as I can tell, you're checking black height only on the leftmost and rightmost paths down the tree. The definition of a red-black tree requires that black height be the same on *all* paths. For example, this invalid tree is not flagged by your program: ``` B / \ / \ / \ B B / \ / \ B R R B ``` Also, it doesn't check for cycles or if the keys are in order.
So I realize that you're working in java here, but here's some pseudocode that may help: ``` unsigned int blackHeight() height, heightLeft, heightRight = 0 if black height++ if left heightLeft = left->blackHeight() else heightLeft = 1 if right heightRight = right->blackHeight() else heightRight = 1 if heightLeft != heightRight //YOU HAVE A PROBLEM! height += heightLeft return height ``` I'm only just starting to experiment with red black trees myself, but I believe this algorithm should give you the black height on any node you call it from. Edit: I guess I should qualify, this would be code found within a node not within the tree. In c++ it would be called with a someNode->blackHeight().
Red Black Tree <Black Height> (Redraft)
[ "", "java", "tree", "red-black-tree", "" ]
I have a question regarding static function in php. let's assume that I have a class ``` class test { public function sayHi() { echo 'hi'; } } ``` if I do `test::sayHi();` it works without a problem. ``` class test { public static function sayHi() { echo 'hi'; } } ``` `test::sayHi();` works as well. What are the differences between first class and second class? What is special about a static function?
In the first class, `sayHi()` is actually an instance method which you are calling as a static method and you get away with it because `sayHi()` never refers to `$this`. Static functions are associated with the class, not an instance of the class. As such, `$this` is not available from a static context (`$this` isn't pointing to any object).
Simply, static functions function independently of the class where they belong. $this means, this is an object of this class. It does not apply to static functions. ``` class test { public function sayHi($hi = "Hi") { $this->hi = $hi; return $this->hi; } } class test1 { public static function sayHi($hi) { $hi = "Hi"; return $hi; } } // Test $mytest = new test(); print $mytest->sayHi('hello'); // returns 'hello' print test1::sayHi('hello'); // returns 'Hi' ```
php static function
[ "", "php", "class", "static", "member", "" ]
I have 20+ tables similar to table 1. Where all letters represent actual values. ``` Table 1: $ / cars |<1 | 2 | 3 | 4+ <10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p ``` A user input could be for example, (2.4, 24594) which is a value between f, g, j, and k. My Python function definition and pseudo-code to calculate this bilinear interpolation is as follows. ``` def bilinear_interpolation( x_in, y_in, x_high, x_low, y_low, y_high ): # interpolate with respect to x # interpolate with respect to y # return result ``` How should I store the data from table 1 (a file, a dict, tuple of tuples, or dict of lists), so I can perform the bilinear interpolation most efficiently and correctly?
If you want the most computationally efficient solution I can think of and are not restricted to the standard library, then I would recommend scipy/numpy. First, store the a..p array as a 2D numpy array and then both the $4k-10k and 1-4 arrays as 1D numpy arrays. Use scipy's interpolate.interp1d if both 1D arrays are monotonically increasing, or interpolate.bsplrep (bivariate spline representation) if not and your example arrays are as small as your example. Or simply write your own and not bother with scipy. Here are some examples: ``` # this follows your pseudocode most closely, but it is *not* # the most efficient since it creates the interpolation # functions on each call to bilinterp from scipy import interpolate import numpy data = numpy.arange(0., 16.).reshape((4,4)) #2D array prices = numpy.arange(10000., 50000., 10000.) cars = numpy.arange(1., 5.) def bilinterp(price,car): return interpolate.interp1d(cars, interpolate.interp1d(prices, a)(price))(car) print bilinterp(22000,2) ``` The last time I checked (a version of scipy from 2007-ish) it only worked for monotonically increasing arrays of x and y) for small arrays like this 4x4 array, I think you want to use this: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html#scipy.interpolate.bisplrep> which will handle more interestingly shaped surfaces and the function only needs to be created once. For larger arrays, I think you want this (not sure if this has the same restrictions as interp1d): <http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp2d.html#scipy.interpolate.interp2d> but they both require a different and more verbose data structure than the three arrays in the example above.
I'd keep a sorted list of the first column, and use the `bisect` module in the standard library to look for the values -- it's the best way to get the immediately-lower and immediately-higher indices. Every other column can be kept as another list parallel to this one.
Data storage to ease data interpolation in Python
[ "", "python", "interpolation", "" ]
I've been introduced to this wonderful project, [xhtmlrenderer; the flying saucer project](http://code.google.com/p/flying-saucer//). Problem is, is that where I work, it's strictly a microsoft shop and I haven't done any java development since college, and a smidge of WebSphere a few years back. I was wondering what it takes these days to do java development? I set up a quick proof of concept to see if I could do what I wanted with this project and it works great, however, I used jnbridge whose licenses are a bit on the expensive side but Visual Studio was what I had handy and got the job done with an hour of finagling. I'm wondering what it take to do java development these days? Are servlets still the norm? Is Apache where I should start looking to get a small web server up and running? Is Eclipse/Ganymede the IDE to use? Essentially what I want to do is pass a url to the service and have it spit back out a PDF. Just on vacation right now, and stuck on dial up, but can't stop thinking about this. Thought I'd post these thoughts now to see if I can get a jump start on next weeks work.
Eclipse is certainly the IDE on no budget, NetBeans is also free. I prefer IDEA from Intellij, but for something that sounds like such a side part of your project, it probably isn't worth the money. In terms of servlets, etc., it really depends on the archetecture/scalability you are looking for. If you are looking for something that needs to run as a small web interface, then something like Jetty or Tomcat with a basic servlet should be fine. You might be looking at something invoked via the command line, although starting a JVM for every conversion is going to be too heavy for all but the most trivial usages, but a little program that monitors a directory and pulls stuff out of it for the conversion may be what you need. If you give more details about the archetecture and how you are planing to use it you could get some more specific advice. In general .NET and Java development are quite similar (.NET was started to compete directly with Java, after all), but the real practical difference is that a lot of the .NET environment is kind of provided to you on a silver platter. You need a web container, you have IIS, you need a database, you have MS-SQL, You need an IDE, you have Visual Studio, etc., etc. In Java development, these are all choices to be made, there isn't really a default obvious good choice for a lot of things - there are many competitors. That can create a larger curve for a Microsoft shop than you are expecting.
Consider sneaking in IKVM (<http://www.ikvm.net/>) as it allows you to use Java components in a .NET environment.
Java in a Microsoft shop
[ "", "java", "pdf-generation", "xhtmlrenderer", "" ]
In SQL I have a column called "answer", and the value can either be 1 or 2. I need to generate an SQL query which counts the number of 1's and 2's for each month. I have the following query, but it does not work: ``` SELECT MONTH(`date`), YEAR(`date`),COUNT(`answer`=1) as yes, COUNT(`answer`=2) as nope,` COUNT(*) as total FROM results GROUP BY YEAR(`date`), MONTH(`date`) ```
Try the SUM-CASE trick: ``` SELECT MONTH(`date`), YEAR(`date`), SUM(case when `answer` = 1 then 1 else 0 end) as yes, SUM(case when `answer` = 2 then 1 else 0 end) as nope, COUNT(*) as total FROM results GROUP BY YEAR(`date`), MONTH(`date`) ```
I would group by the year, month, and in addition the answer itself. This will result in two lines per month: one counting the appearances for answer 1, and another for answer 2 (it's also generic for additional answer values) ``` SELECT MONTH(`date`), YEAR(`date`), answer, COUNT(*) FROM results GROUP BY YEAR(`date`), MONTH(`date`), answer ```
SQL; Only count the values specified in each column
[ "", "sql", "count", "" ]
I have a site with an image uploader, and whenever a user tries to upload an image, they are getting this error message: "No suitable nodes are available to serve your request." I've contacted the hosting company(mosso) and they have said that it is nothing on their end. Any idea what causes this issue, and what I can do to fix it?
I'm pretty sure it's a problem for your hosting company, as it has something to do with clustered servers.
There are several reasons that you might receive the "no suitable nodes" error regarding requests. A fuller discussion of this problem is at <http://nosuitablenodes.com>. Here's a summary: > First, this is an error message from a load balancer used to direct traffic to available backend servers for your site. It means no backend resources are available to produce the content requested. This is a default message basically meaning the site is currently unavailable. Think about your site's resources. Static HTML? Scripting language that creates the page content on the fly? DB-backed website? At each level there are resources that can cause a load balancer (that produced the error message) to time out and return this message. What can you do? (The real question!) First, contact the system administrator for your site. The system administrator with access to the load balancer will be able to pinpoint the service that is causing the error condition. As the site owner you can do a few things to remedy this condition yourself. Add more resources behind the load balancer (for hosted sites, this may be beyond your control) If you are not in control of the resources (i.e., you are using a hosting provider): Determine the actual cause and then for: 1. Web Server) Optimize the configuration to support more connections 2. File system/server) Move static content to a CDN, using byte-code caching in your scripting engine to reduces disk reads 3. Scripting engine) Optimize scripting engine to use byte-code caching 4. Database) optimize queries or move to a dedicated database instance 5. Remote resources) minimize dependencies on remote resources, or optimize them, if possible
How to Fix 'No Suitable Nodes' Error?
[ "", "php", "mysql", "upload", "nodes", "" ]
how can we get distinct result by using criteria in hibernate.
``` criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); ``` See also <https://forum.hibernate.org/viewtopic.php?t=941669>
A more flexible solution may be: ``` criteria.setProjection(Projections.distinct(Projections.property("property"))); ```
Getting unique result in Hibernate
[ "", "java", "hibernate", "criteria", "" ]
I'm using the `System.Drawing` classes to generate thumbnails and watermarked images from user-uploaded photos. The users are also able to crop the images using jCrop after uploading the original. I've taken over this code from someone else, and am looking to simplify and optimize it (it's being used on a high-traffic website). The previous guy had static methods that received a bitmap as a parameter and returned one as well, internally allocating and disposing a `Graphics` object. My understanding is that a `Bitmap` instance contains the entire image in memory, while `Graphics` is basically a queue of draw operations, and that it is idempotent. The process currently works as follows: * Receive the image and store it in a temporary file. * Receive crop coordinates. * Load the original bitmap into memory. * Create a new bitmap from the original, applying the cropping. * Do some crazy-ass brightness adjusting on the new bitmap, maybe (?) returning a new bitmap (I'd rather not touch this; pointer arithmetics abound!), lets call this A. * Create another bitmap from the resulting one, applying the watermark (lets call this B1) * Create a 175x175 thumbnail bitmap from A. * Create a 45x45 thumbnail bitmap from A. This seems like a lot of memory allocations; my question is this: is it a good idea to rewrite portions of the code and reuse the `Graphics` instances, in effect creating a pipeline? In effect, I only need 1 image in memory (the original upload), while the rest can be written directly to disk. All the generated images will need the crop and brightness transformations, and a single transformation that is unique to that version, effectively creating a tree of operations. Any thought or ideas? Oh, and I should probably mention that this is the first time I'm really working with .NET, so if something I say seems confused, please bear with me and give me some hints.
Reusing Graphics objects will probably not result in significant performance gain. The underlying GDI code simple creates a device context for the bitmap you have loaded in RAM (a Memory DC). The bottleneck of your operation appears to be in loading the image from disk. Why reload the image from disk? If it is already in a byte array in RAM, which it should be when it is uploaded - you can just create a memory stream on the byte array and then create a bitmap from that memory stream. In other words, save it to the disk, but don't reload it, just operate on it from RAM. Also, you shouldn't need to create a new bitmap to apply the watermark (depending on how it'd done.) You should profile the operation to see where it needs improvement (or even if it needs to be improved.)
The process seems reasonable. Each image has to exist in memory before it is saved to disk - so each version of your thumbnails will be in memory first. The key to making sure this works efficiently is to Dispose your Graphics and Bitmap objects. The easiest way to do that is with the using statement. ``` using( Bitmap b = new Bitmap( 175, 175 ) ) using( Graphics g = Graphics.FromBitmap( b ) ) { ... } ```
Efficient image manipulation in C#
[ "", "c#", ".net", "asp.net", "image", "" ]
``` import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value ``` In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad. except str,e: doesn't catch it? why? system: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Here is the solution from [python mailing list](http://groups.google.com/group/comp.lang.python/browse_frm/thread/6f82aa367e86a54e/6891821d373b50a8#6891821d373b50a8), not very elegant but will work if can't avoid the need for such hack ``` import sys try: raise "a string exception" except: e, t, tb = sys.exc_info() if not isinstance(e, str): raise print "caught", e ```
The generic `except:` clause is the only way to catch all str exceptions. str exceptions are a legacy Python feature. In new code you should use `raise Exception("xxx")` or raise your own Exception subclass, or `assert 0, "xxx"`.
How to catch str exception?
[ "", "python", "exception", "string", "" ]
* I need to "proxy" a feed * and leave most of the nodes unspoiled * and transform the content of a few known nodes by calling some java methods * and return the transformed feed Of course I prefer to avoid - loading in memory the whole feed - transform other nodes - bad performance It's a kind of java pipe ! Thanks for your recommendations
This is something I use: ``` import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMResult; import org.w3c.dom.Document; ... TransformerFactory mTransformFactory = TransformerFactory.newInstance(); cTransformer = mTransformFactory.newTransformer(new StreamSource(new StringReader(StringUtil.readFromResource("/foo.xslt")))); Document mResultDoc = XmlUtil.createDocument(); Document mResultDoc = XmlUtil.parseXmlFile("foo.xml"); transformer.transform(new DOMSource(source), new DOMResult(mResultDoc)); ``` Since you want to avoid memory overhead you should replace the DOMSource and DOMResult usage with SAX equivalents. The String and XML util class usage should be obvious from context.
Well I don't know about the "not loading into memory" but if you want to transform xml you should consider **[xslt](http://en.wikipedia.org/wiki/Xslt)** and **[xpath](http://www.ibm.com/developerworks/library/x-javaxpathapi.html)**.
Effective way to transform a few nodes contents of feeds
[ "", "java", "xml", "xslt", "rss", "atom-feed", "" ]
For an online game (MMORPG) I want to create characters (players) with random strength values. The stronger the characters are, the less should exist of this sort. Example: * 12,000 strength 1 players * 10,500 strength 2 players * 8,500 strength 3 players * 6,000 strength 4 players * 3,000 strength 5 players Actually, I need floating, progressive strength values from 1.1 to 9.9 but for this example it was easier to explain it with integer strengths. Do you have an idea how I could code this in PHP? Of course, I would need mt\_rand() to generate random numbers. But how can I achieve this pyramid structure? What function is it? Root function, exponential function, power function or logarithm function? Thanks in advance! It should look like this in a graph: [Pyramid graph http://img7.imageshack.us/img7/107/pyramidy.jpg](http://img7.imageshack.us/img7/107/pyramidy.jpg)
You can simulate a distribution such as the one you described using a logarithmic function. The following will return a random strength value between 1.1 and 9.9: ``` function getRandomStrength() { $rand = mt_rand() / mt_getrandmax(); return round(pow(M_E, ($rand - 1.033) / -0.45), 1); } ``` Distribution over 1000 runs (where `S` is the strength value floored): ``` S | Count --+------ 1 - 290 2 - 174 3 - 141 4 - 101 5 - 84 6 - 67 7 - 55 8 - 50 9 - 38 ``` ##Note: This answer was updated to include a strength value of 1.1 (which wasn't included before because of the rounding) and to fix the name of the [`mt_getrandmax()`](https://www.php.net/manual/en/function.mt-getrandmax.php) function
The simplest way to do this would be to provide 'bands' for where a random number should go. In your example, you have 15 players so you could have: ``` rand < 1/15, highest strength 1/15 < rand < 3/15, second highest 3/15 < rand < 6/15, third highest 6/15 < rand < 10/15, fourth highest 10/15 < rand < 15/15, lowest strength ``` You could also parameterise such a function with a 'max' number of each band that you allow and when the band is filled, it is subsumed into the next lowest existing band (apart from the bottom band, which would be subsumed into the next highest) to ensure only a certain number of each with a random distribution. Edit adding from my comments: To get a floating range pyramid structure the best function would most likely be a logarithm. The formula: ``` 11 - log10(rand) ``` would work (with log10 being a logarithm with base 10) as this would give ranges like: ``` 1 < rand < 10 = 9 < strength < 10 10 < rand < 100 = 8 < strength < 9 100 < rand < 1000 = 7 < strength < 8 etc. ``` but rand would need to range from 1 to 10^10 which would require a lot of randomness (more than most random generators can manage). To get a random number in this sort of range you could multiply some together. 3 random numbers could manage it: ``` 11 - log10(rand1 * rand2 * rand3) ``` with rand1 having range 1-10000 and rand2 and rand3 having range 1-1000. This would skew the distribution away from a proper pyramid slightly though (more likely to have numbers in the centre I believe) so it may not be suitable.
Generate random player strengths in a pyramid structure (PHP)
[ "", "php", "random", "" ]
I'm trying to work out how to iterate though a returned SimpleXML object. I'm using a toolkit called [Tarzan AWS](http://tarzan-aws.com/), which connects to Amazon Web Services (SimpleDB, S3, EC2, etc). I'm specifically using SimpleDB. I can put data into the Amazon SimpleDB service, and I can get it back. I just don't know how to handle the SimpleXML object that is returned. The Tarzan AWS documentation says this: > Look at the response to navigate through the headers and body of the response. Note that this is an object, not an array, and that the body is a SimpleXML object. Here's a sample of the returned SimpleXML object: ``` [body] => SimpleXMLElement Object ( [QueryWithAttributesResult] => SimpleXMLElement Object ( [Item] => Array ( [0] => SimpleXMLElement Object ( [Name] => message12413344443260 [Attribute] => Array ( [0] => SimpleXMLElement Object ( [Name] => active [Value] => 1 ) [1] => SimpleXMLElement Object ( [Name] => user [Value] => john ) [2] => SimpleXMLElement Object ( [Name] => message [Value] => This is a message. ) [3] => SimpleXMLElement Object ( [Name] => time [Value] => 1241334444 ) [4] => SimpleXMLElement Object ( [Name] => id [Value] => 12413344443260 ) [5] => SimpleXMLElement Object ( [Name] => ip [Value] => 10.10.10.1 ) ) ) [1] => SimpleXMLElement Object ( [Name] => message12413346907303 [Attribute] => Array ( [0] => SimpleXMLElement Object ( [Name] => active [Value] => 1 ) [1] => SimpleXMLElement Object ( [Name] => user [Value] => fred ) [2] => SimpleXMLElement Object ( [Name] => message [Value] => This is another message ) [3] => SimpleXMLElement Object ( [Name] => time [Value] => 1241334690 ) [4] => SimpleXMLElement Object ( [Name] => id [Value] => 12413346907303 ) [5] => SimpleXMLElement Object ( [Name] => ip [Value] => 10.10.10.2 ) ) ) ) ``` So what code do I need to get through each of the object items? I'd like to loop through each of them and handle it like a returned mySQL query. For example, I can query SimpleDB and then loop though the SimpleXML so I can display the results on the page. Alternatively, how do you turn the whole shebang into an array? I'm new to SimpleXML, so I apologise if my questions aren't specific enough.
You can use the `SimpleXML` object (or its properties) in a `foreach` loop. If you want to loop through all the 'records' something like this can be used to access and display the data: ``` //Loop through all the members of the Item array //(essentially your two database rows). foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){ //Now you can access the 'row' data using $Item in this case //two elements, a name and an array of key/value pairs echo $Item->Name; //Loop through the attribute array to access the 'fields'. foreach($Item->Attribute as $Attribute){ //Each attribute has two elements, name and value. echo $Attribute->Name . ": " . $Attribute->Value; } } ``` Note that $Item will be a SimpleXML object, as is $Attribute, so they need to be referenced as objects, not arrays. While the example code above is looping through the arrays in the SimpleXML object ($SimpleXML->body->QueryWithAttributesResult->Item), you can also loop through a SimpleXML object (say $SimpleXML->body->QueryWithAttributesResult->Item[0]), and that would give you each of the object's properties. Each child element of a SimpleXML object is an XML entity. If the XML entity (tag) is not unique, then the element is simply an array of SimpleXML objects representing each entity. If you want, this should create a more common row/fields array from your SimpleXML object (or get you close): ``` foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){ foreach($Item->Attribute as $Attribute){ $rows[$Item->Name][$Attribute->Name] = $Attribute->Value; } } //Now you have an array that looks like: $rows['message12413344443260']['active'] = 1; $rows['message12413344443260']['user'] = 'john'; //etc. ```
``` get_object_vars($simpleXMLElement); ```
Looping through a SimpleXML object, or turning the whole thing into an array
[ "", "php", "amazon-web-services", "simplexml", "amazon-simpledb", "" ]
Is it possible to use the Assembly.LoadFrom overload with the Evidence parameter to ensure the assembly is strongly named? I want to be able to specify the assembly name, culture, version, and public key token. If any of this information does not match the assembly should fail to load.
I found another way to do this. ``` var assemblyName = new AssemblyName(<fully qualified type name>); assemblyName.CodeBase = <path to assembly> Assembly.Load(assemblyName); ```
You can get an Assembly's public key after loading it - if it loads successfully and has a public key, then it's strong-named: ``` Assembly assembly = Assembly.LoadFrom (...); byte[] pk = assembly.GetName().GetPublicKey(); ``` Better still, check the assembly's public key and version info *before* loading it: ``` AssemblyName an = AssemblyName.GetAssemblyName ("myfile.exe"); byte[] publicKey = an.GetPublicKey(); CultureInfo culture = an.CultureInfo; Version version = an.Version; ``` If GetPublicKey() returns a non-null value, and then the assembly successfully loads, it has a valid strong name.
Assembly.LoadFrom - using Evidence overload to verify strong name signature
[ "", "c#", ".net", "assemblies", "" ]
What is the maximum number of connections to SQL Server 2005 for one user? I'm having a problem with C# code trying to make multiple connection to the database in different threads. After about five threads the connections in other threads start timing out. If i knew the exact number of connection for one user, even if it was one, would help with knowing how many threads I can have loading at one time.
5 connections and you start to timeout? That smells like connections not being closed and/or concurrency issues (locks/deadlocks). I have services that spawn threads and generate upwards of 100 connections without any problems.
A long shot, 5 connections sounds like you might have licensing issues. Is the SQL instance you're using limited to the number of concurrent connections? (This is not something I've ever had to deal with. I know there are CAL licensing plans, and that there may be limits if you are using SQL Server Express edition.)
Maximum number of connection to SQL Server database
[ "", "c#", "sql-server-2005", "database-connection", "" ]
We're using maven 2.1.0. I have multiple modules that are completely separate, but still have many common dependencies. Like log4J, but some modules don't need it. I am wondering if it is a good idea to declare all common dependencies in one parent file in the `<dependencyManagement>` section or is there a better way to deal with this? A follow up question about `<dependencyManagement>`. If I declare Log4J in the `<dependencyManagement>` section of the parent and a sub project does not use it, will it be included anyway?
Each module should have its own POM and where it declares its own dependencies. This not only tracks external dependencies, but also internal ones. When you use Maven to build a project it will sort the whole lot out. So if many modules (perhaps all) depend on log4j, then it will only be included once. There are some problems if your modules depend on different versions of log4j but this approach usually works fine. It is also useful (if there are more than 1-2 developers working together) to set up an internal repository (like [Artifactory](http://sourceforge.net/projects/artifactory/)) and use that internally. It makes it much easier to deal with libraries that are not in the public repos (just add it to your internal repo!) and you can also use build tools to push builds of your own code there so other can use the modules without checking out the code (useful in larger projects)
If you have a parent project, you can declare all dependencies and their versions in the dependencyManagement section of the parent pom. This *doesn't* mean that all projects will use all those dependencies, it means that if a project does declare the dependency, it will inherit the configuration, so it only need declare the groupId and artifactId of the dependency. You can even declare your child projects in the parent's dependencyManagement without introducing a cycle. Note you can also do similar with plugins by declaring them in the pluginManagement section. This means any child declaring the plugin will inherit the configuration. For example, if you have 4 projects, *parent*, *core*, *ui* and *utils*, you could declare all the external dependences and the internal project versions in the parent. The child projects then inherit that configuration for any dependencies they declare. If all modules are to have the same version, these can be even be declared as properties in the parent. An example parent is as follows: ``` <project> <modelVersion>4.0.0</modelVersion> <groupId>name.seller.rich</groupId> <artifactId>parent</artifactId> <version>1.0.0</version> <packaging>pom</packaging> <dependencyManagement> <dependencies> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>name.seller.rich</groupId> <artifactId>ui</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>name.seller.rich</groupId> <artifactId>core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>name.seller.rich</groupId> <artifactId>utils</artifactId> <version>${project.version}</version> </dependency> </dependencies> </dependencyManagement> <modules> <module>utils</module> <module>core</module> <module>ui</module> </modules> </project> ``` And the utils, core, and ui projects inherit all the relevant versions. utils: ``` <project> <modelVersion>4.0.0</modelVersion> <groupId>name.seller.rich</groupId> <artifactId>utils</artifactId> <!--note version not declared as it is inherited--> <parent> <artifactId>parent</artifactId> <groupId>name.seller.rich</groupId> <version>1.0.0</version> </parent> <dependencies> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> </dependencies> </project> ``` core: ``` <project> <modelVersion>4.0.0</modelVersion> <groupId>name.seller.rich</groupId> <artifactId>core</artifactId> <parent> <artifactId>parent</artifactId> <groupId>name.seller.rich</groupId> <version>1.0.0</version> </parent> <dependencies> <dependency> <groupId>name.seller.rich</groupId> <artifactId>utils</artifactId> </dependency> </dependencies> ``` ui: ``` <project> <modelVersion>4.0.0</modelVersion> <groupId>name.seller.rich</groupId> <artifactId>ui</artifactId> <parent> <artifactId>parent</artifactId> <groupId>name.seller.rich</groupId> <version>1.0.0</version> </parent> <dependencies> <dependency> <groupId>name.seller.rich</groupId> <artifactId>core</artifactId> </dependency> </dependencies> </project> ```
Declare dependency in <dependencyManagement> section even if dependency not used everywhere?
[ "", "java", "maven-2", "dependencies", "" ]
I have a table in my DB with a list of people. I need to create a list of random buddies every day. The idea is that every day every person is paired with a different random person for that day. Since the table may get very large I was wondering what would be the best way to do such a thing? I have thought of 2 ideas but I am not so sure about them in regard to performance. 1) I use a random number generator to randomly pick two ids. The problem with that is that I have to constantly make sure the numbers weren't called yet and as I get close to the end of the list this can get real slow. 2) start every one off with the guy below them in the list and simply move down one every day until you get to the bottom at whcih point I move back to the top. Any other ideas? Thanks
Perhaps you can make a query that sorts the table randomly, and then just pair people from the top down. The first entry gets paired with the second, third with the fourth and so on. SQL Server example: ``` SELECT * FROM Table ORDER BY NEWID() ```
It's not really that hard, using a random-generator isn't really slow but if you are very unlucky the time complexity will become O(n^2) and in best case O(1), how do you like that? However, just have a table that connects two persons, see if their IDs occure which is fast, if it doesn't, just add their ID's, use T-SQL to loose extra connections.
Generating random couples in C#
[ "", "c#", "performance", "random", "combinations", "" ]
I know that Powershell is quite powerful in that it is a scripting language in which you have access to the entire .Net framework (thats all I know about it). But i'm struggling to understand what's the big hype about Powershell when I could use C# to code the exact same thing?
I think you are asking the wrong question. It should be: *"Why should I use C# when I could use Powershell to code the same thing?"* This is the old argument of scripting versus compiled software revisited. A scripting solution is more flexible (you just need Notepad to edit the script, no compiler is required). For a small task, a script is faster to write, deploy and change than creating a project in Visual Studio, compiling it, deploying it to the target, correcting the code, compiling it again, deploying it again... For any bigger task, I definitely prefer an IDE that compiles my code. The error messages on a broken build alone are a huge help for finding the cause. (Runtime efficiency is usually better in a compiled software, but with modern CPUs it comes down to a difference of a few milli seconds, so for most projects, it does not matter any more.) You **can** do any kind of project in either C# or Powershell. That doesn't mean you **should**.
When not using Powershell as a shell but a programming environment, you can think of Powershell as a kind of interactive .NET playground. I'd never use Powershell for GUI prototyping but I have used it in the past for playing around with .NET objects and their methods to solve a particular problem. Simply altering a commandline is more productive than doing an edit/save/compile/run cycle every time you make a change. Furthermore, the appropriate domains for either language are very different. Powershell is, at its heart an adminstration and automation tool, having streamlined access to many things that may be more awkward to use from another environment, like the Registry, certificate store, WMI and others. You probably don't want to write an enterprisey database application with Powershell and you probably don't want to write a C# program just to copy some stuff around in the file system.
Why would I use Powershell over C#?
[ "", "c#", "powershell", "" ]
I am trying to search an XML field within a table, This is not supported with EF. Without using pure Ado.net is possible to have native SQL support with EF?
For .NET Framework version 4 and above: use [`ObjectContext.ExecuteStoreCommand()`](http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.executestorecommand.aspx) if your query returns no results, and use [`ObjectContext.ExecuteStoreQuery`](http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.executestorequery.aspx) if your query returns results. For previous .NET Framework versions, here's a sample illustrating what to do. Replace ExecuteNonQuery() as needed if your query returns results. ``` static void ExecuteSql(ObjectContext c, string sql) { var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection; DbConnection conn = entityConnection.StoreConnection; ConnectionState initialState = conn.State; try { if (initialState != ConnectionState.Open) conn.Open(); // open connection if not already open using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } finally { if (initialState != ConnectionState.Open) conn.Close(); // only close connection if not initially open } } ```
Using `Entity Framework 5.0` you can use [`ExecuteSqlCommand`](http://msdn.microsoft.com/en-us/library/system.data.entity.database.executesqlcommand%28v=vs.103%29.aspx) to execute multi-line/multi-command pure `SQL` statements. This way you won't need to provide any backing object to store the returned value since the method returns an int (the result returned by the database after executing the command). Sample: ``` context.Database.ExecuteSqlCommand(@ "-- Script Date: 10/1/2012 3:34 PM - Generated by ExportSqlCe version 3.5.2.18 SET IDENTITY_INSERT [Students] ON; INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (12,N'First Name',N'SecondName',{ts '1988-03-02 00:00:00.000'},N'RUA 19 A, 60',N'MORADA DO VALE',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3346-7125',NULL,NULL,{ts '2011-06-04 21:25:26.000'},2,1); INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (13,N'FirstName',N'LastName',{ts '1976-04-12 00:00:00.000'},N'RUA 201, 2231',N'RECANTO FELIZ',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3341-6892',NULL,NULL,{ts '2011-06-04 21:38:38.000'},2,1); "); ``` For more on this, take a look here: [Entity Framework Code First: Executing SQL files on database creation](http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2011/07/15/entity-framework-code-first-executing-sql-files-on-database-creation.aspx)
Is it possible to run native sql with entity framework?
[ "", "sql", "entity-framework", "ado.net", "" ]
How can I cast `Long` to `BigDecimal`?
You'll have to create a new `BigDecimal`. ``` BigDecimal d = new BigDecimal(long); ```
For completeness you can use: ``` // valueOf will return cached instances for values zero through to ten BigDecimal d = BigDecimal.valueOf(yourLong); ``` 0 - 10 is as of the java 6 implementation, not sure about previous JDK's
cast Long to BigDecimal
[ "", "java", "bigdecimal", "" ]
``` <div class="poll"> <h1>Poll</h1> <form name="pollvoteform1" method="post" xxaction="/plugins/content_types/poll/poll.php"> <p class="tekstaanmelden"><b>Het regent </b></p> <input type="hidden" name="poll" value="1"> <input type="hidden" name="cmd" value=""> <div class="pollOption"><input type="radio" class="stelling" name="poll_option1" value="1"></div><div class="pollOptionText">Eens</div><br clear="all"><div class="pollOption"><input type="radio" class="stelling" name="poll_option1" value="2"></div><div class="pollOptionText">Oneens</div><br clear="all"><div class="pollOption"><input type="radio" class="stelling" name="poll_option1" value="3"></div><div class="pollOptionText">Waar</div><br clear="all"><div class="pollOption"><input type="radio" class="stelling" name="poll_option1" value="4"></div><div class="pollOptionText">Niet waar</div><br clear="all"> <input type="button" name="bt_submit" class="pollButtonNormal" onmouseover="this.className='pollButtonHigh';" onmouseout="this.className='pollButtonNormal';" value="Stem" onclick="javascript:vote1();" style="padding-bottom: 3px; margin-top: 5px;"> <input type="button" name="bt_submit2" class="pollButtonNormal" onMouseOver="this.className='pollButtonHigh';" onMouseOut="this.className='pollButtonNormal';" value="Bekijk resultaten" onclick="javascript:viewResults1();" style="padding-bottom: 3px; margin-top: 5px; width:98px;"> </form> </div> <div style="display:none;width: 175px;"> <form><input type="button" name="bt_submit" class="pollButtonNormal" onmouseover="this.className='pollButtonHigh';" onmouseout="this.className='pollButtonNormal';" value="Resultaten" onclick="javascript:viewResults1();" style="padding-bottom: 3px; margin-top: 10px; "></form> </div> ``` In my script I have: var r=document.forms.pollvoteform1.poll\_option1; But I get the error: document.forms.pollvoteform1 is undefined And I don't understand why. Since the pollvoteform1 and the poll\_option\_1 are both there. //update: the full js code ``` function vote() { var r=document.forms.pollvoteform1.poll_option1; var voted=false; if (r.value!=null && r.checked){ voted=true; } else { for (i=0;i<r.length;i++){ if (r[i].checked) { voted=true; break; } }} if (voted) { document.forms.pollvoteform1.submit(); } else { alert("you didn't make a choice yet"); } } ```
Its either ``` var r=document.forms['pollvoteform1'].poll_option1; ``` or if that dosnt work ``` var r=document.forms[0].poll_option1; ```
Try adding an ID tag to the form. It should be the same as the name tag.
js seems not to be able to find my form
[ "", "javascript", "" ]
We create a `Set` as: ``` Set myset = new HashSet() ``` How do we create a `List` in Java?
``` List myList = new ArrayList(); ``` or with generics ([Java 7](https://docs.oracle.com/javase/tutorial/java/generics/types.html#diamond) or later) ``` List<MyType> myList = new ArrayList<>(); ``` or with generics (Old java versions) ``` List<MyType> myList = new ArrayList<MyType>(); ```
Additionally, if you want to create a list that has things in it (though it will be fixed size): ``` List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You"); ```
How to make a new List in Java
[ "", "java", "list", "collections", "" ]
I want to create a class that initializes a timer which will be used as a central core for other class members to register themselves for the timer elapsed event. My problem is that I don't really know how to expose the timer elapsed event to other classes. One solution, that I think might work is that I simply expose the timer as a public property which will return the timer object and I can call the timer elapsed event from this object, for example: ``` MyAppTimer appTimer = new MyAppTimer(); Timer timer = appTimer.GetAppTimer; timer.Elapsed += SomeMethod; ``` But with this solution I will be exposing the entire timer which I don't want. How can I pass in a method in the MyAppTimer class which will register the method with the timer's elapsed event internally? Is it something to do with delegates? Maybe something like: ``` public void RegisterHandler(someStuffGoesHere) //What do I pass in here? { timer.Elapsed += someStuffGoesHere; } ```
You can create an event with explicit accessors : ``` public event EventHandler TimerElapsed { add { timer.Elapsed += value; } remove { timer.Elapsed -= value; } } ``` The clients of your class can subscribe directly to the TimerElapsed event : ``` appTimer.TimerElapsed += SomeHandlerMethod; ``` If you want to use a RegisterHandler method as shown in your code, the type of the parameter should be EventHandler **EDIT:** note that with this approach, the value of sender parameter will be the Timer object, not the MyAppTimer object. If that's a problem, you can do that instead : ``` public MyAppTimer() { ... timer.Elapsed += timer_Elapsed; } private void timer_Elapsed(object sender, EventArgs e) { EventHandler handler = this.TimerElapsed; if (handler != null) handler(this, e); } ```
As others have mentioned, exposing an Event is probably the way you want to go, but to answer your question about the type required in your RegisterHandler method, it would look something like: ``` using System.Timers; ...snip... public void RegisterHandler(ElapsedEventHandler callback) { timer.Elapsed += callback; } ```
Registering for timer elapsed events
[ "", "c#", ".net", "delegates", "timer", "" ]
I embedded .NET's WebBrowser into a form that has some other buttons. The application that I'm developing does not use a keyboard, but uses a touchscreen. So it actually uses the mouse only. To scroll the webbrowser down, I made two custom buttons. When I click those buttons, it should send a "PageDown" key stroke to the browser, and the browser should scroll down. So the code on the click event is as follows: ``` theForm.Activate(); Application.DoEvents(); theBrowser.Focus(); Application.DoEvents(); SendKeys.Send(key); ``` Where 'theForm' is the form and 'theBrowser' is the browser instance. So when I click the button, nothing happens. When I first click on the browser, and then click the button, it DOES work. But im giving it focus right? And i gave the application enough space to set the focus? But now what I think is strange. When I put a MessageBox.Show("HELLO"); in the code, like this: ``` theForm.Activate(); Application.DoEvents(); theBrowser.Focus(); MessageBox.Show("HELLO"); Application.DoEvents(); SendKeys.Send(key); ``` ...it does work immediatly when I click the button. So the question is: Why does this code not work when i leave the MessageBox.Show() out, but does when I do use the MessageBox.Show()? Hope you can help, thanks in advance...
To me this looks like the wrong way to be going about this. Try something along the lines of this [C++ sample](http://www.codeproject.com/KB/miscctrl/scrollbrowser.aspx?df=100&forumid=2537&exp=0&select=780783) or this [C# sample](http://www.ben-rush.net/blog/PermaLink.aspx?guid=635eccfd-f33b-49f5-a351-02bf1a33cfdd&dotnet=consultant). At least be explicit about the HWND you are sending the message to if you are going to be simulating key presses.
Without getting into whether your approach is correct. (and I suspect it is not). I would gamble that You have a race condition. Which mean that the browser control needs more time to load and respond to events than you are letting it. So when you do Message.Show, suddenly the thread that you send the events is blocked and it is letting the browser control complete intializing or something else. It is hard to know from your question whether you are running on Mobile, or regular desktop because there are better approaches to deal with touch. Look at Window7 Api for multi Touch or WPF 4.0 (which is shared by Surface Touch SDK aswell). Hope that helps. Ariel
How come my code works when I use a MessageBox.Show() in between, and does not work without it?
[ "", "c#", ".net", "messagebox", "" ]
I just wrote a whole blurb on how I reached this point, but figured it's easier to post the code and leave it at that :) As far as I can tell, the performance of test3() should be the same as test1() - the only difference is where the exception is caught (inside the calling method for test1(), inside the called method for test3()) Why does test3() regularly take time somewhere between test1() and test2() to complete? ``` import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class Test { public static void main(String[] args) { warmup(); test1(2500000); // Exception caught inside the loop test2(2500000); // Exception caught outside the loop test3(2500000); // Exception caught "inside" the loop, but in the URLEncoder.encode() method } private static void warmup() { // Let URLEncoder do whatever startup it needs before we hit it String encoding = System.getProperty("file.encoding"); try { URLEncoder.encode("ignore", encoding); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private static void test1(int count) { String encoding = System.getProperty("file.encoding"); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { try { URLEncoder.encode("test 1 " + i, encoding); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println("Performed " + count + " encodings trying to catch each in " + (end - start) + "ms"); } private static void test2(int count) { String encoding = System.getProperty("file.encoding"); long start = System.currentTimeMillis(); try { for (int i = 0; i < count; i++) { URLEncoder.encode("test 2" + i, encoding); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("Performed " + count + " encodings trying to catch all in " + (end - start) + "ms"); } private static void test3(int count) { long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { URLEncoder.encode("test 3 " + i); } long end = System.currentTimeMillis(); System.out.println("Performed " + count + " encodings with a deprecated method in " + (end - start) + "ms"); } } ``` Running it gives me (JDK 1.6.0\_13 on Windows XP) the output: ``` Performed 2500000 encodings trying to catch each in 4906ms Performed 2500000 encodings trying to catch all in 2454ms Performed 2500000 encodings with a deprecated method in 2953ms ``` So, responses are pretty close (we're talking something that's so trivial it's irrelevant), btu I'm curious! **Later...** People have suggested that there's JVM optimization getting in the way - I agree. So, I've broken each test down into it's own class/main method and each individually. The results from this: ``` 1 - Performed 2500000 encodings trying to catch each in 5016ms 1 - Performed 5000000 encodings trying to catch each in 7547ms 1 - Performed 5000000 encodings trying to catch each in 7515ms 1 - Performed 5000000 encodings trying to catch each in 7531ms 2 - Performed 2500000 encodings trying to catch all in 4719ms 2 - Performed 5000000 encodings trying to catch all in 7250ms 2 - Performed 5000000 encodings trying to catch all in 7203ms 2 - Performed 5000000 encodings trying to catch all in 7250ms 3 - Performed 2500000 encodings with a deprecated method in 5297ms 3 - Performed 5000000 encodings with a deprecated method in 8015ms 3 - Performed 5000000 encodings with a deprecated method in 8063ms 3 - Performed 5000000 encodings with a deprecated method in 8219ms ``` Interesting observations: * The gap between catching each call versus catching everything outside of the loop is reduced in it's own JVM (I assume optimization is not going the whole hog in the all-tests-in-one case due to the other iterations that have been performed) * The gap between the try/catch on my side versus the try/catch inside URLEncoder.encode() is now much smaller (half a second over 5000000 iterations) but still consistantly there...
Running it in the order you posted: > Performed 2500000 encodings trying to > catch each in 34208ms > Performed 2500000 encodings trying to catch all > in 31708ms > Performed 2500000 encodings > with a deprecated method in 30738ms Reversing the order: > Performed 2500000 encodings with a > deprecated method in 32598ms > Performed > 2500000 encodings trying to catch all > in 31239ms > Performed 2500000 encodings > trying to catch each in 31208ms Therefore I don't actually think you're seeing what you think you're seeing (certainly, test1 is not 66% slower than test3, which is what your benchmarks suggest)
Yeah you have your explanation, I think: 3 is slightly slower than 1 due to the extra method call involved. 2 is faster than either since it does not 'set up' and 'tear down' exception-catching-related bytecode in each loop. You can crack open the byte code to see the difference with javap -- see <http://www.theserverside.com/tt/articles/article.tss?l=GuideJavaBytecode> Whether you use 2 or 1 depends on which behavior you want, since they are not equivalent. I would choose 1 over 3 since you are then not using a deprecated method, which is more important than tiny speed increases -- but as it happens 1 is faster anyhow.
Java Exceptions Loops and Deprecation (or is it a URLEncoding thing?)
[ "", "java", "performance", "exception", "urlencode", "malformedurlexception", "" ]
When I use make command, like make mica2, in TinyOS. The following problem will occured: ``` Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) make: *** [exe0] Error 1 ``` I reinstalled JAVA and add env variables, but it didn't work. I use TinyOS 2.1 and JAVA 1.5 u18. Can any one help me? Problem solved by install JDK 1.6. Although when I run tos-check-env command, it shows me a warning that tell me its not JDK 1.4 or 1.5. Maybe it is a bug in TinyOS.
an UnsupportedClassVersionError means you are trying to run byte code on an older version of the JVM than it was compiled in. You can use a class file viewer to check which version of the JDK the source code was compiled it and make sure it is compatible with JAVA 1.5 u18.
The error you're getting means that the version of Java that's running is trying to load a class that was compiled with an incompatible version of Java. With the information you've provided it's not possible to diagnose the problem any more specifically than this - look at any Java libraries you're using and what their required Java versions are. If you can't find anything wrong here, you might just need to clean out some cached \*.class files that were built with a version of Java before the reinstall. Finally, if you have multiple JVMs installed be sure that `make` is using the one you expect. It's definitely possible for you to have installation Java 1.5u18 but for the application to still be finding and using a 1.4 JVM from somewhere.
Tinyos Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
[ "", "java", "tinyos", "" ]
Various JavaScript libraries (e.g. jQuery) offer an `each` method: ``` $.each(myObj, myFunc); ``` What's the advantage over using the built-in `for..in` loop: ``` for(var i in myObj) { myFunc(i, myObj[i]); } ``` In both cases I'd have to check for unwanted properties (usually functions), so I don't see why the each method is provided in the first place.
I can think of at least 3 advantages, though they are relatively small. 1. It follows the jQuery chainability paradigm, allowing you to chain multiple iterations together if needed. 2. It breaks out both the key and the value for you as arguments to the callback, removing this code from your loop. 3. The syntax is consistent with other jQuery code you may have, potentially increasing readability. The disadvantages are some, small overhead -- you have to pay for what it does for you -- and the potential for confusing it with the $().each() method which is completely different.
As the [jQuery `$.each(object, callback)` explanation](http://docs.jquery.com/Utilities/jQuery.each#objectcallback) states > A generic iterator function, which can > be used to seamlessly iterate over > both objects and arrays. In keeping in line with other utility functions, it provides an easy one line jQuery-fied syntax to use
advantage of $.each method over for..in loops?
[ "", "javascript", "jquery", "" ]
Do you think Microsoft's RAP program worth the money you pay ? Any suggestions ? Thanks
I would have to say that it depends on a number of factors. First how knowledgeable are you at configuring and maintaining the specific versions of SQL Server that they would be looking at? Then why are you doing the SQL RAP? Is it to really get a good risk assessment, to demonstrate to management that things are being done correctly, or to learn where you are coming up short in an effort to correct things and find areas to learn more about the product, or is it none of the above? I had a SQL RAP done at the end of last year, and I can tell you from personal experience, you will only get as much from it as you are open to learning. If you have a cluster, be prepared to have your eyes opened to areas you never thought to look at. The SQL RAP visit has four different phases, or at least mine did. First they collect the data from your SQL Servers using pssdiag and a bunch of other neat tools that they leave copies of most with you. Then they go into analysis, where they take the data and perform a very thorough analysis of it and generate reports and recommendations. Then they sit down with you and management if you so chose and go over everything, what was good, what was iffy, and what was bad. Then the last part they sit down with you as a DBA and teach you how to use the tools they used and that they can leave copies of with you. They go over the PAL Tool, SQL Nexus, and some others and make sure that you know how to use these tools to do self analysis. Best of all, they leave you these really detailed reports that you can use as a self check for setting up new environments in the future. Is it worth it? You probably can't tell that until you are done with it. For me, I'd recommend it to anyone who wants to know more about running a "Best Practice" implementation of SQL Server, and who'd like some one on one learning time with a Senior Microsoft Field Engineer.
Oh boy, is that all they does with this much hyped RAP. Pssdiag is already done. We did the PAL and Nexus and they too did it before. They took around 20 Gigs of size trace files to analyse. Now, wanted to do RAP. Holy cRAP, if this is the same thing to do again, what that's for. I expect much more than this level of analysis without which I think this is useless and waste of money.
Microsoft RAP (Risk Assessment Program)
[ "", "sql", "sql-server-2005", "" ]
Sometimes when I see my logging code I wonder if I am doing it right. There might be no definitive answer to that, but I have the following concerns: **Library Classes** I have several library classes which might log some `INFO` messages. Fatal Errors are reported as exceptions. Currently I have a static logger instance in my classes with the class name as the logging name. (Log4j's: `Logger.getLogger(MyClass.class)`) Is this the right way? Maybe the user of this library class doesn't want any messages from my implementation or wants to redirect them to an application specific log. Should I allow the user to set a logger from the "outside world"? How do you handle such cases? **General logs** In some applications my classes might want to write a log message to a specific log not identified by the class' name. (I.e.: `HTTP Request log`) What is the best way to do such a thing? A lookup service comes to mind...
Your conventions are pretty standard and quite fine (imho). The one thing to watch is memory fragmentation from excessive unnedded debug calls so, with Log4J (and most other Java logging frameworks), you end up with something like this: ``` if (log.isDebugEnabled()) { log.debug("..."); } ``` because constructing that log message (that you probably aren't using) could be expensive, especially if done thousands or millions of times. Your INFO level logging shouldn't be too "chatty" (and from what you say, it sounds like it isn't). INFO messages should be generally meaningful and significant, like the application being started and stopped. Things that you might want to know if you encounter a problem. Debug/fine level logging is more used for when you actually have a problem you're trying to diagnose. Debug/fine logging is typically only turned on when needed. Info is typically on all the time. If someone doesn't want specific INFO messages from your classes, they are of course free to change your log4j configuration to not get them. Log4j is beautifully straightforward in this department (as opposed to Java 1.4 logging). As for your HTTP thing, I've generally not found that to be an issue with Java logging because typically a single class is responsible for what you're interested in so you only need to put it in one place. In the (rare in my experience) when you want common log messages across seemingly unrelated classes, just put in some token that can easily be grepped for.
The following is the set of guidelines I follow in all my projects to ensure good performance. I have come to form this set of guidelines based on the inputs from various sources in the internet. As on today, I believe Log4j 2 is by far the best option for logging in Java. The benchmarks are available [here](https://logging.apache.org/log4j/2.x/performance.html). The practice that I follow to get the best performance is as follows: 1. I avoid using SLF4J at the moment for the following reasons: * It has some concurrency issues with Markers which I want to use to manage the logging of SQL statements ([Markers not as powerful as slf4j](https://issues.apache.org/jira/browse/LOG4J2-585) - Refer to the first comment by Ralph Goers) * It does not support the Java 8 Lambda which, again, I want to use for better performance ([Support the lambda expression in the Logger](https://jira.qos.ch/browse/SLF4J-371)) 2. Do all regular logging using asynchronous logger for better performance 3. Log error messages in a separate file using synchronous logger because we want to see the error messages as soon as it occurs 4. Do not use location information, such as filename, class name, method name, line number in regular logging because in order to derive those information, the framework takes a snapshot of the stack and walk through it. This impacts the performance. Hence use the location information only in the error log and not in the regular log 5. For the purpose of tracking individual requests handled by separate threads, consider using thread context and random UUID as explained [here](https://logging.apache.org/log4j/2.x/manual/thread-context.html) 6. Since we are logging errors in a separate file, it is very important that we log the context information also in the error log. For e.g. if the application encountered an error while processing a file, print the filename and the file record being processed in the error log file along with the stacktrace 7. Log file should be grep-able and easy to understand. For e.g. if an application processes customer records in multiple files, each log message should be like below: > ``` > 12:01:00,127 INFO FILE_NAME=file1.txt - Processing starts > 12:01:00,127 DEBUG FILE_NAME=file1.txt, CUSTOMER_ID=756 > 12:01:00,129 INFO FILE_NAME=file1.txt - Processing ends > ``` 8. Log all SQL statements using an SQL marker as shown below and use a filter to enable or disable it: > ``` > private static final Marker sqlMarker = > MarkerManager.getMarker("SQL"); > > private void method1() { > logger.debug(sqlMarker, "SELECT * FROM EMPLOYEE"); > } > ``` 9. Log all parameters using Java 8 Lambdas. This will save the application from formatting message when the given log level is disabled: > ``` > int i=5, j=10; > logger.info("Sample output {}, {}", ()->i, ()->j); > ``` 10. Do not use String concatenation. Use parameterized message as shown above 11. Use dynamic reloading of logging configuration so that the application automatically reloads the changes in the logging configuration without the need of application restart 12. Do not use `printStackTrace()` or `System.out.println()` 13. The application should shut down the logger before exiting: > ``` > LogManager.shutdown(); > ``` 14. Finally, for everybody’s reference, I use the following configuration: > ``` > <?xml version="1.0" encoding="UTF-8"?> > <Configuration monitorinterval="300" status="info" strict="true"> > <Properties> > <Property name="filePath">${env:LOG_ROOT}/SAMPLE</Property> > <Property name="filename">${env:LOG_ROOT}/SAMPLE/sample > </Property> > <property name="logSize">10 MB</property> > </Properties> > <Appenders> > <RollingFile name="RollingFileRegular" fileName="${filename}.log" > filePattern="${filePath}/sample-%d{yyyy-dd-MM}-%i.log"> > <Filters> > <MarkerFilter marker="SQL" onMatch="DENY" > onMismatch="NEUTRAL" /> > </Filters> > <PatternLayout> > <Pattern>%d{HH:mm:ss,SSS} %m%n > </Pattern> > </PatternLayout> > <Policies> > <TimeBasedTriggeringPolicy > interval="1" modulate="true" /> > <SizeBasedTriggeringPolicy > size="${logSize}" /> > > </Policies> > </RollingFile> > <RollingFile name="RollingFileError" > fileName="${filename}_error.log" > filePattern="${filePath}/sample_error-%d{yyyy-dd-MM}-%i.log" > immediateFlush="true"> > <PatternLayout> > <Pattern>%d{HH:mm:ss,SSS} %p %c{1.}[%L] [%t] %m%n > </Pattern> > </PatternLayout> > <Policies> > <TimeBasedTriggeringPolicy > interval="1" modulate="true" /> > <SizeBasedTriggeringPolicy > size="${logSize}" /> > </Policies> > </RollingFile> > </Appenders> > <Loggers> > <AsyncLogger name="com" > level="trace"> > <AppenderRef ref="RollingFileRegular"/> > </AsyncLogger> > <Root includeLocation="true" level="trace"> > <AppenderRef ref="RollingFileError" level="error" /> > </Root> > </Loggers> > </Configuration> > ``` 15. The required Maven dependencies are here: > ``` > <dependency> > <groupId>org.apache.logging.log4j</groupId> > <artifactId>log4j-api</artifactId> > <version>2.8.1</version> > </dependency> > <dependency> > <groupId>org.apache.logging.log4j</groupId> > <artifactId>log4j-core</artifactId> > <version>2.8.1</version> > </dependency> > <dependency> > <groupId>com.lmax</groupId> > <artifactId>disruptor</artifactId> > <version>3.3.6</version> > </dependency> > <!-- (Optional)To be used when working > with the applications using Log4j 1.x --> > <dependency> > <groupId>org.apache.logging.log4j</groupId> > <artifactId>log4j-1.2-api</artifactId> > <version>2.8.1</version> > </dependency> > ```
Logging in Java and in general: Best Practices?
[ "", "java", "logging", "log4j", "" ]
I encountered ConcurrentModificationException and by looking at it I can't see the reason why it's happening; the area throwing the exception and all the places modifying the collection are surrounded by ``` synchronized (this.locks.get(id)) { ... } // locks is a HashMap<String, Object>; ``` I tried to catch the the pesky thread but all I could nail (by setting a breakpoint in the exception) is that the throwing thread owns the monitor while the other thread (there are two threads in the program) sleeps. How should I proceed? What do you usually do when you encounter similar threading issues?
It may have nothing to do with the synchronization block. `ConcurrentModificationException`s often occur when you're modifying a collection while you are iterating over its elements. ``` List<String> messages = ...; for (String message : messages) { // Prone to ConcurrentModificationException messages.add("A COMPLETELY NEW MESSAGE"); } ```
Similar to a previous post, you can get the same issue if you delete an entry. e.g. ``` for(String message : messages) { if (condition(message)) messages.remove(message); } ``` Another common example is cleaning up a Map. This particular problem can be resolved using an Iterator explicitly. ``` for(Iterator<String> iter = messages.iterator(); iter.hasNext();) { String message = iter.next(); if (condition(message)) iter.remove(); // doesn't cause a ConcurrentModificationException } ```
How to debug ConcurrentModificationException?
[ "", "java", "multithreading", "exception", "concurrency", "" ]
I am fairly new to ASP.NET and I discovered repeaters recently. Some people use them, other don't and I'm not sure which solution would be the best practice. From what I've experienced, it makes simple operation (display a list) simple, but as soon as you want to do more complicated things the complexity explodes, logic wise. Maybe it's just me and me poor understanding of the concept (this is highly possible), so here's an example of what am I trying to do and my issue: --- **Problem**: I want to display a list of files located in a folder. **Solution**: ``` String fileDirectory = Server.MapPath("/public/uploaded_files/"); String[] files = Directory.GetFiles(fileDirectory); repFiles.DataSource = files; repFiles.DataBind(); ``` and ``` <asp:Repeater ID="repFiles" runat="server" OnItemCommand="repFiles_ItemCommand" > <ItemTemplate> <a href="/public/uploaded_files/<%# System.IO.Path.GetFileName((string)Container.DataItem) %>" target="_blank">View in a new window</a> <br /> </ItemTemplate> </asp:Repeater> ``` This works fine. --- **New problem**: I want to be able to delete those files. **Solution**: I add a delete link in the item template: ``` <asp:LinkButton ID="lbFileDelete" runat="server" Text="delete" CommandName="delete" /> ``` I catch the event: ``` protected void repFiles_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "delete") { // ... blah } } ``` ... then what? How do I get the file path that I want to remove from here knowing that e.Item.DataItem is null (I ran the debugger). Did I just wasted my time using repeaters when I could have done the same thing using an loop, which would have been just as simple, just -maybe- less elegant? What is the real advantage of using repeaters over other solutions?
You can definitely handle the LinkButton events as you are showing. You can add a CommandArgument to your LinkButton like this: ``` <asp:LinkButton CommandArgument="<%# (string)Container.DataItem %>" ID="lbFileDelete" runat="server" Text="delete" CommandName="delete" /> ``` Then in your code you can do this: ``` string path = e.CommandArgument.ToString(); ``` In general, I'm a fan of the Repeater control. It gives you the ability to make repeating things quickly, with limited code and a high level of control over the generated HTML. I prefer it over the GridView and other more complex controls because you have much more fine-tuned ability to generate the output exactly as you need. I prefer it over looping, because I believe you can develop faster, with fewer errors if you're not appending tons of HTML together in your code to make the generated HTML.
For displaying a list of things, Repeaters are typically faster than GridViews, DataLists, and their other counterparts. Repeaters are best suited for display, rather than adding and editing records, although you can manually wire up what is needed to use a Repeater for CRUD operations. In your example, you need to bind the file path to the CommandArgument property of your link button. Then you should have access to the path using e.CommandArgument in the event handler.
ASP.NET repeater issue (+ question about best practices)
[ "", "c#", "asp.net", "repeater", "" ]
Is there any way, to optimalize linking time in MS Visual studio C++ (2005) ? We're using Xoreax Incredibuild for compilation speed up, but nothing for link. Currently every linking takes about 30seconds. When I turn on incremental linking, takes abou 35-40 seconds. ( No matter if i compile project with or without incredibuild ) Is there any way, how to profile linker and watch how long what takes ? Or any tool for paralel linking ? Or any tips for code optimalization to speed up linker ? Thanks for reply Ludek Vodicka --- Edit: Thanks for first replies, and additional info: * Whole Program Optimization and link-time code generation is already off. * PIMPL idiom is already used when possible * other static libraries are already included via #pragma comment(lib, "pathToLib"). (also because of easier maintenance] * HW : quad core q6600, 8GB ram, 3x WD raptor raid 0. Windows Vista 64bit
I'm not aware of any parallel linking tools; I do know that Incredibuild does not allow it. The biggest tool in your toolbox for avoiding link times is the appropriate level of abstraction. If your link times are long, it may be because objects know too much about other objects. Decoupling them is then the key -- through abstract interfaces (perhaps using the PIMPL paradigm), or though other methods such as event passing. The overhead for linking projects through Project Dependencies is also quite high. If your target platform is Win32 only, or primarily, you may consider using a header to link your dependent libraries via #pragma comment(lib, "pathToLib").
If you can live without the optimization, turn off link-time code generation (remove the /GL switch or in properties c/c++ -> Optimization -> Whole Program Optimization. For the linker remove /ltcg or use the Link Time Code Generation Setting). This will make the compiler slower though, as code generation now happens during compile time. I've seen projects that take hours to build with /GL+/LTCG, mere seconds without (this one for example: <http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/750ed2b0-0d51-48a3-bd9a-e8f4b544ded8>)
How to speed up c++ linking time
[ "", "c++", "linker", "visual-c++", "" ]
Firebug is certainly a wonderful tool for javascript debugging; I use console.log() extensively. I wanted to know if I can leave the Firebug-specific code in production. What's the best practice? Commenting the debug code?
If you leave console.log() calls in your production code, then people visiting the site using Internet Explorer will have JavaScript errors. If those people have extra debugging tools configured, then they will see nasty dialog boxes or popups. A quick search revealed this thread discussing methods to detect if the Firebug console exists: <http://www.nabble.com/Re:-detect-firebug-existance-td19610337.html>
been bitten by this before. Ideally all the console.log statements need to be removed before production, but this is error prone and developers invariably forget or only test in FF + Firebug. A possible solution is to create a dummy console object if one isn't already defined. ``` if( typeof window.console == 'undefined'){ window.console = { log:function(){} }; } ``` One word of caution: It used to be the case for Safari on 10.4 that any call to console.log would throw a security exception as the console object is a reserved object used in the Mac OS Dashboard widgets. Not sure this is the case anymore, will check tonight.
Javascript best practice: handling Firebug-specific code
[ "", "javascript", "jquery", "firebug", "" ]
Somewhat related to [this question](https://stackoverflow.com/questions/877689/quickbooks-invoice-modify-has-different-address-behavior-than-create-how-to-comp), but in the absence of any answer about QuickBooks specifically, does anyone know of an address parser for Java? Something that can take unstructured address information and parse out the address line 1, 2 and city state postal code and country?
I do know that the Google Maps web service is **great** at doing this. So, if you want to use that, you could save a lot of effort. The real issue here is that you need a worldwide database of city/country/province names to effectively parse UNSTRUCTURED addresses. Here is how I build a URL for use by the Google Maps API in C#: ``` string url = "http://maps.google.com/maps/geo?key=" + HttpUtility.UrlEncode(this.apiKey) + "&sensor=false&output=xml&oe=utf8&q=" + HttpUtility.UrlEncode(location); ```
The SourceForge JGeocoder has an address parser that you may find useful. See <http://jgeocoder.sourceforge.net/parser.html>.
Java postal address parser
[ "", "java", "parsing", "street-address", "" ]
I am writing/learning to fetch email using java from an IMAP folder using javax.mail package. I was successfully able to retrieve the last n messages in a Folder, however I am looking to build an example to retrieve messages since a specified date. Any examples?
You could also use the SearchTerm classes in the java mail package. ``` SearchTerm olderThan = new ReceivedDateTerm(ComparisonTerm.LT, someFutureDate); SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, somePastDate); SearchTerm andTerm = new AndTerm(olderThan, newerThan); inbox.search(andTerm); ``` Some combination of the above should prove to be a better way to get dates within a certain range.
``` public class CheckDate { public void myCheckDate(Date givenDate) { SearchTerm st = new ReceivedDateTerm(ComparisonTerm.EQ,givenDate); Message[] messages = inbox.search(st); } // in main method public static void main(String[] args) throws ParseException{ SimpleDateFormat df1 = new SimpleDateFormat( "MM/dd/yy" ); String dt="06/23/10"; java.util.Date dDate = df1.parse(dt); cd.myCheckDate(dDate); } } ```
java imap fetch messages since a date
[ "", "java", "email", "imap", "" ]
I am trying to assign a custom type as a key for `std::map`. Here is the type which I am using as key: ``` struct Foo { Foo(std::string s) : foo_value(s){} bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; } bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; } std::string foo_value; }; ``` When used with `std::map`, I am getting the following error: ``` error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:\program files\microsoft visual studio 8\vc\include\functional 143 ``` If I change the `struct` to the one below, everything works: ``` struct Foo { Foo(std::string s) : foo_value(s) {} friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value; } friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value; } std::string foo_value; }; ``` Nothing changed, except that the operator is overloaded as *friend*. Why does my first code not work?
I suspect you need ``` bool operator<(const Foo& foo1) const; ``` Note the `const` after the arguments, this is to make "your" (the left-hand side in the comparison) object constant. The reason only a single operator is needed is that it is enough to implement the required ordering. To answer the abstract question "does a have to come before b?" it is enough to know whether a is less than b.
It's probably looking for const member operators (whatever the correct name is). This works (note const): ``` bool operator<(const Foo& foo1) const { return foo_value < foo1.foo_value;} ``` EDIT: deleted `operator>` from my answer as it was not needed (copy/paste from question) but it was attracting comments :) Note: I'm 100% sure that you need that **const** because I compiled the example.
How can I use a custom type as key for a map in C++?
[ "", "c++", "struct", "key", "operator-overloading", "stdmap", "" ]
I have done some research, and majority of the examples I have found use forms (obviously for user input) to collect data which is then passed to another JSP page through the request object. My question is: Is it possible to pass a parameter between JSP pages if the parameter hasn't been set in HTML `<form>` tags?
There's no way a JSP page can tell the difference between a manually constructed GET url, e.g.: `<a href="/foo.jsp?bar=baz">Go to the next JSP page</a>`, versus something like: ``` <form method="get" action="/foo.jsp"> <input name="bar" value="baz"> </form> ``` Either way it can be accessed through `getParameter` or `getParameterValues` Is that what you're asking?
There are a few ways to pass information from one JSP page to another. # 1. Hidden values. Simply write the data to an input field within a form with the type 'hidden', e.g. ``` <input type="hidden" name="mydata" value="<%=thedata%>"> ``` Data written thus will get posted back when the relevant form is submitted. This can be a useful way to 'carry along' information as the user fills out a series of dialogs as all state is user side and the back and forward buttons will work as expected. # 2. URL writing. Attach parameters to URLs in links on the page, e.g. ``` <a href="another.jsp?mydata=<%=thedata>>Go!</a> ``` This also maintains the state with the client while removing the need for a form element to be submitted. # 3. Cookies. Should speak for itself.The state is still user side but is now handled by a cookie. More fragile in some ways since some people disable cookies. Also the back and forward buttons may do unexpected things if you are not careful # 4. Server side (session) Finally you could store the data in a session variable on one JSP and retrieve it on the next, e.g. ``` session.setAttribute(String key, Object value) ``` and ``` session.getAttribute(String key) ``` Here the state is kept server side which has some benefits (the user can browse away and return without losing his place, but tends to make the back and forward buttons in the browser a bit unreliable unless you are careful. Also the value is available to all pages. It does however have the advantage that the information is never sent to the client and is thus more secure and more tamper proof.
Passing parameter without use of HTML forms in JSP
[ "", "java", "jsp", "" ]
``` $(document).ready(function() { function countChecked() { var n = $("input:checked").length; $("div").text(n + (n <= 1 ? " is" : " are") + " checked!"); } countChecked(); $(":checkbox").click(countChecked); }); ``` ``` div { color: red; } ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="checkbox" name="newsletter" checked="checked" value="Hourly" /> <input type="checkbox" name="newsletter" value="Daily" /> <input type="checkbox" name="newsletter" value="Weekly" /> <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> <input type="checkbox" name="newsletter" value="Yearly" /> </form> ``` I need to get the value of all the checked checkboxes like "Hourly", "Daily" how can I get all the value of the checked checkboxes can anybody help me, please
slight improvement on Pim Jager (guessing you want an array of the values returned): ``` function getCheckedNames(){ var arr = new Array(); var $checked = $('[@name=newsletter]:checked'); $checked.each(function(){ arr.push($(this).val()); }); return arr; } ``` and with the improvement from duckyflip: ``` function getCheckedNames(){ return jQuery('[@name=newsletter]:checked').map(function(){ return this.value; }); } ```
``` var values = $.makeArray($(":checkbox:checked").map(function(){ return this.value })).join(', ') alert(values) ```
need to get each checked checkboxes value which is in loop
[ "", "javascript", "jquery", "" ]
I think I saw someday a way to create a link without sending the page that the user was in originally. Is that possible? Or do we need to use a redirector to hide the location of the previous site? EDIT: If you have an idea for a server-side option to anonymise the link you're welcome.
Check out [this section on Wiki](http://en.wikipedia.org/wiki/HTTP_referrer#Referer_hiding) on referrer hiding. > Most major browsers do not send the referrer header when they are instructed to redirect using the "Refresh" HTTP header. However, this method of redirection is discouraged by the [W3C.](http://www.w3.org/TR/WCAG10-HTML-TECHS/#meta-element)
``` <a href="example.com" rel="noreferrer">Example</a> ``` <http://www.w3.org/TR/html5/links.html#link-type-noreferrer> The **noreferrer** keyword may be used with a and area elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one). *It indicates that no referrer information is to be leaked when following the link.* If a user agent follows a link defined by an a or area element that has the noreferrer keyword, the user agent must not include a Referer (sic) HTTP header (or equivalent for other protocols) in the request.
How to not send a referrer from a link in html
[ "", "php", "html", "" ]
I want to create a structure which contains a list of same structure like this: ``` #include <list> struct Url { CString strUrl; std::list<Url> children; }; int main() { Url u1, u2; u1.children.push_back(u2); } ``` This code is not compiling. But when I replace `std::list` with `std::vector` it is working fine. How can I make this working with `std::list`? Output window contains the following error. ``` c:\program files\microsoft visual studio\vc98\include\list(29) : error C2079: '_Value' uses undefined struct 'Url' E:\test\Test.cpp(23) : see reference to class template instantiation 'std::list<struct Url,class std::allocator<struct Url> >' being compiled c:\program files\microsoft visual studio\vc98\include\functional(185) : error C2079: 'value' uses undefined struct 'Url' c:\program files\microsoft visual studio\vc98\include\list(285) : see reference to class template instantiation 'std::binder2nd<struct std::not_equal_to<struct Url> >' being compiled E:\test\Test.cpp(23) : see reference to class template instantiation 'std::list<struct Url,class std::allocator<struct Url> >' being compiled ```
If you need a workround for what seems to be a VC6 bug, create the list dynamically: ``` #include <list> #include <string> // I don't use MFC struct Url { std::string strUrl; std::list<Url> * children; Url() { children = new std::list <Url>; } ~Url() { delete children; } }; int main() { Url u1, u2; u1.children->push_back(u2); } ``` Some have asked why lists of the same type as members are allowed (and in my view they are) when ``` Url array[5]; ``` for example as a member would not be. I can't find anything in the standard either, but `sizeof( std:;list <T>)` is not dependent on the thing it is a list of. Suppose list was implemented as (some pseudo C++ here): ``` list <T> { listEntry <T> * first; }; ``` then there is no unknown size to deal with. Consider the following minimal code that addresses the questioners problem: ``` template <typename T> struct A { }; struct B { A <B> b; }; ``` I can't see any possible reason that this should not be legal.
Can you tell us what compiler you are using? There is nothing inherently wrong with what you are doing. I tried the following on VS2008 SP1 and it compiled no problem ``` #include <list> struct Url { std::string name; std::list<Url> children; }; int _tmain(int argc, _TCHAR* argv[]) { Url u1,u2; u1.children.push_back(u2); return 0; } ``` Did you perhaps forget to include list? **EDIT** OP is using Visual Studio 6.0 and Neil was able to confirm that it is indeed a bug in VS6
How to create a structure which contains a list of itself?
[ "", "c++", "stl", "visual-c++-6", "" ]
I give up, how do I cast this? ``` class AmountIsTooHighConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //int amount = (int)value; //int amount = (int)(string)value; //int amount = (int)(value.ToString); //int amount = Int32.Parse(value); //int amount = (int)Convert.ChangeType(value, typeof(int)); //int amount = Convert.ToInt32(value); if (amount >= 35) { return true; } else { return false; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } } ```
Both `Convert.ToInt32` or `Int32.Parse` should work... If they don't, then the value is definitely not an int ;) Try to put a breakpoint in your converter to watch the value, it might show you why it doesn't work
If the value is actually a string object (with a content that represents an integer value), this gives the least overhead: ``` int amount = Int32.Parse((string)value); ``` The `Convert.ToInt32` should be able to handle most anything that is possible to convert to an `int`, like a string containing digits or any numeric type that is within the range that an `int` can handle.
How do I cast an object to an int in a Converter?
[ "", "c#", "wpf", "converters", "" ]
I know how to get the user that last modified a file, but does Windows track the process that made the modification as well? If so, is there an API for looking that up?
No. It is not recorded. You could enable Object Access Auditing on a particular folder (I wouldn't recommended using on the general file system). See this [post](http://blogs.msdn.com/ericfitz/archive/2006/03/07/545726.aspx) and use with caution! You might be able to use .NET's [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) class.
You could use procmon.exe from <https://live.sysinternals.com/procmon.exe> This is a live monitor, so not much use retrospectively. 1. Deselect (uncheck) the "File | Capture Events" menu item. 2. Clear the currently displayed events by selecting the "Edit | Clear Display" menu item. 3. Configure a filter by: a. Select the Process Monitor "Filter | Filter..." menu item. This will display the "Process Monitor Filter" dialog. b. Set a new filter by setting the "Display entries matching those conditions" fields: c. (pick)Path (pick)contains `whatever.txt` then (pick)Include d. Click the "Add" button to add the new filter. derived from instructions here: <http://answers.perforce.com/articles/KB/3035>
How do you determine the last process to modify a file?
[ "", "c#", ".net", "windows", "winapi", "" ]
We are considering to use Configuration Admin Service as a primary API for configuring components in our OSGi-based application. It would be nice if we could reuse some existing implementation so I'm trying to investigate and evaluate the most popular ones. I know there is: * [Apache Felix Config Admin](http://felix.apache.org/site/apache-felix-configuration-admin-service.html) (org.apache.felix.cm) * [Equinox Config Admin](http://www.eclipse.org/equinox/bundles/) (org.eclipse.equinox.cm) Are there any other implementations to be considered? Also I was not able to find any good documentation for these implementations. I would be mainly interested in the implementation-specific details. For example I was wondering how different implementations persist the configuration data (e.g. multiple property files? XML file? multiple XML files? database?, ...).
The three public implementations I know of are * [Apache Felix](http://felix.apache.org/site/apache-felix-configuration-admin-service.html) * Equinox […source](http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.equinox/compendium/bundles/org.eclipse.equinox.cm/src) (this has moved recently) * Knopflerfish […front page](http://www.knopflerfish.org/snapshots/2.3.2.snapshot_trunk_2751/docs/components.html#knopflerfish) and […source](https://www.knopflerfish.org/svn/knopflerfish.org/trunk/osgi/bundles/cm) Equinox's implementation of the `ConfigurationAdmin` service appears not to support fine control over the persistence policy, as Felix's does, and the Knopflerfish implementation looks (I've only read the source briefly) similar to Equinox's. The Felix one appears to be the most recently updated and the most reliable. At present these are the only ones I can find; at dm Server we made the decision to use Felix's bundle, and this is now obtainable from the [SpringSource Enterprise Bundle Repository](http://www.springsource.com/repository/app/), where you can quick-search for `Apache Felix` or `ConfigAdmin`.
Felix's Configuration Admin has a [default implementation](http://svn.apache.org/viewvc/felix/releases/org.apache.felix.configadmin-1.0.8/src/main/java/org/apache/felix/cm/file/FilePersistenceManager.java?revision=734642) that persists to the file system, but they define a service interface ([org.apache.felix.cm.PersistenceManager](http://svn.apache.org/viewvc/felix/releases/org.apache.felix.configadmin-1.0.8/src/main/java/org/apache/felix/cm/PersistenceManager.java?revision=734642&view=markup)) for alternative backends that you could plug in instead. The default implementation does the following: > The FilePersistenceManager class stores configuration data in > properties-like files inside a given directory. All configuration files are > located in the same directory. > > Configuration files are created in the configuration directory by appending > the extension ".config" to the PID of the configuration. The PID > is converted into a relative path name by replacing enclosed dots to slashes. > Non-symbolic-name characters in the PID are encoded with their > Unicode character code in hexadecimal.
Existing implementations of OSGi Configuration Admin Service?
[ "", "java", "configuration", "osgi", "" ]
There are already lots of questions on SO about exceptions, but I can't find one that answers my question. Feel free to point me in the direction of another question if I've missed it. My question is quite simple: how do other (C#) developers go about choosing the most appropriate type of exception to throw? Earlier I wrote the following code: ``` if (Enum.IsDefined(enumType, value)) { return (T)Enum.Parse(enumType, value); } else { throw new ArgumentException(string.Format("Parameter for value \"{0}\" is not defined in {1}", value, enumType)); } ``` I have since realised that throwing an `InvalidEnumArgumentException` would probably have been more appropriate had I known of its existence at the time. Is there an authoritative resource available that helps developers chose exception types, or is it simply a matter of experience? ## Edit I've given the points to Noldorin for providing a range of ideas in a well thought-out answer. The points could have gone to any one of you really - thanks for all the suggestions.
I would say it's just down to experience. There's still new exceptions I discover every so often, and I've been working with many aspects of .NET for a while now! What would you want this source to tell you, anyway? Choosing the appropriate exception type would seem highly context-specific, so I'm doubtful over the level of advice it could offer. Listing the more common ones would be most it could provide. The names and Intellisense descriptions of the exception types typically explain with good clarity their usage scenarios. My recommendation is simply to familiarize yourself with all of the fundamental ones (specifically, those in `System`, `System.IO`, and any other namespaces you often use), and learn the others along the way. I find that I generally get away using just a small number. If you accidentally use a more generic exception type when there already exists a more specific one in the BCL, then it's no great crime, and can be changed later easily enough. To be honest, for any error that's particularly specific, you will often need to create your own class inheriting from `Exception` anyway. Hope that helps. **Edit:** If you want a brief guide to the very common ones, see the [Common Exception Classes](http://msdn.microsoft.com/en-us/library/aa664610.aspx) page on MSDN.
Krzysztof Cwalina has a good post on this [see chapter "1.1.1 Choosing the Right Type of Exception to Throw"](https://learn.microsoft.com/en-us/archive/blogs/kcwalina/choosing-the-right-type-of-exception-to-throw) PS: Consider subscribing to his blog. Good reading! To answer your question: **[InvalidEnumArgumentException](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.invalidenumargumentexception)** because throw the most specific (the most derived) exception that makes sense. AND callers that catch `ArgumentException`, catch `InvalidEnumArgumentException` too...
How do I chose the most appropriate type of exception to throw?
[ "", "c#", "exception", "" ]
I need to perform a query like this: ``` SELECT *, (SELECT Table1.Column FROM Table1 INNER JOIN Table2 ON Table1.Table2Id = Table2.Id ) as tmp FROM Table2 WHERE tmp = 1 ``` I know I can take a workaround but I would like to know if this syntax is possible as it is (I think) in Mysql.
You've already got a variety of answers, some of them more useful than others. But to answer your question directly: No, SQL Server will not allow you to reference the column alias (defined in the select list) in the predicate (the WHERE clause). I think that is sufficient to answer the question you asked. **Additional details:** (this discussion goes beyond the original question you asked.) As you noted, there are several workarounds available. Most problematic with the query you posted (as others have already pointed out) is that we aren't guaranteed that the subquery in the SELECT list returns only one row. If it does return more than one row, SQL Server will throw a "too many rows" exception: ``` Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, , >= or when the subquery is used as an expression. ``` For the following discussion, I'm going to assume that issue is already sufficiently addressed. Sometimes, the easiest way to make the alias available in the predicate is to use an inline view. ``` SELECT v.* FROM ( SELECT * , (SELECT Table1.Column FROM Table1 JOIN Table2 ON Table1.Table2Id = Table2.Id WHERE Table1.Column = 1 ) as tmp FROM Table2 ) v WHERE v.tmp = 1 ``` Note that SQL Server won't push the predicate for the outer query (`WHERE v.tmp = 1`) into the subquery in the inline view. So you need to push that in yourself, by including the `WHERE Table1.Column = 1` predicate in the subquery, particularly if you're depending on that to make the subquery return only one value. That's just one approach to working around the problem, there are others. I suspect that query plan for this SQL Server query is not going to be optimal, for performance, you probably want to go with a JOIN or an EXISTS predicate. NOTE: I'm not an expert on using MySQL. I'm not all that familiar with MySQL support for subqueries. I do know (from painful experience) that subqueries weren't supported in MySQL 3.23, which made migrating an application from Oracle 8 to MySQL 3.23 particularly painful. Oh and btw... of no interest to anyone in particular, the Teradata DBMS engine *DOES* have an extension that allows for the NAMED keyword in place of the AS keyword, and a NAMED expression *CAN* be referenced elsewhere in the QUERY, including the WHERE clause, the GROUP BY clause and the ORDER BY clause. *Shuh-weeeet*
The query you posted won't work on sql server, because the sub query in your select clause could possibly return more than one row. I don't know how MySQL will treat it, but from what I'm reading MySQL will also yield an error if the sub query returns any duplicates. I do know that SQL Server won't even compile it. The difference is that MySQL will at least attempt to run the query and if you're very lucky (Table2Id is unique in Table1) it will succeed. More probably is will return an error. SQL Server won't try to run it at all. Here is a query that should run on either system, and won't cause an error if Table2Id is not unique in Table1. It *will* return "duplicate" rows in that case, where the only difference is the source of the Table1.Column value: ``` SELECT Table2.*, Table1.Column AS tmp FROM Table1 INNER JOIN Table2 ON Table1.Table2Id = Table2.Id WHERE Table1.Column = 1 ``` Perhaps if you shared what you were trying to accomplish we could help you write a query that does it.
Sql Server query syntax
[ "", "sql", "mysql", "sql-server-2005", "" ]
How can I loop through all members in a JavaScript object, including values that are objects? For example, how could I loop through this (accessing the "your\_name" and "your\_message" for each)? ``` var validation_messages = { "key_1": { "your_name": "jimmy", "your_msg": "hello world" }, "key_2": { "your_name": "billy", "your_msg": "foo equals bar" } } ```
``` for (var key in validation_messages) { // skip loop if the property is from prototype if (!validation_messages.hasOwnProperty(key)) continue; var obj = validation_messages[key]; for (var prop in obj) { // skip loop if the property is from prototype if (!obj.hasOwnProperty(prop)) continue; // your code alert(prop + " = " + obj[prop]); } } ```
Under ECMAScript 5, you can combine `Object.keys()` and `Array.prototype.forEach()`: ``` var obj = { first: "John", last: "Doe" }; // // Visit non-inherited enumerable keys // Object.keys(obj).forEach(function(key) { console.log(key, obj[key]); }); ```
How to loop through a plain JavaScript object with the objects as members
[ "", "javascript", "loops", "" ]
Is there a way to programmatically log into Yahoo!, providing email id and password as inputs, and fetch the user's contacts? I've achieved the same thing with Gmail, thanks to the its ClientLogin interface. Yahoo Address book API provides BBAuth, which requires the user to be redirected to Yahoo login page. But I'm looking for a way to authenticate the user with Yahoo without the redirection. The way Ning.com handles it. Code samples in Python will be much appreciated. Thanks.
I just found a python script that solves my problem <http://pypi.python.org/pypi/ContactGrabber/0.1> It's not complete though, fetches only a portion of the address book.
You may want to look into the [Contacts API](http://developer.yahoo.com/social/rest_api_guide/contact_api.html) provided by Yahoo!
Programmatically fetching contacts from Yahoo! Address Book
[ "", "python", "yahoo", "" ]
I'm curious about what be the best way to model this for optimized performance... not as concerned about real time data integrity I'll continue with the stackoverflow example ``` Question id title Votes id user question ``` A question has many votes For many queries however, we're only concerned with the aggregate number of votes (e.g. to show next to the question). Good relational db theory would create the two entities (Q and V) as separate relations, requiring a join then a sum or count aggregate call. Another possibility is to break normal form and occasionally materialize the aggregate value of votes as an attribute in Question (e.g. Question.votes). Performance is gained on reads, however, depending on how stale you are willing to let your "votes" data get, it requires a lot more rights to that Question record... in turn hindering performance. Other techniques involving caching, etc. can be used. But I'm just wondering, performance wise what's the best solution? Let's say the site is higher traffic and receiving a considerable more amount of votes than questions. Open to non-relational models as well.
It's unlikely that a join will be too slow in this case, especially if you have an index on (question) in the Votes table. If it is REALLY too slow, you can cache the vote count in the Question table: ``` id - title - votecount ``` You can update the votecount whenever you record a vote. For example, from a stored procedure or directly from your application code. Those updates are tricky, but since you're not that worried about consistency, I guess it's ok if the vote is sometimes not exactly right. To fix any errors, you can periodically regenerate all cached counts like: ``` UPDATE q SET votecount = count(v.question) FROM questions q LEFT JOIN votes v on v.question = q.id ``` The aggregate count(v.question) returns 0 if no question was found, as opposed to count(\*), which would return 1. If locks are an issue, consider using "with (nolock)" or "set transaction isolation level read uncommited" to bypass locks (again, based on data integrity being a low priority.) As an alternative to nolock, consider "read committed snapshot", which is meant for databases with heavy read and less write activity. You can turn it on with: ``` ALTER DATABASE YourDb SET READ_COMMITTED_SNAPSHOT ON; ``` It is available for SQL Server 2005 and higher. This is how Oracle works by default, and it's what stackoverflow itself uses. There's even a [coding horror blog entry](http://www.codinghorror.com/blog/archives/001166.html) about it.
I used indexed views from sql 2005 all over the place for this kind of thing on a social networking site. Our load was definitely a high ratio of reads/writes so it worked well for us.
Effecient way to model aggregate data of a many-to-one relationship (e.g. votes count on a stackoverflow question)
[ "", "sql", "database", "database-design", "aggregate", "relational", "" ]
I have a problem with IE. I have a layer that has this style to make it transparent and fullscreen. ``` position:absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; background-color: #000000; filter:alpha(opacity=50); -moz-opacity: 0.5; opacity: 0.5; z-index: 1; ``` And i use the JQuery method fadeIn and fadeOut to show and hide it. Well all well in Opera locks great but IE7 Just overides the style and sets it to 100% opacity. it dosent even fade!!
Peter-Paul Koch has a [fantastic article on opacity](http://www.quirksmode.org/css/opacity.html). In general, quirksmode.org is the first place I go to solve browser-compatibility issues; PPK's done a great deal of research. That said, you look like you have all the right styles in place - is jquery's fadein implementation not doing the right thing, even when you give it a target opacity? Could you solve the problem by setting the declared CSS to fully-opaque but visible:false, and then use [fadeto](http://docs.jquery.com/Effects/fadeTo) to get to the target opacity?
please use like : ``` .abc{ opacity: 0.5; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; // first! for ie8 filter: alpha(opacity=50); // second! for other ie versions } ```
JQuery IE <div> opacity problem
[ "", "javascript", "jquery", "html", "internet-explorer", "" ]
I am currently messing around with some stuff for an idea for a site - where I pretty much want to enable my users to create "Tables" which holds data and then allow them to query over this data (in a less geeky way than writing up SQL Queries and hopefully easier than using excel). My idea, so far, is to represent this in my database using a couple of tables - have one table representing a table, one table representing columns for the table, having one table that represents each row in a table and finally one that represents values. Something akin to (PSEUDO SQL): ``` CREATE TABLE 'Tables' ( Id INT NOT NULL PRIMARY KEY, NAME VARCHAR(255) ) CREATE TABLE 'TableColumns' ( Id INT NOT NULL PRIMARY KEY, TableId INT NOT NULL FOREIGN KEY ON 'Tables', NAME VARCHAR(255) ) CREATE TABLE 'TableRows' ( Id INT NOT NULL PRIMARY KEY, TableId INT NOT NULL FOREIGN KEY ON 'Tables', RowNumber INT NOT NULL ) CREATE TABLE 'TableValues' ( RowId INT NOT NULL PRIMARY KEY, ColumnId INT NOT NULL PRIMARY KEY, Value VARCHAR(255) ) ``` (note that the TableValues table has 2 primary key fields here, it's supposed to represent a "composite" primary key, don't bother too much with the fact that my syntax is not legal SQL, it's just supposed to show the idea). I did a bit of testing with this and was able to successfully do simple querying (simple filtering, ordering and so forth). My way of doing this was to first query the TableRows table - for filtering I then filtered out the rows who's columns did not match the criteria, and for sorting i sorted the RowIds based on their column's content (as specified by the sorting specified). Resulting in a list of Row Ids in the desired order, from here on it was merely just to select what was needed. All this works fine, but I am a bit stuck from here on. I'd like to somehow be able to represent different data types (which is my main issue really) and also later on work out how to do joins. While thinking all this through I start to wonder if there's a better way of doing this. Note that performance here, of course, is a factor, but I'm not planning on supporting virtual tables with hundreds of thousands of rows, maybe about 1000 rows per virtual table - of course the entire system needs to be capable of handling many of these. I know I could always just actually create tables in my database with queries created on the fly in C# to accomplish this, and likewise query using just SQL Queries - however I have never been a huge fan of letting users "construct" queries against my database like this - and it seems to me as if that would lead down a path where many bugs would appear - and in worst case scenario end up allowing the user to kill the database in one way or another. Also, then my issue becomes how I can deal with this in a way that would make sense from a C# perspective. So far I think I am leaning on using LINQ and then create my own extension methods which would apply the needed functionality - that is ExtensionMethods extending IQueryable. So what I'd really like would be some ideas of how this could be done, ideas of how to tune performance, ideas of how to deal with separate data types in the table (of course store the type in the tablecolumn, but how to actually store the value so I can filter, sort and so forth by it? - without just adding a "TextValue", "MoneyValue" and so forth column on my tablevalues table). And last but not least, hopefully some good discussions here - I at the very least consider this to be somewhat an interesting topic.
For some reason, everybody encounters that idea at some point or another. It seems right, it should work. It would. Sort of. The comments about TheDailyWTF have a point. Re-implementing a DBMS on top of a DBMS is really not a good idea. Going meta like that is going to give you * an underperfoming system * a maintenance nightmare If you really need that kind of flexibility (do you ?), you time would be much better spent implementing the layer that allows you to store metadata in some tables and generate the schema for the actual tables in the database. There are a few examples of this kind of system that I know of: * [Microsoft OSLO](http://msdn.microsoft.com/en-us/oslo/default.aspx) (specifically the Repository system) * the [ASAM-ODS](http://www.asam.net/index.php?option=com_content&task=view&id=117&Itemid=207) server architecture (look for the ASAM-ODS package) And I am sure there are others. The up-side of that kind of design is that your database actually makes sense in the end, and it uses the RDBMS for its strength. Also since that kind of configuration should not happen all the time once a table has been created, it allows the user to fine-tune the database if needed (in terms of indexing mainly). I really strongly feel the only correct answer to the kind of system you propose is **don't**.
It's an interesting idea, but using SQL in this way is probably going to be very painful over time. If I get you correctly, you want users to be able to define data structures and then save data to those structures. You also want to be able query it. I think there are maybe a couple of other ways to go about this; * What about using XML? Allow each user to store an XML file per "table" and just maintain it's schema. Each "row" would be an XML element with child elements. You could optionally stick the XML in SQL or just store it by some other means. This wouldn't work very well with large datasets, but for thousands of records it is surprisingly fast; I did some tests with 20+MB XML files in C# and was able to create them, read them and parse them in less than 1 second. Using LINQ to XML you could even construct fairly sophisticated queries and joins. I wouldn't use XML for a large enterprise system but you'd be surprised how far it will go on modern machines with lots of memory and fast processors - and it is infinitely flexible. * Could you use an object-oriented database (Matisse etc) instead? I haven't got experience of these myself, but I think you can quite easily do something like the XML approach but with better performance. * Amazon Simple DB: If I remember correctly this is essentially a name/value pair-based database which you can use. Could your application use that in the background instead to avoid you having to deal with all the plumbing? If you had to pay for SQL Server then Amazon DB might be cheaper and has the muscle to scale large, but without some of the things like relational queries.
"Dynamic" tables in SQL?
[ "", "c#", ".net", "t-sql", "database-design", "entity-attribute-value", "" ]
One of the most powerful things of jQuery is to select any item on a page like this: ``` $(".block").css("border","3px solid red"); ``` How can I also get the values of the selected items like width height and top left offset?
Use [`width`](http://docs.jquery.com/CSS/width), [`height`](http://docs.jquery.com/CSS/height) and [`position`](http://docs.jquery.com/CSS/position) or [`offset`](http://docs.jquery.com/CSS/offset): ``` var elem = $(".block"); var elemWidth = elem.width(); var elemHeight = elem.height(); var elemPosition = elem.position(); var elemOffset = elem.offset(); ``` For further questions, first take a look into the [jQuery documentation](http://docs.jquery.com/).
``` var height = $(".block").css("height"); alert(height); ```
How can we return the css attributes of an element with jQuery?
[ "", "javascript", "jquery", "" ]
I'm dealing with financial data, so there's a lot of it and it needs to be relatively high-precision (64bit floating point or wider). The standard practice around my workplace seems to be to represent all of it as the c# decimal type which is a 128bit wide floating point specifically created to support round-off free base10 operations. Since 64bit is wide enough to maintain the representative precision, is it ridiculous to cast the data to the wider type for all calculations (mult,div,add,etc) and then back to 64bit for sitting in memory (which is where it spends of most if its time)? For reference: memory is definitely the limiting resource here.
The point of using decimal (128 bits) over double (64 bits) and float (32 bits) isn't usually to do with the size. It's to do with the base. While double and float are floating *binary* point types, decimal is a floating *decimal* point type - and it's that feature that lets it represent numbers like 0.1 exactly where float/double can't. There's no conceptual reason why we couldn't haven't a 64-bit decimal type, and in many cases that would indeed be enough - but until such a type comes along or you write it yourself, *please* don't use the "shorter" (and binary floating point) types of float/double for financial calculations. If you do, you're asking for trouble. If you're suggesting writing a storage type which can convert to/from decimal and is still a floating decimal type, that sounds like a potentially good idea even without it being able to do any calculations. You'll need to be very careful when you think about what to do if you're ever asked to convert a decimal value which you can't represent exactly though. I'd be interested in seeing such a type, to be honest. Hmm... (As other answers have indicated, I'd really make sure that it's the numbers which are taking up the memory before doing this, however. If you don't *need* to do it, there's little point in introducing the extra complexity speculatively.)
64bit floating point cannot maintain precision of financial data. It is not a matter of space, it is a matter of which number system the data types use; double uses base-2, decimal is base-10, and base-2 cannot represent exact base-10 decimals even if it had 1000 bits of precision. Don't believe me? Run this: ``` double d = 0.0; for (int i = 0; i < 100; i++) d += 0.1; Console.WriteLine(d); > 9.99999999999998 ``` If you need base-10 calculations you need the decimal type. (Edit: damn, beaten by Jon Skeet again...) If the decimal type really is the bottleneck, you can use a long number of pennies (or 1/8 cent or whatever your unit is) instead of decimal dollars.
Is casting narrow types to wider types to save memory and keep high-precision calculations a terrible idea?
[ "", "c#", "performance", "memory", "casting", "decimal", "" ]
I was trying the next code without success HTML ``` <a id="addBookButton" href="javascript:showForm('addBookButton','add-book','activateAddBookForm');" class="addA"><span>Add Book</span></a> Javascript function showForm(button,form,callback) { $("#"+button).hide(); $("#"+form).show(); callback(); } ```
You can just pass a reference to the function into your showForm function. ``` <a id="addBookButton" href="javascript:showForm('addBookButton','add-book',activateAddBookForm);" class="addA"><span>Add Book</span></a> ```
Try this: ``` function showForm(button,form,callback) { $("#"+button).hide(); $("#"+form).show(); if (typeof this[callback] == "function") this[callback](); } ``` Of you pass the function by value and not just the name of it: ``` <a id="addBookButton" href="javascript:showForm('addBookButton','add-book',activateAddBookForm);" class="addA"><span>Add Book</span></a> ```
Call a function in JavaScript by its name?
[ "", "javascript", "jquery", "" ]
I'm retrieving a float value from a mysql database on a php page (2.5, 3.0 etc) I would like to format this value so that if it is actually an integer, it should show zero decimal places. (it should output 3 instead of 3.0, but output 2.5 as 2.5) What would be the simplest way to achieve this?
I would try something along the lines of: ``` echo (intval($v) == $v) ? intval($v) : $v; ``` But I wonder if there's a more efficient way.
You could also do the formatting in your query, it is likely to be faster than doing it in php especially if you have many rows to process. Something like: ``` SELECT CASE WHEN t.myColumn % 1 = 0 THEN FORMAT( t.myColumn, 0 ) ELSE FORMAT( t.myColumn, 2 ) END AS `formatted` ... FROM myTable t WHERE ... ``` The same method does apply for php if you want to do it outside the database: ``` $displayValue = $myValue % 1 == 0 ? number_format( $myValue, 0 ) : number_format( $myValue, 2 ); ```
Conditional formatting of a float in PHP
[ "", "php", "" ]
Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML) All my check boxes have the same name... ``` <form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2"> <input type=checkbox name="us" value="Joe" ID="Checkbox1"> <input type=checkbox name="us" value="Dan" ID="Checkbox2"> <input type=checkbox name="us" value="Sal" ID="Checkbox3"> </form> ```
You have to loop through them. Even a library like jQuery will loop through them, just hide it from you. ``` var form = document.getElementById('Form2'); var inputs = form.getElementsByTagName('input'); var is_checked = false; for(var x = 0; x < inputs.length; x++) { if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') { is_checked = inputs[x].checked; if(is_checked) break; } } // is_checked will be boolean 'true' if any are checked at this point. ```
jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this: ``` function AreAnyCheckboxesChecked () { var checkboxes = document.forms.Form2.elements.us; for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) { return true; } } return false; } ```
Fast way to validate if all checkboxes are un-selected?
[ "", "javascript", "html", "validation", "forms", "input", "" ]
I've been looking for a good Excel file generation class and have yet to find one - my number one issue is that I although I can get the exported file to open in Excel (running 2007), I always get a warning saying "the file is in a different format to the file extension". I noticed that the Excel export in phpMyAdmin even generates the aforementioned warning message. What code do other users use for this common requirement? **Quick update** If I set the file extension of my generated Excel file as xml it opens in the browser (even though I'm sending the correct headers), but if I choose to save the xml file and then open it from Excel, it works without any warnings! Unfortunately, that's more hassle for the users than simply clicking 'Proceed anyway' with the warning I'm getting. Any more ideas?
I've discovered that adding the following, under the xml declaration in my generated Excel file, ensures Excel opens the file with an xml file extension (rather than the web browser): ``` <?mso-application progid=\"Excel.Sheet\"?> ``` I'm also setting the following headers in php: ``` // deliver header (as recommended in php manual) header('Content-Type: application/vnd.ms-excel; charset=UTF-8'); header('Content-Disposition: attachment; filename="' . $filename . '.xml"'); ```
<http://www.phpexcel.net>
PHP Microsoft Excel file generation / export class
[ "", "php", "mysql", "excel", "class", "export", "" ]
How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case. I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call `System.setProperty( "user.dir", "/path/to/dir" )`, but as far as I can figure out, calling that line just silently fails and does nothing. I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to *get* the current working directory, and even allows you to open files using relative file paths....
There is no reliable way to do this in pure Java. Setting the `user.dir` property via `System.setProperty()` or `java -Duser.dir=...` does seem to affect subsequent creations of `Files`, but not e.g. `FileOutputStreams`. The [`File(String parent, String child)`](https://docs.oracle.com/javase/8/docs/api/java/io/File.html#File-java.lang.String-java.lang.String-) constructor can help if you build up your directory path separately from your file path, allowing easier swapping. An alternative is to set up a script to run Java from a different directory, or use JNI native code [as suggested below](/questions/840190#8204584). [The relevant OpenJDK bug](https://bugs.openjdk.java.net/browse/JDK-4045688) was closed in 2008 as "will not fix".
If you run your legacy program with [ProcessBuilder](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html "ProcessBuilder"), you will be able to specify its working [directory](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html#directory).
Changing the current working directory in Java?
[ "", "java", "working-directory", "" ]
Let's say we've got a metaclass `CallableWrappingMeta` which walks the body of a new class, wrapping its methods with a class, `InstanceMethodWrapper`: ``` import types class CallableWrappingMeta(type): def __new__(mcls, name, bases, cls_dict): for k, v in cls_dict.iteritems(): if isinstance(v, types.FunctionType): cls_dict[k] = InstanceMethodWrapper(v) return type.__new__(mcls, name, bases, cls_dict) class InstanceMethodWrapper(object): def __init__(self, method): self.method = method def __call__(self, *args, **kw): print "InstanceMethodWrapper.__call__( %s, *%r, **%r )" % (self, args, kw) return self.method(*args, **kw) class Bar(object): __metaclass__ = CallableWrappingMeta def __init__(self): print 'bar!' ``` Our dummy wrapper just prints the arguments as they come in. But you'll notice something conspicuous: the method isn't passed the instance-object receiver, because even though `InstanceMethodWrapper` is callable, it is not treated as a function for the purpose of being converted to an instance method during class creation (after our metaclass is done with it). A potential solution is to use a decorator instead of a class to wrap the methods -- that function will become an instance method. But in the real world, `InstanceMethodWrapper` is much more complex: it provides an API and publishes method-call events. A class is more convenient (and more performant, not that this matters much). I also tried some dead-ends. Subclassing `types.MethodType` and `types.UnboundMethodType` didn't go anywhere. A little introspection, and it appears they decend from `type`. So I tried using both as a metaclass, but no luck there either. It might be the case that they have special demands as a metaclass, but it seems we're in undocumented territory at this point. Any ideas?
Just enrich you `InstanceMethodWrapper` class with a `__get__` (which can perfectly well just `return self`) -- that is, make that class into a *descriptor* type, so that its instances are descriptor objects. See <http://users.rcn.com/python/download/Descriptor.htm> for background and details. BTW, if you're on Python 2.6 or better, consider using a class-decorator instead of that metaclass -- we added class decorators exactly because so many metaclasses were being used just for such decoration purposes, and decorators are really much simpler to use.
**Edit**: I lie yet again. The `__?attr__` attributes on functions are readonly, but apparently do not always throw an `AttributeException` exception when you assign? I dunno. Back to square one! **Edit**: This doesn't actually solve the problem, as the wrapping function won't proxy attribute requests to the `InstanceMethodWrapper`. I could, of course, duck-punch the `__?attr__` attributes in the decorator--and it is what I'm doing now--but that's ugly. Better ideas are very welcome. --- Of course, I immediately realized that combining a simple decorator with our classes will do the trick: ``` def methodize(method, callable): "Circumvents the fact that callables are not converted to instance methods." @wraps(method) def wrapper(*args, **kw): return wrapper._callable(*args, **kw) wrapper._callable = callable return wrapper ``` Then you add the decorator to the call to `InstanceMethodWrapper` in the metaclass: ``` cls_dict[k] = methodize(v, InstanceMethodWrapper(v)) ``` Poof. A little oblique, but it works.
callable as instancemethod?
[ "", "python", "methods", "metaclass", "python-descriptors", "" ]
I don't know why this is happening, but when I create a new form inside an EventHandler, it disappears as soon as the method is finished. Here's my code. I've edited it for clarity, but logically, it is exactly the same. ``` static void Main() { myEventHandler = new EventHandler(launchForm); // Code that creates a thread which calls // someThreadedFunction() when finished. } private void someThreadedFunction() { //Do stuff //Launch eventhandler EventHandler handler = myEventHandler; if (handler != null) { handler(null, null); myEventHandler = null; } } private void launchForm(object sender, EventArgs e) { mf = new myForm(); mf.Show(); MessageBox.Show("Do you see the form?"); } private myForm mf; private EventHandler myEventHandler; ``` The new form displays as long as the MessageBox "Do you see the form?" is there. As soon as I click OK on it, the form disappears. What am I missing? I thought that by assigning the new form to a class variable, it would stay alive after the method finished. Apparently, this is not the case.
I believe the problem is that you are executing the code within the handler from your custom thread, and *not* the UI thread, which is required because it operates the Windows message pump. You want to use the `Invoke` method here to insure that the form gets and shown on the UI thread. ``` private void launchForm(object sender, EventArgs e) { formThatAlreadyExists.Invoke(new MethodInvoker(() => { mf = new myForm(); mf.Show(); MessageBox.Show("Do you see the form?"); })); } ``` Note that this assumes you already have a WinForms object (called `formThatAlreadyExists`) that you have run using `Application.Run`. Also, there may be a better place to put the `Invoke` call in your code, but this is at least an example of it can be used.
I think if you create a form on a thread, the form is owned by that thread. When creating any UI elements, it should always be done on the main (UI) thread.
C# Windows Form created by EventHandler disappears immediately
[ "", "c#", "winforms", "multithreading", ".net-2.0", "event-handling", "" ]
What is the reason that in Java, a member with a "protected" modifier can not only be accessed by the same class and by subclasses, but also by everyone in the same package? I am wondering about language design reasons, not actual applications (e.g., testing)
This design is based on the idea that the package is the appropriate unit, maintained and released by one internally consistent team; inheritance relationships have much less to do with who's maintaining and releasing what when.
The modifiers are well-described in [The Java Tutorials](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html). From there, we see this table: | Modifier | Class | Package | Subclass | World | | --- | --- | --- | --- | --- | | `public` | Y | Y | Y | Y | | `protected` | Y | Y | Y | N | | *no modifier* | Y | Y | N | N | | `private` | Y | N | N | N | From this, the reason for the design decision is obvious: it's to have a nice symmetric matrix.
Why does the "protected" modifier in Java allow access to other classes in same package?
[ "", "java", "inheritance", "protected", "" ]
I need an inherited static function "call" to call another static function "inner" that has been overridden. I could do this with late static binding, but my host does not have php5.3 yet and so I need to work around it. ``` class ClassA{ static function call() { return self::inner(); } static function inner(){ return "Class A"; } } class ClassB extends ClassA{ static function inner(){ return "Class B"; } } echo "<p>Class A = " . ClassA::call(); echo "<p>Class B = " . ClassB::call(); ``` I would like the output to be: Class A = Class A Class B = Class B But what it is: Class A = Class A Class B = Class A My gut tells me that I should be able to write something in call() to detect what object was referenced when "call()" was, well, called. So instead of self::inner() it would so something along the lines of calledclass::inner(). Detecting the proper version of inner() to call from the original method call.
You can use object instances rather than classes. If you want a global symbol, you can use a global variable. Since they are rather unwieldy in PHP, one trick is to wrap it in a function. Eg.: ``` class ClassA { function call() { return $this->inner(); } function inner() { return "Class A"; } } function ClassA() { static $instance; return $instance ? $instance : new ClassA(); } class ClassB extends ClassA { function inner() { return "Class B"; } } function ClassB() { static $instance; return $instance ? $instance : new ClassB(); } echo "<p>Class A = " . ClassA()->call(); echo "<p>Class B = " . ClassB()->call(); ``` But a better idea might be to avoid global symbols altogether; The reason why it works well in Ruby/Rails, is that Ruby doesn't really have static state in the same way that PHP has. A class can be rebound and added to at runtime, which allows for easy extension of the framework. In PHP, classes are always final, so referring to them in application code, is a very strong degree of coupling.
If performance is not an issue, you can use debug\_backtrace() to find the called class: ``` $bt = debug_backtrace(); return get_class($bt[1]['object']); ``` <http://php.net/manual/en/function.debug-backtrace.php>
Faking Late Static Binding before php 5.3
[ "", "php", "oop", "static", "" ]
What is the correct C++ way of comparing a memory buffer with a constant string - `strcmp(buf, "sometext")` ? I want to avoid unnecessary memory copying as the result of creating temporary std::string objects. Thanks.
If you're just checking for equality, you may be able to use [`std::equal`](http://en.cppreference.com/w/cpp/algorithm/equal) ``` #include <algorithms> const char* text = "sometext"; const int len = 8; // length of text if (std::equal(text, text+len, buf)) ... ``` of course this will need additional logic if your buffer can be smaller than the text
strcmp is good if you know the contents of your buffer. [`std::strncmp`](http://en.cppreference.com/w/cpp/string/byte/strncmp) might give you a little more security against buffer overflows.
compare buffer with const char* in C++
[ "", "c++", "string", "comparison", "" ]
When you try to access a key which isn't in a Dictionary (for example), here's the stack trace you get : ``` at System.ThrowHelper.ThrowKeyNotFoundException() at System.Collections.Generic.Dictionary`2.get_Item(TKey key) .... .... (my own code stack trace) ``` Like most people probably do, I log this errors when they occur, and try to figure out what happened. The two key informations I want are where did this occur (the stacktrace is very helpful for that), and the key which caused the exception, which doesn't appear anywhere. Either I didn't look properly (the KeyNotFoundException class contains a "Data" member, which is always empty, and the "Message" field" doesn't contain the key value), or it wasn't included in the framework at all. I can't imagine nobody in the .net BCL team thought this would be an useful feature to have. I'm curious to know why they didn't include it. Are there some good reasons not to? How do you deal with those exceptions ? The only alternative I can think of is to use a custom extension method on Dictionary which would wrap the call, catch the exception, and rethrow it with additional information regarding the key, but that wouldn't help for code I don't own, and it feel broken to change such a "base" functionality. What do you think ? --- I'm aware of [this question](https://stackoverflow.com/questions/157911/in-a-net-exception-how-to-get-a-stacktrace-with-argument-values), regarding the general fact that one cannot access the arguments of the method which raised an exception. My question is specifically related to the KeyNotFoundException. --- Edit : I'm aware of the TryGetValue pattern, I do that all the time when I expect that my collection may not contain the key. But when it should contain it, I don't test, because I prefer my program to fail with an exception so that I know something unexpected happened *before* (ie at the time when the key should have been inserted) I could wrap a try/catch/log error/rethrow around all my dictionary access, but this would lead to difficult-to-read code, cluterred with all my exception handling/logging stuff.
Why do you rely on (slow) exceptions? Just verify whether the key exists with `ContainsKey` or `TryGetValue`? I don't know the reason why the exception doesn't contain the error-causing field (maybe because it should be ungeneric) but just wrap it if you think you'll need it. ``` class ParameterizedKeyNotFoundException<T> : KeyNotFoundException { public T InvalidKey { get; private set; } public ParameterizedKeyNotFoundException(T InvalidKey) { this.InvalidKey = InvalidKey; } } static class Program { static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> Dict, TKey Key) { TValue res; if (Dict.TryGetValue(Key, out res)) return res; throw new ParameterizedKeyNotFoundException<TKey>(Key); } static void Main(string[] args) { var x = new Dictionary<string, int>(); x.Add("foo", 42); try { Console.WriteLine(x.Get("foo")); Console.WriteLine(x.Get("bar")); } catch (ParameterizedKeyNotFoundException<string> e) { Console.WriteLine("Invalid key: {0}", e.InvalidKey); } Console.ReadKey(); } } ```
You could use the ContainsKey or TryGetValue method instead to verify if the dictionary contains the key.
Why doesn't .net provide us with the key when it raises a KeyNotFound Exception (and how can I get it?)
[ "", "c#", ".net", "debugging", "exception", "dictionary", "" ]
I have a query that looks like ``` SELECT P.Column1, P.Column2, P.Column3, ... ( SELECT A.ColumnX, A.ColumnY, ... FROM dbo.TableReturningFunc1(@StaticParam1, @StaticParam2) AS A WHERE A.Key = P.Key FOR XML AUTO, TYPE ), ( SELECT B.ColumnX, B.ColumnY, ... FROM dbo.TableReturningFunc2(@StaticParam1, @StaticParam2) AS B WHERE B.Key = P.Key FOR XML AUTO, TYPE ) FROM ( <joined tables here> ) AS P FOR XML AUTO,ROOT('ROOT') ``` P has ~ 5000 rows A and B ~ 4000 rows each This query has a runtime performance of ~10+ minutes. Changing it to this however: ``` SELECT P.Column1, P.Column2, P.Column3, ... INTO #P SELECT A.ColumnX, A.ColumnY, ... INTO #A FROM dbo.TableReturningFunc1(@StaticParam1, @StaticParam2) AS A SELECT B.ColumnX, B.ColumnY, ... INTO #B FROM dbo.TableReturningFunc2(@StaticParam1, @StaticParam2) AS B SELECT P.Column1, P.Column2, P.Column3, ... ( SELECT A.ColumnX, A.ColumnY, ... FROM #A AS A WHERE A.Key = P.Key FOR XML AUTO, TYPE ), ( SELECT B.ColumnX, B.ColumnY, ... FROM #B AS B WHERE B.Key = P.Key FOR XML AUTO, TYPE ) FROM #P AS P FOR XML AUTO,ROOT('ROOT') ``` Has a performance of ~4 seconds. This makes not a lot of sense, as it would seem the cost to insert into a temp table and then do the join should be higher by default. My inclination is that SQL is doing the wrong type of "join" with the subquery, but maybe I've missed it, there's no way to specify the join type to use with correlated subqueries. Is there a way to achieve this without using #temp tables/@table variables via indexes and/or hints? EDIT: Note that dbo.TableReturningFunc1 and dbo.TableReturningFunc2 are inline TVF's, not multi-statement, or they are "parameterized" view statements.
Your procedures are being reevaluated for each row in `P`. What you do with the temp tables is in fact caching the resultset generated by the stored procedures, thus removing the need to reevaluate. Inserting into a temp table is fast because it does not generate `redo` / `rollback`. Joins are also fast, since having a stable resultset allows possibility to create a temporary index with an `Eager Spool` or a `Worktable` You can reuse the procedures without temp tables, using `CTE`'s, but for this to be efficient, `SQL Server` needs to materialize the results of `CTE`. You may *try* to force it do this with using an `ORDER BY` inside a subquery: ``` WITH f1 AS ( SELECT TOP 1000000000 A.ColumnX, A.ColumnY FROM dbo.TableReturningFunc1(@StaticParam1, @StaticParam2) AS A ORDER BY A.key ), f2 AS ( SELECT TOP 1000000000 B.ColumnX, B.ColumnY, FROM dbo.TableReturningFunc2(@StaticParam1, @StaticParam2) AS B ORDER BY B.Key ) SELECT … ``` , which may result in `Eager Spool` generated by the optimizer. However, this is far from being guaranteed. The guaranteed way is to add an `OPTION (USE PLAN)` to your query and wrap the correspondind `CTE` into the `Spool` clause. See this entry in my blog on how to do that: * [**Generating XML in subqueries**](http://explainextended.com/2009/05/28/generating-xml-in-subqueries/) This is hard to maintain, since you will need to rewrite your plan each time you rewrite the query, but this works well and is quite efficient. Using the temp tables will be much easier, though.
This answer needs to be read together with Quassnoi's article <http://explainextended.com/2009/05/28/generating-xml-in-subqueries/> With judicious application of CROSS APPLY, you can force the caching or shortcut evaluation of inline TVFs. This query returns instantaneously. ``` SELECT * FROM ( SELECT ( SELECT f.num FOR XML PATH('fo'), ELEMENTS ABSENT ) AS x FROM [20090528_tvf].t_integer i cross apply ( select num from [20090528_tvf].fn_num(9990) f where f.num = i.num ) f ) q --WHERE x IS NOT NULL -- covered by using CROSS apply FOR XML AUTO ``` You haven't provided real structures so it's hard to construct something meaningful, but the technique should apply as well. If you change the multi-statement TVF in Quassnoi's article to an inline TVF, the plan becomes even faster (at least one order of magnitude) and the plan magically reduces to something I cannot understand (it's too simple!). ``` CREATE FUNCTION [20090528_tvf].fn_num(@maxval INT) RETURNS TABLE AS RETURN SELECT num + @maxval num FROM t_integer ``` Statistics ``` SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. (10 row(s) affected) Table 't_integer'. Scan count 2, logical reads 22, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 2 ms. ```
Why is inserting into and joining #temp tables faster?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I have a ListView where several items have more text than fits in the column width. ShowItemToolTips means i can hover over a column and see the full text which is great. However, for really long texts, it disappears before there is time to read everything, so i would like to make it stay longer (or possibly until the dismissed manually, eg by moving away the mouse or clicking. How do I do this?
You know, of course, that underneath the .NET ListView class is a Windows listview control. This listview control uses a Windows tooltip control to show the truncated strings. You can get hold of this underlying tooltip control through the LVM\_GETTOOLTIPS message. ``` [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); public IntPtr GetTooltipControl(ListView lv) { const int LVM_GETTOOLTIPS = 0x1000 + 78; return SendMessage(lv.handle, LVM_GETTOOLTIPS, 0, 0); } ``` Once you have the handle to the tooltip control, you can send messages to it. ``` public void SetTooltipDelay(ListView lv, int showTime) { const int TTM_SETDELAYTIME = 0x400 + 3; const int TTDT_AUTOPOP = 2; IntPtr tooltip = this.GetTooltipControl(lv); if (tooltip != IntPtr.Zero) { SendMessage(tooltip, TTM_SETDELAYTIME, TTDT_AUTOPOP, showTime); } } ``` showTime is the number of milliseconds you want the control to stay visible.
There is a pure .NET code alternative to the user32.dll P/Invoke call. Create a [ToolTip](http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.aspx) control and set all of the delay properties. Then use the ListView [MouseMove](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousemove.aspx) event to switch the tool tip text based upon the currently selected list view control. ``` ToolTip toolTip = new ToolTip(); toolTip.AutoPopDelay = 7000; toolTip.InitialDelay = 450; toolTip.ReshowDelay = 450; listView.MouseMove += new MouseEventHandler(listView_MouseMove); ``` I gave two options below. Option #1 sets the tool tip text to Text property of the sub-item. Option #2 sets the tool tip to the ToolTipText property of the parent ListViewItem. ``` void listView_MouseMove(object sender, MouseEventArgs e) { ListViewItem item = listView.GetItemAt(e.X, e.Y); ListViewHitTestInfo info = listView.HitTest(e.X, e.Y); if ((item != null) && (info.SubItem != null)) { // Option #1 - Set it to the sub-item text // toolTip.SetToolTip(listView, info.SubItem.Text); // Option #2 - Sets it to the tool tip text of the sub-item toolTip.SetToolTip(listView, info.Item.ToolTipText); } else { toolTip.SetToolTip(listView, null); } } ```
c# make ShowItemToolTips sticky
[ "", "c#", "listview", "" ]
I am trying to put a filter on my C# openFileDialog that excludes certain file extensions. For example I want it to show all files in a directory that are not .txt files. Is there a way to do this?
There is no direct way to do this using the BCL OpenFileDialog. I can think of a couple of options: 1) Make a filter that just has all of the types you do want to support. This would be my recommendation, since that's the most common way of going about this type of operation. 2) Use something along the lines of this [custom OpenFileDialog implementation](http://www.codeproject.com/KB/dialog/OpenFileDialogEx.aspx?fid=356223&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26). You could then override the OnFileNameChanged() method to potentially disable the "Open" button if the selected file has a .txt extension. 3) Let the user pick a .txt file, throw up an error dialog, and reopen the file dialog. This feels clunky and not too great to me, though....
I don't think this is possible. The way the filter is set up, is that you can choose which files to show, but I don't think there's a way to show "All files except...". Come to think of it, have you ever seen an Open File Dialog in Windows that has this? I don't think I've ever seen one. Your best bet is to let them choose all files, and then prompt the user if they select one that isn't allowed OR filter it down to all the possible files that you can deal with.
Excluding file extensions from open file dialog in C#
[ "", "c#", "visual-studio", "openfiledialog", "" ]
``` $('#servertable td:eq(' + server + ')') ``` this finds only 1 (first I think) match, how to find all matches. btw. td:contains will not work for me.
`eq` expects a numerical index to only return a single row. If you want to match a td by its contents, you have to use the [:contains](http://docs.jquery.com/Selectors/contains#text) selector. Saying "it doesn't work" and throwing it away is not the right approach to the problem, as the selector is (most likely) not at fault (Do note its case sensitive, which might be it...) Anyhow, if you have a table like this: ``` <table> <tr> <td>Hello</td> <td>World</td> </tr> <tr> <td>World</td> <td>Hello</td> </tr> <tr> <td>Hello</td> <td>Hello</td> </tr> </table> ``` This jQuery code: ``` $(function() { $("td:contains('Hello')").css('color','red'); }); ``` Will turn all cells with "Hello" to red. [Demo](http://jsbin.com/uzoxi). If you need a case insensitive match, you could do this, using the [`filter`](http://docs.jquery.com/Traversing/filter) function: ``` $(function() { var search = 'HELLO'.toLowerCase(); $("td").filter(function() { return $(this).text().toLowerCase().indexOf(search) != -1; }).css('color','red'); }); ``` If you need to match the *exact* contents of the cell, you could use something similar to the above: ``` $(function() { var search = 'HELLO'.toLowerCase(); $("td").filter(function() { return $(this).text().toLowerCase() == search; }).css('color','red'); }); ``` The above is case insensitive (by turning both the search and the contents to lower case when comparing) otherwise you can just remove those if you want case sensitivity. [Demo](http://jsbin.com/ofeca).
I could be wrong, but the [:eq positional selector](http://docs.jquery.com/Core/eq) takes an integer *n* an finds the *nth* matching element. So if you said td:eq(1) -- you'd get the 2nd TD element in the table (second because the first index is zero/0). My guess is that you don't want to use the [:contains selector](http://docs.jquery.com/Selectors/contains) because you're looking for an exact string match and don't want partial matches. I'm not aware that jquery has a built in selector that will meet your needs (if so, please correct me). You could add one as an extension or use another method, such as an attribute selector to do the search for you. If you are able to control the generated HTML, you could add an ID attribute to each TD like so: ``` <table id="servertable" border="1"> <thead> <tr><th>Server</th><th>Memory</th></tr> </thead> <tbody> <tr><td id="server_mars">Mars</td><td>4 GB</td></tr> <tr><td id="server_venus">Venus</td><td>1 GB</td></tr> <tr><td id="server_jupiter">Jupiter</td><td>2 GB</td></tr> <tr><td id="server_uranus">Uranus</td><td>8 GB</td></tr> <tr><td id="server_mars_2010">Mars_2010</td><td>4 GB</td></tr> </tbody> </table> <form> <label for="server">Find:</label><input type="text" id="server" /> <button id="find">Find</button> </form> ``` The following attribute selector would locate the correct TD in the table: ``` <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#find").click(function() { var server = $("#server").val(); $("#servertable td").css("background-color", ""); // reset $("#servertable td[id='server_" + server.toLowerCase() + "']").css("background-color", "#FFFF00"); return false; }); }); </script> ``` If you instead want to target the entire row that has the TD that you're looking for, you can add additional selectors: ``` $("#servertable tbody tr").css("background-color", ""); $("#servertable tbody tr:has(td[id='server_" + server.toLowerCase() + "'])").css("background-color", "#FFFF00"); ``` The tbody tag isn't completely necessary, it just helps to distinguish between rows in the table body and rows in the table header.
jquery to find all exact td matches
[ "", "javascript", "jquery", "" ]
The dillema is like this: If I try to fit all the scripts blocks on the masterpage (include page in some frameworks), every page gets a copy of every script (including the ones they don't need) and these quickly adds up and bloats the page size. If I include/insert script blocks where needed, javascript will be spread all over the project. I am struggling with where to keep the right balance. Anyone?
We minify, merge and gzip our site wide JS (which is actually about 17 files merged down into two files, one for all our code and one for library code like mootools and clientcide). This greatly reduces the time it takes to download the scripts. Compression and merging are done and the fly and cached on the server so development is not slowed at all. Our total JS for the sitewide goodies is about 50K once all compressed up as above. We also set a long expires time on the files, which all have a version number so when we make a change we up the version number (we have a sitewide one to make it easy) and users are forced to get a fresh version and once downloaded they are cached by the browser. Additionally to that we have made the move to put our JS at the footer of the page, this allows everything to render out much faster and gives the user something to look at while we download the JS. Some individual pages have one off scripts that they need (search forms, etc.) these get the same treatment as above (ie all the files needed would be merged, minified, gzipped) but the sitewide code is left as is so we can make use of the caching. So in this instance we could down load 3 JS files, sitewide, library and custom code for that page(s).
Including all JS files isn't a major problem (unless they have slow code running on loading), and won't bloat the page that much: once they are loaded, the browser will cache them anyway, so it will result in 0 load time on next pages. As long as you don't put the content of the JS files in the page itself, of course! :-)
Where to insert script blocks
[ "", "asp.net", "javascript", "master-pages", "unobtrusive-javascript", "" ]
I have a model that has a field named "state": ``` class Foo(models.Model): ... state = models.IntegerField(choices = STATES) ... ``` For every state, possible choices are a certain subset of all STATES. For example: ``` if foo.state == STATES.OPEN: #if foo is open, possible states are CLOSED, CANCELED ... if foo.state == STATES.PENDING: #if foo is pending, possible states are OPEN,CANCELED ... ``` As a result, when foo.state changes to a new state, its set of possible choices changes also. How can I implement this functionality on Admin add/change pages?
You need to [use a custom ModelForm](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form) in the ModelAdmin class for that model. In the custom ModelForm's \_\_init\_\_ method, you can dynamically set the choices for that field: ``` class FooForm(forms.ModelForm): class Meta: model = Foo def __init__(self, *args, **kwargs): super(FooForm, self).__init__(*args, **kwargs) current_state = self.instance.state ...construct available_choices based on current state... self.fields['state'].choices = available_choices ``` You'd use it like this: ``` class FooAdmin(admin.ModelAdmin): form = FooForm ```
When you create a new admin interface for a model (e.g. MyModelAdmin) there are specific methods for override the default choices of a field. For a generic [choice field](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_choice_field): ``` class MyModelAdmin(admin.ModelAdmin): def formfield_for_choice_field(self, db_field, request, **kwargs): if db_field.name == "status": kwargs['choices'] = ( ('accepted', 'Accepted'), ('denied', 'Denied'), ) if request.user.is_superuser: kwargs['choices'] += (('ready', 'Ready for deployment'),) return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs) ``` But you can also override choices for [ForeignKey](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey) and [Many to Many](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany) relationships.
How to modify choices on Django Admin
[ "", "python", "python-3.x", "django", "django-models", "django-admin", "" ]
Is there a JavaScript library which allow me to perform all the REST operation like (`GET`, `POST`, `PUT` and `DELETE` over `HTTP` or `HTTPS`)?
You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic `$.ajax` function with the type of request you want to make: ``` $.ajax({ url: 'http://example.com/', type: 'PUT', data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray() success: function() { alert('PUT completed'); } }); ``` You can replace `PUT` with `GET`/`POST`/`DELETE` or whatever.
While you may wish to use a library, such as the excellent [jQuery](http://jquery.com/), you don't have to: all modern browsers support HTTP very well in their JavaScript implementations via the [XMLHttpRequest API](http://en.wikipedia.org/wiki/XMLHttpRequest), which, despite its name, is not limited to XML representations. Here's an example of making a synchronous HTTP PUT request in JavaScript: ``` var url = "http://host/path/to/resource"; var representationOfDesiredState = "The cheese is old and moldy, where is the bathroom?"; var client = new XMLHttpRequest(); client.open("PUT", url, false); client.setRequestHeader("Content-Type", "text/plain"); client.send(representationOfDesiredState); if (client.status == 200) alert("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText) else alert("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + "."); ``` This example is synchronous because that makes it a little easier, but it's quite easy to make asynchronous requests using this API as well. There are thousands of pages and articles on the web about learning XmlHttpRequest — they usually use the term AJAX – unfortunately I can't recommend a specific one. You may find [this reference](http://www.w3.org/TR/XMLHttpRequest/) handy though.
JavaScript REST client Library
[ "", "javascript", "jquery", "rest", "" ]
I'm writing my first proper useful piece of software. Part of it will involve the user viewing an image, and choosing to accept or reject it. Doing this will cause the image to be saved to an accepted or rejected folder, and possibly rotated and/or resized. At the moment, my rotate/resize/save operation is pausing execution of my program, but I'd like it to happen in the background so the next image is displayed instantly. Is the only way to do this in Qt to process the image in a separate thread, or is there another way? I'm still getting my head round C++ and Qt, so I don't want to confuse myself by diving into a new field!
Qt has thread support. You might find [this example application](http://doc-snapshot.qt-project.org/4.8/threads-queuedcustomtype-renderthread-cpp.html) interesting since it's somewhat similar to what you describe. Also, [here is the full Qt thread documentation](http://doc.qt.digia.com/stable/thread-basics.html).
these kind of tasks are perfectly suited for threads. still, you should first do a 'normal' function that does it, and when it works add a thread that reads a queue and calls the same processing function. Qt has a lot of tools to help you on this, mainly the fact that most of the containers are thread-safe, and also a couple of threading algorithms (like map-reduce). still, first try it synchronously.
Running a separate process or thread in Qt
[ "", "c++", "multithreading", "qt", "concurrency", "" ]
How can I run a batch file on the client side? An exe file? Just to open pre-installed program in client side? [Edit] Regarding ActiveX, I tried ``` var activeXObj = new ActiveXObject("Shell.Application"); activeXObj.ShellExecute("C:\\WINDOWS\\NOTEPAD.EXE", "", "", "open", "1"); ``` but this doesn't work. Any suggestions?
From Javascript? You can't. It's a security risk. Think about it - would you want every website to be able to run programs on your PC?
You mean launch an external program thru a browser window using JavaScript? No way you can do that! That's a goddamn security black hole!
How can I run a program or batch file on the client side?
[ "", "javascript", "batch-file", "executable", "client-side", "" ]
I'm iterating over a JRE `Collection` which enforces the fail-fast iterator concept, and thus will throw a `ConcurrentModificationException` if the `Collection` is modified while iterating, other than by using the `Iterator.remove()` method . However, I need to remove an object's "logical partner" if the object meets a condition. Thus preventing the partner from also being processed. How can I do that? Perhaps by using better collection type for this purpose? Example. ``` myCollection<BusinessObject> for (BusinessObject anObject : myCollection) { if (someConditionIsTrue) { myCollection.remove(anObjectsPartner); // throws ConcurrentModificationException } } ``` Thanks.
You want to remove an item from a list and continue to iterate on the same list. Can you implement a two-step solution where in step 1 you collect the items to be removed in an interim collection and in step 2 remove them after identifying them?
It's not a fault of the collection, it's the way you're using it. Modifying the collection while halfway through an iteration leads to this error (which is a good thing as the iteration would in general be impossible to continue unambiguously). *Edit*: Having reread the question this approach won't work, though I'm leaving it here as an example of how to avoid this problem in the general case. What you want is something like this: ``` for (Iterator<BusinessObject> iter = myCollection.iterator; iter.hasNext(); ) { BusinessObject anObject = iter.next(); if (someConditionIsTrue) { iter.remove(); } } ``` If you remove objects through the Iterator itself, it's aware of the removal and everything works as you'd expect. Note that while I think all standard collections work nicely in this respect, Iterators are not *required* to implement the remove() method so if you have no control over the class of `myCollection` (and thus the implementation class of the returned iterator) you might need to put more safety checks in there. An alternative approach (say, if you can't guarantee the iterator supports `remove()` and you require this functionality) is to create a *copy* of the collection to iterate over, then remove the elements from the *original* collection. *Edit*: You can probably use this latter technique to achieve what you want, but then you still end up coming back to the reason why iterators throw the exception in the first place: **What should the iteration do if you remove an element it hasn't yet reached**? Removing (or not) the current element is relatively well-defined, but you talk about removing the current element's *partner*, which I presume could be at a random point in the iterable. Since there's no clear way that this should be handled, you'll need to provide some form of logic yourself to cope with this. In which case, I'd lean towards creating and populating a new collection during the iteration, and then assigning this to the `myCollection` variable at the end. If this isn't possible, then keeping track of the partner elements to remove and calling `myCollection.removeAll` would be the way to go.
How to safely remove other elements from a Collection while iterating through the Collection
[ "", "java", "collections", "" ]
What's the difference in Java between a utility class (a class with static methods) and a Service class (a class with public methods that provides a "service"). For example, one can argue that a cryptographic object (providing methods to encrypt, decrypt, hash or get a salt value) is a Service provider, but many group this functionality into a Utility class with static methods, like CryptoUtil.encrypt(...). I'm trying to figure out which way follows better "design". Thoughts?
Different behaviors can be obtained by using different service objects. Static methods in a utility class can't be swapped out. This is extremely useful for testing, changing implementations, and other purposes. For example, you mention a `CryptoUtil` with an `encrypt` method. It would extremely useful to have different objects that could support different encryption strategies, different message recipients, etc.
The difference is that service classes might have state. And by state I mean conversational state. Consider a notional ordering system. ``` interface OrderSystem { void login(String username, String password); List<Item> search(String criteria); void order(Item item); void order(Item item, int quantity); void update(Item item, int quantity); void remove(Item item); void checkout(); Map<Item, Integer> getCart(); void logout(); } ``` Such a thing could be done with stateful session beans (as one example), although in that case authentication would probably be covered more traditional EJB mechanisms. The point here is that there is conversational state in that the results of one call affects subsequent calls. You could view static methods as a bunch of simple stateless services that execute locally. A service has a much broader meaning that includes, but is not limited to, being: * stateful; * remote; and * implementation dependent (ie through an interface). Best practice I think is to simply use static methods as convenience methods (especially given Java's lack of extension methods). Services are much richer than that.
Java Utility Class vs. Service
[ "", "java", "static", "service", "utility", "" ]