Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I know we can do something like this: ``` Class.class.getResourceAsStream("/com/youcompany/yourapp/module/someresource.conf") ``` to read the files that are packaged within our jar file. I have googled it a lot and I am surely not using the proper terms; what I want to do is to list the available resources, something like this: ``` Class.class.listResources("/com/yourcompany/yourapp") ``` That should return a list of resources that are inside the package `com.yourcompany.yourapp.*` Is that possible? Any ideas on how to do it in case it can't be done as easily as I showed? Note: I know it is possible to know where your jar is and then open it and inspect its contents to achieve it. But, I can't do it in the environment I am working in now.
For resources in a JAR file, something like this works: ``` URL url = MyClass.class.getResource("MyClass.class"); String scheme = url.getProtocol(); if (!"jar".equals(scheme)) throw new IllegalArgumentException("Unsupported scheme: " + scheme); JarURLConnection con = (JarURLConnection) url.openConnection(); JarFile archive = con.getJarFile(); /* Search for the entries you care about. */ Enumeration<JarEntry> entries = archive.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith("com/y/app/")) { ... } } ``` You can do the same thing with resources "exploded" on the file system, or in many other repositories, but it's not quite as easy. You need specific code for each URL scheme you want to support.
In general can't get a list of resources like this. Some classloaders may not even be *able* to support this - imagine a classloader which can fetch individual files from a web server, but the web server doesn't have to support listing the contents of a directory. For a jar file you can load the contents of the jar file explicitly, of course. ([This question](https://stackoverflow.com/questions/676097/java-resource-as-file) is similar, btw.)
How to walk through Java class resources?
[ "", "java", "resources", "classpath", "" ]
Is there any way to make a **label** on a .NET Windows form to be **highlightable** to allow for the text to be copied. I have attempted to do this with a text box that was made to look like a label, but this results in a flashing cursor.
I think this is pretty darn close: ``` textBox.BackColor = System.Drawing.SystemColors.Control; textBox.BorderStyle = System.Windows.Forms.BorderStyle.None; textBox.ReadOnly = true; textBox.Text = "This is selectable text"; textBox.MouseUp += new MouseEventHandler( delegate(object sender, MouseEventArgs e) { HideCaret((sender as Control).Handle); }); [DllImport("User32.dll")] static extern Boolean HideCaret(IntPtr hWnd); ``` And if you need it to span more than one line: ``` textBox.Multiline = true; ```
If you want it to be a predictable, well behaved and standard control with all the keyboard and shortcut support you simply need a textbox. And then the flashing cursor is a normal helpful feature, why fight it?
Highlighting labels Windows Forms
[ "", "c#", ".net", "windows", "winforms", "user-interface", "" ]
Say I have a string of words: `'a b c d e f'`. I want to generate a list of multi-word terms from this string. Word order matters. The term `'f e d'` shouldn't be generated from the above example. **Edit:** Also, words should not be skipped. `'a c'`, or `'b d f'` shouldn't be generated. **What I have right now:** ``` doc = 'a b c d e f' terms= [] one_before = None two_before = None for word in doc.split(None): terms.append(word) if one_before: terms.append(' '.join([one_before, word])) if two_before: terms.append(' '.join([two_before, one_before, word])) two_before = one_before one_before = word for term in terms: print term ``` **Prints:** ``` a b a b c b c a b c d c d b c d e d e c d e f e f d e f ``` How would I make this a recursive function so that I can pass it a variable maximum number of words per term? **Application:** I'll be using this to generate multi-word terms from readable text in HTML documents. The overall goal is a latent semantic analysis of a large corpus (about two million documents). This is why keeping word order matters (Natural Language Processing and whatnot).
This isn't recursive, but I think it does what you want. ``` doc = 'a b c d e f' words = doc.split(None) max = 3 for index in xrange(len(words)): for n in xrange(max): if index + n < len(words): print ' '.join(words[index:index+n+1]) ``` And here's a recursive solution: ``` def find_terms(words, max_words_per_term): if len(words) == 0: return [] return [" ".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term) doc = 'a b c d e f' words = doc.split(None) for term in find_terms(words, 3): print term ``` Here's the recursive function again, with some explaining variables and comments. ``` def find_terms(words, max_words_per_term): # If there are no words, you've reached the end. Stop. if len(words) == 0: return [] # What's the max term length you could generate from the remaining # words? It's the lesser of max_words_per_term and how many words # you have left. max_term_len = min(len(words), max_words_per_term) # Find all the terms that start with the first word. initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)] # Here's the recursion. Find all of the terms in the list # of all but the first word. other_terms = find_terms(words[1:], max_words_per_term) # Now put the two lists of terms together to get the answer. return initial_terms + other_terms ```
I would suggest that you should make your function a generator and then generate required number of terms. You would need to change `print` to `yield` (and make the whole block function, obviously). You might have a look at [itertools](http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools) module as well, it's fairly useful for kind of work you do.
How do I generate multi-word terms recursively?
[ "", "python", "recursion", "" ]
Consider the following criteria query: var x = SomeCriteria.AddOrder(new Order("Name", true)).List(); This will order the result set by the Name property, but case sensitive: ``` "A1" "B1" "a2" ``` Any ideas how to add the order case insensitive so result "a2" will end up before "B1"?
You should be able to accomplish this by ordering on a projection that normalizes the case for you. For example, Oracle has a "lower" function that will lower case string data types like varchar2 and nvarchar2; so I will use this sql function to form a projection that will order appropriately. ``` var projection = Projections.SqlFunction("lower", NHibernateUtil.String, Projections.Property("Name")); var x = SomeCriteria.AddOrder(Orders.Asc(projection)).List() ``` If you're using SQL Server, I'd recommend using the "upper" function instead of "lower" for efficiency. Microsoft has optimized its native code for performing uppercase comparisons, where the rest of the world seems to have optimized on lowercase.
Hibernate (Java) has an "ignoreCase()" method on the "Order" class, but it looks like NHibernate does not have this method on its "Order." This is how I was thinking you could do it: ``` var x = SomeCriteria.AddOrder(new Order("Name", true).IgnoreCase()).List(); ``` But unfortunately, there is no IgnoreCase(). As a workaround, you could use an HQL or SQL query - either of those should allow you to order case-insensitive.
Case-insensitive sort ordering in NHibernate
[ "", "c#", "nhibernate", "" ]
In c# I am using the UdpClient.Receive function: ``` public void StartUdpListener(Object state) { try { udpServer = new UdpClient(new IPEndPoint(IPAddress.Broadcast, 1234)); } catch (SocketException ex) { MessageBox.Show(ex.ErrorCode.ToString()); } IPEndPoint remoteEndPoint = null; receivedNotification=udpServer.Receive(ref remoteEndPoint); ... ``` However I am getting a socket exception saying that the address is not available with error code 10049 What do I do to negate this exception?
Here's the jist of some code I am currently using in a production app that works (we've got a bit extra in there to handle the case where the client are server apps are running on a standalone installation). It's job is to receive udp notifications that messages are ready for processing. As mentioned by Adam Alexander your only problem is that you need to use IPAddress.Any, instead of IPAddress.Broadcast. You would only use IPAddress.Broadcast when you wanted to *Send* a broadcast UDP packet. Set up the udp client ``` this.broadcastAddress = new IPEndPoint(IPAddress.Any, 1234); this.udpClient = new UdpClient(); this.udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); this.udpClient.ExclusiveAddressUse = false; // only if you want to send/receive on same machine. ``` And to trigger the start of an async receive using a callback. ``` this.udpClient.Client.Bind(this.broadcastAddress); this.udpClient.BeginReceive(new AsyncCallback(this.ReceiveCallback), null); ``` Hopefully this helps, you should be able to adapt it to working synchronously without too much issue. Very similar to what you are doing. If you're still getting the error after this then something else must be using the port that you are trying to listen on. So, to clarify. IPAddress.Any = Used to receive. I want to listen for a packet arriving on any IP Address. IPAddress.Broadcast = Used to send. I want to send a packet to anyone who is listening.
for your purposes I believe you will want to use IPAddress.Any instead of IPAddress.Broadcast. Hope this helps!
UdpClient receive on broadcast address
[ "", "c#", "udp", "" ]
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question. Firstly, here is what I am trying to use as my main program: ``` import java.util.Scanner; public class TheATMGame { public static void main(String[] args){ Scanner input = new Scanner(System.in); double newBalance = 0; double monthlyInterest = 0; int answer = 0; int i=1; while (i < 100) { System.out.print ("Please enter your ID: "); answer = input.nextInt(); System.out.println(" "); if (answer >=0 && answer<10) TheATMGame.runGame (answer); else System.out.println("Sorry, this ID is invalid."); } } public static void runGame(int id) { double amount = 0; int continueOn = 0; while (continueOn < 4) { ATMGame myATM = new ATMGame(); Scanner input = new Scanner(System.in); System.out.println ("---Main menu--- "); System.out.println ("1: Check balance "); System.out.println ("2: Withdraw "); System.out.println ("3: Deposit "); System.out.println ("4: exit "); int answer = input.nextInt(); if (answer == 1) System.out.println("your balance is: " + myATM.getBalance (id)); else if (answer == 2){ System.out.println("Enter an amount to withdraw: "); amount = input.nextInt(); myATM.withdraw(amount, id); } else if (answer == 3) { System.out.println("Enter an amount to deposit: "); amount = input.nextInt(); myATM.deposit(amount, id); } else if (answer == 4) continueOn = 4; else if (answer > 4) System.out.println ("Please review the main menu. " + "Your selection must be between 1-4."); } } //ATM class (balance, annualInterestRate2, id2) //ATM myATM = new ATM (20000, 4.5, 1122 ); //newBalance = myATM.withdraw(2500); //newBalance = myATM.deposit(3000); //monthlyInterest = myATM.getMonthlyInterestRate(); //System.out.println("Your current balance is: " + newBalance); //System.out.println ("Your monthly interest rate is: " + monthlyInterest); } ``` Now here are all of the classes I want to impliment into that program: ``` import java.util.Date; public class ATMGame { private double annualInterestRate = 0; private double balance = 0; private int id = 11; private int[] ids = {0,1,2,3,4,5,6,7,8,9}; private int[] balances = {100,100,100,100,100,100,100,100,100,100}; public Date dateCreated; public ATMGame() { } public ATMGame (double balance2, double annualInterestRate2, int id2) { balance = balance2; annualInterestRate = annualInterestRate2; id = id2; dateCreated.getTime(); } public double getMonthlyInterestRate() { double monthlyInterest = annualInterestRate/12; return monthlyInterest; } public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account double newBalance = balances[id] - amountWithdrawn; System.out.println("Your withdrawel has processed. New balance: " + newBalance); balances[id] = (int) newBalance; return newBalance ; } public double deposit(double amountDeposited, int id) { //This method deposits money in the account double newBalance = balances[id] + amountDeposited; System.out.println("Your deposit has processed. New Balance is: " + newBalance); balances[id] = (int) newBalance; return newBalance ; } public double getBalance(int id) { double myBalance = balances[id]; balance = myBalance; return myBalance ; } } ``` When I try to run the first program it says "No Main classes found." As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong? **Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found."** :/ <http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg> I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
In your class `ATMGame`, replace the following: ``` public void Main() { ``` with: ``` public static void main(String[] args) { ``` Additionally, since this method has to be static, you'll need to change the following: ``` if (answer >=0 && answer<10) runGame (answer); else ``` with: ``` if (answer >=0 && answer<10) ATMGame.runGame (answer); else ``` Then finally, you need to change the method signature of `rungame` to also be static. Change it from: ``` public void runGame(int id) { ``` to: ``` public static void runGame(int id) { ```
You should use: ``` public static void main(String[] args) ``` Instead of Main because the JVM calls this method first. It is a convention.
Java methods and classes, how do they fit together?
[ "", "java", "class", "methods", "main-method", "" ]
I'm trying to use an open source java library to visualize nodes and edges in a graph, but I'm completely lost. I have a bunch of jar files in a folder. Clicking on some of the jar files makes java swing windows pop open with graphs displayed. Clicking other jar files does nothing. If I figured that out, would I just stick the jar files in there with the other ones, or would that still not work? And if I ever figure out how to use these files, does that mean that I have to include them if I transfer my java project to another computer? How would I go about doing that?
Have you included those libraries in your classpath? If you are using eclipse, you could Project - > properties -> Java build path ->addJar. And the Jar file should be placed in a directory inside your workspace (lib/ for example) If you have to take your project to another computer, you could take these steps 1. Before doing anything, export your project (as a Jar file, for example). 2. Save it into your favorite drive (cd / usb drive/ diskette/ tape). 3. On "the other" computer, you can import this project into your workspace
I believe if you put the jars in your classpath, you can import and use classes just like you would a standard library. Figuring out the classpath can be confusing, but you can just set it when you start your jvm. Your IDE may have options for it, too. Most java problems are classpath problems.
How do you use a Java Library?
[ "", "java", "jar", "" ]
I am coding several reference algorithms in both Java and C/C++. Some of these algorithms use π. I would like for the two implementations of each algorithm to produce **identical** results, without rounding differently. One way to do this that has worked consistently so far is to use a custom-defined `pi` constant which is exactly the same in both languages, such as 3.14159. However, it strikes me as silly to define pi when there are already high-precision constants defined in both the Java and GCC libraries. I've spent some time writing quick test programs, looking at documentation for each library, and reading up on floating-point types. But I haven't been able to convince myself that java.lang.Math.PI (or java.lang.StrictMath.PI) is, or is not, equal to M\_PI in math.h. GCC 3.4.4 (cygwin) math.h contains: ``` #define M_PI 3.14159265358979323846 ^^^^^ ``` but this ``` printf("%.20f", M_PI); ``` produces ``` 3.14159265358979311600 ^^^^^ ``` which suggests that the last 5 digits cannot be trusted. Meanwhile, Javadocs say that java.lang.Math.PI is: > The `double` value that is closer than > any other to *pi*, the ratio of the > circumference of a circle to its > diameter. and ``` public static final double PI 3.141592653589793d ``` which omits the questionable last five digits from the constant. ``` System.out.printf("%.20f\n", Math.PI); ``` produces ``` 3.14159265358979300000 ^^^^^ ``` If you have some expertise in floating-point data types, can you convince me that these library constants are exactly equal? Or that they are definitely not equal?
Yes, they are equal, and using them will insure that GCC and Java implementations of the same algorithm are on the same footing – at least as much as using a hand-defined `pi` constant would†. One caveat, hinted by [S. Lott](https://stackoverflow.com/questions/825559#825668), is that the GCC implementation must hold `M_PI` in a `double` data type, and not `long double`, to ensure equivalence. Both Java and GCC appear to use IEEE-754's 64-bit decimal representation for their respective `double` data types. The bytewise representation (MSB to LSB) of the library value, expressed as a `double`, can be obtained as follows (thanks to [JeeBee](https://stackoverflow.com/questions/825559#825631)): pi\_bytes.c: ``` #include <math.h> #include <stdio.h> int main() { double pi = M_PI; printf("%016llx\n", *((uint64_t*)&pi)); } ``` pi\_bytes.java: ``` class pi_bytes { public static void main(String[] a) { System.out.printf("%016x\n", Double.doubleToRawLongBits( Math.PI ) ); } } ``` Running both: ``` $ gcc -lm -o pi_bytes pi_bytes.c && ./pi_bytes 400921fb54442d18 $ javac pi_bytes.java && java pi_bytes 400921fb54442d18 ``` The underlying representations of `M_PI` (as a `double`) and `Math.PI` are identical, down to their bits. † – As noted by [Steve Schnepp](https://stackoverflow.com/questions/825559#825746), the output of math functions such as sin, cos, exp, etc. is not guaranteed to be identical, even if the inputs to those computations are bitwise identical.
Note the following. The two numbers are the same to 16 decimal places. That's almost 48 bits which are the same. In an IEEE 64-bit floating-point number, that's all the bits there are that aren't signs or exponents. The `#define M_PI` has 21 digits; that's about 63 bits of precision, which is good for an IEEE 80-bit floating-point value. What I think you're seeing is ordinary truncation of the bits in the `M_PI` value.
Is java.lang.Math.PI equal to GCC's M_PI?
[ "", "java", "gcc", "floating-point", "language-features", "pi", "" ]
How can I call a function from an object in javascript, like for example in jquery you call myDiv.html() to get the html of that div. So what I want is this to work : ``` function bar(){ return this.html(); } alert($('#foo').bar()); ``` this is a simplified example, so please don't say : just do $('#foo').html() :)
``` jQuery.fn.extend({ bar: function() { return this.html(); } }); alert($('#foo').bar()); ```
You mean how you call a function with an *object in context*? This works- ``` function bar() { return this.html(); } bar.apply($('#foo')); ``` Or if you want to attach a method to an object permanently, ``` obj = {x: 1}; obj.prototype.bar = function() {return this.x;}; obj.bar(); ```
Call a function from an object : object.function()
[ "", "javascript", "jquery", "function", "object", "methods", "" ]
I'm making an application where I interact with each running application. Right now, I need a way of getting the window's z-order. For instance, if Firefox and notepad are running, I need to know which one is in front. Any ideas? Besides doing this for each application's main window I also need to do it for its child and sister windows (windows belonging to the same process).
You can use the GetTopWindow function to search all child windows of a parent window and return a handle to the child window that is highest in z-order. The GetNextWindow function retrieves a handle to the next or previous window in z-order. GetTopWindow: <http://msdn.microsoft.com/en-us/library/ms633514(VS.85).aspx> GetNextWindow: <http://msdn.microsoft.com/en-us/library/ms633509(VS.85).aspx>
Nice and terse: ``` int GetZOrder(IntPtr hWnd) { var z = 0; for (var h = hWnd; h != IntPtr.Zero; h = GetWindow(h, GW.HWNDPREV)) z++; return z; } ``` If you need more reliability: ``` /// <summary> /// Gets the z-order for one or more windows atomically with respect to each other. In Windows, smaller z-order is higher. If the window is not top level, the z order is returned as -1. /// </summary> int[] GetZOrder(params IntPtr[] hWnds) { var z = new int[hWnds.Length]; for (var i = 0; i < hWnds.Length; i++) z[i] = -1; var index = 0; var numRemaining = hWnds.Length; EnumWindows((wnd, param) => { var searchIndex = Array.IndexOf(hWnds, wnd); if (searchIndex != -1) { z[searchIndex] = index; numRemaining--; if (numRemaining == 0) return false; } index++; return true; }, IntPtr.Zero); return z; } ``` (According to the Remarks section on [`GetWindow`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633515.aspx), `EnumChildWindows` is safer than calling `GetWindow` in a loop because your `GetWindow` loop is not atomic to outside changes. According to the Parameters section for [`EnumChildWindows`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms633494.aspx), calling with a null parent is equivalent to `EnumWindows`.) Then instead of a separate call to `EnumWindows` for each window, which would also be not be atomic and safe from concurrent changes, you send each window you want to compare in a params array so their z-orders can all be retrieved at the same time.
How to get the z-order in windows?
[ "", "c#", ".net", "windows", "z-order", "" ]
I have a fairly large CRUD WinForm app that has numerous objects. **Person, Enrollment, Plan, CaseNote etc**. There are over 30 forms that make up the app with the UI broken down logically. **Member, Enrollments, Plans, CaseNotes, etc**. I am trying to figure out how I can create my ***Person Object*** after searching on the *Search Form* and pass THE object to the next requested form. Whatever that may be, let's say *Demographics*. The short of it is that I need the Person object to be available throughout the App and there can only be one. Now I have ZERO exposure to Design Patterns but I am trying. I have read <http://www.switchonthecode.com/tutorials/csharp-tutorial-singleton-pattern> and <http://www.yoda.arachsys.com/csharp/singleton.html> but I want to make sure I understand correctly how to apply this to my situation. First, the examples state that you are accessing a *reference*, correct? Am I mistaken or would I need to access the *value*? Second, is there anything else that I need to do to make this Globally available? Do I just declare a instance on each form but through this Singleton Pattern so as to not have more then one? Thanks ## EDIT 1 To clarify, All objects are child objects of Person. Also, As the Search Page eludes to; the users can select a different currentPerson. But they can only interact with ***ONE*** Person at a time. Lastly, as I stated I am an infant in this and if I should be considering something else, a different approach please say so and if you'd be so kind as to offer some explanation as to why, I'd be very grateful. ## EDIT 2 Based on Medicine Man's comment I thought I wauld clarify. First, Thank you to everyone who has contributed so far. Second, I don't know the first thing about design patterns and I certainly don't have the foggiest if a certain one is needed in my current situation. If someone has a better, simpler, or ,in your opinion, a more fitting method of passing a Data Object from FORM to FORM to FORM then PLEASE tell. In the end I just need a way of tracking the information as my users go from place to place. Thank You ---
You can use the Singleton pattern to assure that only one instance is ever created. However, [the jury is still out](https://stackoverflow.com/questions/11831/singletons-good-design-or-a-crutch) (at least in my mind) on whether this is a good decision. There's plenty of reading on SO and other places about this. I would approach this from a different angle. I'd make all of my forms take in a Person instance in the constructor. That way, each form is only ever worried about it's instance of Person. You could do this by creating a new class that inherits from Form and has a field/property/constructor for your Person. Then, any form that uses Person can inherit from your new class. You would, of course, have to manage the creation of your Person object. You could even do this with a singleton. However, the benefit is that each form doesn't have to know how to create a Person or who created the Person. That way, if you choose to [move away from the Singleton pattern](https://stackoverflow.com/questions/474613/how-should-i-refactor-my-code-to-remove-unnecessary-singletons), you wouldn't have to go change all of your references to your singleton instance. **EDIT:** Here's some code to demonstrate this. It took me a while to get the designer to play nice. I had to add an empty private constructor in PersonForm to get the designer to not throw an error. Program.cs ``` static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyDerivedForm(new Person { Name = "Hello World!" })); } } ``` Person.cs ``` public class Person { public virtual string Name { get; set; } } ``` PersonForm.cs ``` using System; using System.Windows.Forms; public class PersonForm : Form { private readonly Person myPerson; protected virtual Person MyPerson { get { return this.myPerson; } } private PersonForm() { } public PersonForm(Person person) { this.myPerson = person; } } ``` MyDerivedForm.cs (add a label named label1) ``` public partial class MyDerivedForm : SingletonMadness.PersonForm { public MyDerivedForm(Person person) : base(person) { InitializeComponent(); } private void MyDerivedForm_Load(object sender, EventArgs e) { label1.Text = this.MyPerson.Name; } } ```
> First, the examples state that you are accessing a reference, correct? Am I mistaken or would I need to access the value? Your class that you are accessing is a reference to a single class in memory. For example, say your class is: ``` public class Person { ... } ``` If you have a singleton of that, you'll have a single "Person" saved in memory, with a shared reference to that one person in the singleton. When you access your single person, you'll be working with that reference, which is probably what you want. Any changes to the person will change it everywhere. > Second, is there anything else that I need to do to make this Globally available? Do I just declare a instance on each form but through this Singleton Pattern so as to not have more then one? Singletons are used to basically enforce that every time you use the object, it's the same object (each use is a separate reference to the one, single object in memory). You can just grab the singleton anywhere you need it, and it'll just work.
MonoState, Singleton, or Derived Forms: Best approach for CRUD app?
[ "", "c#", ".net", "winforms", "design-patterns", "singleton", "" ]
I am using ASP.net with VB.NET. Is there some Validator that I can use that will check the size of the uploaded image? Else what must I do in code to make sure that the user do not upload images more than 1MB? p.s C# code will also do, I can use a converter to VB.NET **EDIT** For some reason when I change the maxRequestLength to 1024 (in my WEB.config) and I upload a image with size 1.25mb then I get the Microsoft Error page saying "Internet Explorer cannot display the webpage". And I do have a Try Catch block inside my Submit button. If I remove the maxRequestLength from my Web.config then it works fine.
This is ultimately handled in Web.config. Look for the httpRuntime section: ``` <httpRuntime executionTimeout="110" maxRequestLength="4096" /> ``` There are many other settings in httpRuntime but these are the two that are relevant. Here, the maxRequestLength is set to 4096, or 4KB (the number is in bytes). So, set this value accordingly. Also, you will want to set the executionTimeout accordingly as well so it gives a reasonable amount of time to upload whatever you max upload is.
You can use the following code to determine the size [in KB] of the uploaded file and once you know the size you can easily decide if you want to proceed further with the file or reject the upload. ``` Request.Files(0).ContentLength / 1024 ```
Best way to make sure the user dont upload images more than 1MB in size
[ "", "c#", "asp.net", "vb.net", "image", "file-upload", "" ]
I am starting a process from a Windows application. When I press a button I want to simulate the pressing of key `F4` in that process. How can I do that? [Later edit] I don't want to simulate the pressing of the `F4` key in my form, but in the process I started.
To send the F4 key to another process you will have to activate that process <http://bytes.com/groups/net-c/230693-activate-other-process> suggests: 1. Get Process class instance returned by Process.Start 2. Query Process.MainWindowHandle 3. Call unmanaged Win32 API function "ShowWindow" or "SwitchToThisWindow" You may then be able to use System.Windows.Forms.SendKeys.Send("{F4}") as Reed suggested to send the keystrokes to this process EDIT: The code example below runs notepad and sends "ABC" to it: ``` using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; namespace TextSendKeys { class Program { [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); static void Main(string[] args) { Process notepad = new Process(); notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe"; notepad.Start(); // Need to wait for notepad to start notepad.WaitForInputIdle(); IntPtr p = notepad.MainWindowHandle; ShowWindow(p, 1); SendKeys.SendWait("ABC"); } } } ```
You can use [System.Windows.Forms.SendKeys.Send("{F4}")](http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx);
How can I send the F4 key to a process in C#?
[ "", "c#", "process", "keyboard", "key", "" ]
I am trying to determine the class type of a class using reflection and then do something specific. For example, if the class is a double, use a double specific method. I am attempting to use ``` if(f.getClass() == Double.class) ``` However, I am getting a compiler error: "Incompatible operand types Class <capture#1-of ? extends Field> and Class<Double>" What is the proper way to do this? Edit: to be more clear f is of type Field. obtained by reflection in a loop ``` (Field f : instance.getDeclaredFields()) ```
Interesting error message (I didn't know '==' operator would check those). But based on it, I suspect that your comparison is wrong: you are trying to see if Field class (theoretically its super-class, but only in theory -- Field is final) is same as Double.class, which it can not be. So: yes, comparison should work, iff you give it right arguments. So I suspect you want to do: if (f.getType() == Double.class) instead. And that should work, given that Double is a final class. Otherwise "isAssignableFrom" would be more appropriate.
If you have objects then use ``` if (f instanceof Double) { } ``` Another interesting thing is method isAssignableFrom: ``` if (f.getClass().isAssignableFrom (Double.class)) { } ``` But in general it's a bad style. Use polymorphism to implement logic which depends on class types. --- Answer for comment: f instanceof Double works fine. You probably wrote something like this: ``` float f = 1.1f; if (f instanceof Double) { ..} ``` And smart java compiler says that you've got CE. BUT: ``` public static boolean isInstanceOfDouble (Object obj) { return obj instanceof Double; } psvm (String [] args) { sout (isInstanceOfDouble (1.1f); } ``` ..this works fine
How do I compare classes using reflection?
[ "", "java", "reflection", "" ]
I don't necessarily want to use UUIDs since they are fairly long. The file just needs to be unique within its directory. One thought which comes to mind is to use `File.createTempFile(String prefix, String suffix)`, but that seems wrong because the file is not temporary. The case of two files created in the same millisecond needs to be handled.
Well, you could use the 3-argument version: [`File.createTempFile(String prefix, String suffix, File directory)`](http://java.sun.com/javase/6/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File)) which will let you put it where you'd like. Unless you tell it to, Java won't treat it differently than any other file. The only drawback is that the filename is guaranteed to be at least 8 characters long (minimum of 3 characters for the prefix, plus 5 or more characters generated by the function). If that's too long for you, I suppose you could always just start with the filename "a", and loop through "b", "c", etc until you find one that doesn't already exist.
I'd use Apache Commons Lang library ([<http://commons.apache.org/lang>](http://commons.apache.org/lang)). There is a class `org.apache.commons.lang.RandomStringUtils` that can be used to generate random strings of given length. **Very handy not only for filename generation!** Here is the example: ``` String ext = "dat"; File dir = new File("/home/pregzt"); String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext); File file = new File(dir, name); ```
What is the best way to generate a unique and short file name in Java
[ "", "java", "file", "" ]
I can't understand why this few lines ``` Date submissionT; SimpleDateFormat tempDate = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"); public time_print(String time) { try { submissionT=tempDate.parse(time); } catch (Exception e) { System.out.println(e.toString() + ", " + time); } } ``` Cause exceptions and print out ``` java.text.ParseException: Unparseable date: "Tue Mar 31 06:09:00 CEST 2009", Tue Mar 31 06:09:00 CEST 2009 ``` ... while the "unparsable" time is compliant with the format string i've passed to SimpleDateFormat().. Any Idea?
It is a Locale issue. Use: ``` sdf = SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US); ```
**Works for me.** ``` public class Main { public static void main(String[] args) { time_print("Tue Mar 31 06:09:00 CEST 2009"); } static Date submissionT; static SimpleDateFormat tempDate = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"); public static void time_print(String time) { try { submissionT=tempDate.parse(time); System.out.println(submissionT); } catch (Exception e) { System.out.println(e.toString() + ", " + time); } } ``` }
Unexpected java SimpleDateFormat parse exception
[ "", "java", "datetime", "formatting", "" ]
I want to retrieve the HTML code of a link (web page) in PHP. For example, if the link is <https://stackoverflow.com/questions/ask> then I want the HTML code of the page which is served. I want to retrieve this HTML code and store it in a PHP variable. How can I do this?
If your PHP server allows url fopen wrappers then the simplest way is: ``` $html = file_get_contents('https://stackoverflow.com/questions/ask'); ``` If you need more control then you should look at the [cURL](http://www.php.net/curl) functions: ``` $c = curl_init('https://stackoverflow.com/questions/ask'); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); //curl_setopt(... other options you want...) $html = curl_exec($c); if (curl_error($c)) die(curl_error($c)); // Get the status code $status = curl_getinfo($c, CURLINFO_HTTP_CODE); curl_close($c); ```
Also if you want to manipulate the retrieved page somehow, you might want to try some php DOM parser. I find [*PHP Simple HTML DOM Parser*](http://simplehtmldom.sourceforge.net/) very easy to use.
How do I get the HTML code of a web page in PHP?
[ "", "php", "html", "" ]
I get an UnauthorizedAccessException everytime I try to access (just **read**) a file on a network share *"\\server\folder1\folder2\file.pdf."* I am impersonating the domain\aspnet user which has read & write access to the above mentioned folders. The file is not read-only. I tried finding the permissions via System.Security.Permissions.FileIOPermission. It just says NoAccess to all files. I'm not sure what else I can do. I am using Visual Studio 2008, ASP.net 2.0 on Framework 3.5, WinXP, IIS 5.1.
ASP.NET user will not work with network path. So you need to have a windows account that will have all the rights and then you need to imposernate things in web.config like following. ``` <identity impersonate="true" userName="domainname\windowuseraccount" password="password"/> ```
I'll assume you have set up the impersonation properly. You have turned off anonymous access, set the authentication mode to Windows and set impersonation to true, etc. Even with all that done properly and the correct account impersonating you will still not be able to access the file. The account being impersonated is using what are called network credentials. These are only valid on the machine on which the impersonation is taking place. When you attempt to access a file on the computer itself the access is performed with the user's credentials but for a file on a share the access is done as a non-authenticated user and so no access is allowed. In order to allow you to use the user's credentials for remote work, i.e. accessing a share, integrated security for a remote database, etc. you need to use delegation rather than impersonation. This is a somewhat complicated topic involving your Active Directory set-up and your IIS configuration. Have a look at [this article](http://msdn.microsoft.com/en-us/library/ms998351.aspx), it should give you a good place to start.
C# 3.5 ASP.net File IO issue, UnauthorizedAccessException to file on network share
[ "", "c#", "asp.net", "visual-studio-2008", "security", "file-io", "" ]
How can I select all textboxes and textareas, e.g: ``` <input type='text' /> ``` and ``` <textarea></textarea> ``` on a page and have the property `style.width="90%";` applied to them?
``` $('input[type=text], textarea').css({width: '90%'}); ``` That uses standard CSS selectors, jQuery also has a set of pseudo-selector filters for various form elements, for example: ``` $(':text').css({width: '90%'}); ``` will match all `<input type="text">` elements. See [Selectors documentation](http://docs.jquery.com/Selectors) for more info.
Password boxes are also textboxes, so if you need them too: ``` $("input[type='text'], textarea, input[type='password']").css({width: "90%"}); ``` and while file-input is a bit different, you may want to include them too (eg. for visual consistency): ``` $("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"}); ```
How to select all textareas and textboxes using jQuery?
[ "", "javascript", "jquery", "" ]
Using Linq To XML, how can I get the space\_id value (720) from the xml below? I am reading [this](http://msdn.microsoft.com/en-us/library/bb308960.aspx) but I think the namespace in the xml is my stumbling block. ``` <r25:spaces xmlns:r25="http://www.collegenet.com/r25" pubdate="2009-05-05T12:18:18-04:00"> <r25:space id="VE1QOjRhMDAyZThhXzFfMWRkNGY4MA==" crc="" status="new"> <r25:space_id>720</r25:space_id> <r25:space_name>SPACE_720</r25:space_name> <r25:max_capacity>0</r25:max_capacity> </r25:space> </r25:spaces> ``` ## EDIT Here's where I am: ``` private int GetIDFromXML(string xml) { XDocument xDoc = XDocument.Parse(xml); // hmmm.... } ```
You can also go with (slight variation of the code above which I think is a bit more readable) ``` XNamespace ns = "http://www.collegenet.com/r25"; string id = doc.Descendants(ns.GetName("space_id").Single().Value; ```
If you just want the sole `space_id` element, with no querying etc: ``` XNamespace ns = "http://www.collegenet.com/r25"; string id = doc.Descendants(ns + "space_id") .Single() .Value; ``` (Where `doc` is an `XDocument` - or an `XElement`).
How to get elements value with Linq To XML
[ "", "c#", ".net", "xml", "linq", "linq-to-xml", "" ]
After writing out some processed content to an output stream, I need to revisit the beginning of the stream and write out some content metadata. The data I'm writing is very large, as much as 4Gb, and may be written either directly to a file or to an in-memory buffer, depending on various environmental factors. How can I implement an OutputStream that allows me to write out headers after completing the writing of content?
Here's a random access file output stream. Note that if using it for a large amount of streamed output you can temporarily wrap it in a BufferedOutputStream to avoid lots of small writes (just be very sure to flush it before discarding the wrapper or using the underlying stream directly). ``` import java.io.*; /** * A positionable file output stream. * <p> * Threading Design : [x] Single Threaded [ ] Threadsafe [ ] Immutable [ ] Isolated */ public class RandomFileOutputStream extends OutputStream { // ***************************************************************************** // INSTANCE PROPERTIES // ***************************************************************************** protected RandomAccessFile randomFile; // the random file to write to protected boolean sync; // whether to synchronize every write // ***************************************************************************** // INSTANCE CONSTRUCTION/INITIALIZATON/FINALIZATION, OPEN/CLOSE // ***************************************************************************** public RandomFileOutputStream(String fnm) throws IOException { this(fnm,false); } public RandomFileOutputStream(String fnm, boolean syn) throws IOException { this(new File(fnm),syn); } public RandomFileOutputStream(File fil) throws IOException { this(fil,false); } public RandomFileOutputStream(File fil, boolean syn) throws IOException { super(); File par; // parent file fil=fil.getAbsoluteFile(); if((par=fil.getParentFile())!=null) { IoUtil.createDir(par); } randomFile=new RandomAccessFile(fil,"rw"); sync=syn; } // ***************************************************************************** // INSTANCE METHODS - OUTPUT STREAM IMPLEMENTATION // ***************************************************************************** public void write(int val) throws IOException { randomFile.write(val); if(sync) { randomFile.getFD().sync(); } } public void write(byte[] val) throws IOException { randomFile.write(val); if(sync) { randomFile.getFD().sync(); } } public void write(byte[] val, int off, int len) throws IOException { randomFile.write(val,off,len); if(sync) { randomFile.getFD().sync(); } } public void flush() throws IOException { if(sync) { randomFile.getFD().sync(); } } public void close() throws IOException { randomFile.close(); } // ***************************************************************************** // INSTANCE METHODS - RANDOM ACCESS EXTENSIONS // ***************************************************************************** public long getFilePointer() throws IOException { return randomFile.getFilePointer(); } public void setFilePointer(long pos) throws IOException { randomFile.seek(pos); } public long getFileSize() throws IOException { return randomFile.length(); } public void setFileSize(long len) throws IOException { randomFile.setLength(len); } public FileDescriptor getFD() throws IOException { return randomFile.getFD(); } } // END PUBLIC CLASS ```
If you know the size of the header, you can write a blank header initially, then go back to fix it up with `RandomAccessFile` at the end. If you don't know the size of the header then you have a fundamental that filesystems generally don't allow you to insert data. So you need to write to a temporary file and then write the real file.
How can I implement an OutputStream that I can rewind?
[ "", "java", "io", "outputstream", "" ]
I'm considering implementing one or two JSR APIs. I have not yet read the entire specification (the plan is to read them as I code the implementation) but I am very familiar with them. I have read that the JSR process includes implementing a Test Compatibility Kit (TCK) for testing said JSR implementations. Before I start writing a bunch of unit tests to verify the correctness/completeness of my implementation I would really like to use this TCK but I have no idea if it is available for me. After downloading all files and googling around I could not find anything that could be defined as a TCK for the given JSR. So my question is basically: What steps do I need to do in order to produce my own implementation of a JSR spec and how do I verify that I have indeed done so. For what it's worth, I am considering implementing JSR-168 and JSR-286, but I think that is not relevant for this question.
What you may need to do, is to contact the spec lead for the given JSR. They can give you more information on obtaining a TCK. It may be that you have to pay a license to obtain access to the TCK. Certainly with the Java SE specification, Sun does indeed charge a license fee for the TCK, unless you qualify as a non-profit organization to receive it for free. That said, I believe it varies from JSR to JSR, so as I said above, the best bet is to contact the JSR spec lead.
Wow, this is a very ambitious project, usually taken over by companies or big open source teams. If you are determined enough to do it, I recommend that you have a look at some open source implementations. The mentioned JSRs are implemented by [Pluto](http://portals.apache.org/pluto/). It may worth to have a look at the source distribution.
How to implement a JSR Specification
[ "", "java", "specifications", "portlet", "jsr168", "jsr", "" ]
I heard somewhere that Microsoft will be focusing their efforts on C# rather than C++ for the .NET platform. I can see signs of this being true because of the GUI designer that was available for C# but not C++. So I would like to know if C++ in .NET is dying and if it will continue to be second to C# in the future.
If you are targeting the .NET framework in application development then yes C++/CLI is a second class citizen compared to C#. C# was specifically designed as *the* language for .NET framework meanwhile C++/CLI extension is there to allow developers to bridge native and managed code. However do not confuse C++ with C++/CLI (C++ .NET is the same thing...). C++ is alive and well in areas such as the kernel, games, high-performance and server apps (e.g. SQL server) all of which are unlikely to change. On the other hand most .NET 'GUI stuff' won't use C++.
Managed C++ never really got to be what MS thought it would be. C# could do (nearly) the same thing, with a lot more intuitive and user-friendly syntax. Apart from that, C++/CLI will not be left unsupported for a long time, as it's the easy way to create interop between .NET assemblies and native C++ assemblies. That's about all it's used for though (I'm sure there's a 0.001% of C++/CLI developers out there who disagree :P ).
Is C++ .NET dying?
[ "", "c#", ".net", "c++-cli", "" ]
Does anyone know if there is a quicker way of editing a record that has foreign keys in a table (in sql server).. i will explain.. i have approx 5 tables that have there own ID but are linked together using a foreign key... Hence i needed to change the foreign key (the contract number in my case), but i had to copy each record to a new record and edit it that way... As if i try to edit the contract number it gives me the standard error of being associated and violates a foreign key etc Surly there must be a better way? ANy ideas?
are you talking about changing the PK and then updating all the Fks? In that case enable cascade updates and this will be done automagically same with deletes, you enable cascade deletes ON DELETE CASCADE Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are also deleted. If cascading referential actions have also been defined on the target tables, the specified cascading actions are also taken for the rows deleted from those tables. ON UPDATE CASCADE Specifies that if an attempt is made to update a key value in a row, where the key value is referenced by foreign keys in existing rows in other tables, all of the foreign key values are also updated to the new value specified for the key. If cascading referential actions
I'm not an SQL expert, but can't you set something like ON UPDATE CASCADE to automatically update the foreign key when the primary key is changed?
Changing a record in a table (sql server) that has foreign keys?
[ "", "sql", "sql-server", "database", "foreign-keys", "" ]
My question is best illustrated with an example. Suppose I have the enum: ``` public enum ArrowDirection { North, South, East, West } ``` I want to associate the unit vector corresponding to each direction with that direction. For example I want something that will return (0, 1) for North, (-1, 0) for West, etc. I know in Java you could declare a method inside the enum which could provide that functionality. My current solution is to have a static method -- inside the class that defines the enum -- that returns a vector corresponding to the passed in ArrowDirection (the method uses a HashTable to accomplish the lookup but that's not really important). This seems... unclean. Question: **Is there a best-practice solution for storing additional information corresponding to an enum in .NET?**
There's a FANTASTIC new way to do this in C# 3.0. The key is this beautiful fact: Enums can have extension methods! So, here's what you can do: ``` public enum ArrowDirection { North, South, East, West } public static class ArrowDirectionExtensions { public static UnitVector UnitVector(this ArrowDirection self) { // Replace this with a dictionary or whatever you want ... you get the idea switch(self) { case ArrowDirection.North: return new UnitVector(0, 1); case ArrowDirection.South: return new UnitVector(0, -1); case ArrowDirection.East: return new UnitVector(1, 0); case ArrowDirection.West: return new UnitVector(-1, 0); default: return null; } } } ``` Now, you can do this: ``` var unitVector = ArrowDirection.North.UnitVector(); ``` Sweet! I only found this out about a month ago, but it is a very nice consequence of the new C# 3.0 features. [Here's another example on my blog.](http://charlieflowers.wordpress.com/2009/04/01/c-delights-you-can-put-extension-methods-onto-enums/)
I've blogged about it [here](http://www.gigpeppers.com/blog/2008/07/06/enum-attributes/). Try out something like this with [Attributes](http://msdn.microsoft.com/en-us/library/aa288059(VS.71).aspx). ``` public enum Status { [Status(Description = "Not Available")] Not_Available = 1, [Status(Description = "Available For Game")] Available_For_Game = 2, [Status(Description = "Available For Discussion")] Available_For_Discussion = 3, } public class StatusEnumInfo { private static StatusAttribute[] edesc; public static String GetDescription(object e) { System.Reflection.FieldInfo f = e.GetType().GetField(e.ToString()); StatusEnumInfo.edesc = f.GetCustomAttributes(typeof(StatusAttribute), false) as StatusAttribute[]; if (StatusEnumInfo.edesc != null && StatusEnumInfo.edesc.Length == 1) return StatusEnumInfo.edesc[0].Description; else return String.Empty; } public static object GetEnumFromDesc(Type t, string desc) { Array x = Enum.GetValues(t); foreach (object o in x) { if (GetDescription(o).Equals(desc)) { return o; } } return String.Empty; } } public class StatusAttribute : Attribute { public String Description { get; set; } } public class Implemenation { public void Run() { Status statusEnum = (Status)StatusEnumInfo.GetEnumFromDesc(typeof(Status), "Not Available"); String statusString = StatusEnumInfo.GetDescription(Status.Available_For_Discussion); } } ``` Instead of *Description*, use your custom Property
Associating Additional Information with .NET Enum
[ "", "c#", ".net", "enums", "" ]
I was looking at a library a person has made for FaceBook in C++. The header file is this: ``` #ifndef __FACEBOOK_H__ #define __FACEBOOK_H__ /** * Facebook Class * Joel Seligstein * Last mod: Aug 22, 2006 * * This is the beginnings of a facebook class set and REST client. Its not documented * yet nor nearly complete. But this is a release to demonstrate its usefulness. * Please email joel@seligstein.com with suggestions or additions. * * TODO: Create classes/parsers for each request type * TODO: Linux URL launcher */ //uncomment to have verbose output turned on //#define fb_debug 1 //define which platform you're compiling for #define fb_windows 1 //#define fb_linux 1 #include <string> #include <sstream> #include <list> using namespace std; #ifdef fb_windows #include <windows.h> #endif #include "curl/curl.h" #include "xmlParser/xmlParser.h" #include "md5.h" class facebook { public: //app/session vars string api_key; string secret; string token; string server; string session_key; string session_secret; string uid; bool has_session; facebook( string my_key, string my_secret, string my_server ); bool authenticate( ); bool request( string method, list<string> params, string *res ); bool load_token( ); void launch_login( string url ); bool get_session( ); void clean_up( ); private: //curl info CURL *curl; CURLcode res; int call_id; //internal functions string get_signature( list<string> params ); static string md5( string str ); static string get_param_string( list<string> params, bool separate ); static size_t write_callback( void *ptr, size_t size, size_t nmemb, void *userp ); }; #endif //__FACEBOOK_H__ ``` Then inside the cpp file, my question is regarding this, the below is the constructor: ``` facebook::facebook( string my_key, string my_secret, string my_server ) { this->api_key = my_key; this->secret = my_secret; this->server = my_server; this->has_session = false; this->call_id = 0; } ``` Why have they used the `->` operator and not `.`? I have a limited understanding that `->` accesses properties and methods of the type directly in memory but I am confused, I would, through ignorance, expect to see: ``` facebook::facebook( string my_key, string my_secret, string my_server ) { this.api_key = my_key; this.secret = my_secret; this.server = my_server; this.has_session = false; this.call_id = 0; } ``` All I want to know is the theory behind why `->` is used over the dot notation. --- **UPDATE: For anyone else in the same boat as me and learning C++. I have expanded on an example posted by a member in this question. I have also wrapped in initialization list for a member field.** ``` #include "stdafx.h" #include <iostream> using namespace std; class A { private: int x; public: A() : x(0){} int getX() const {return x;} void setX(int xx) {x += xx;} }; int main() { A a; a.setX(13); A *pa = &a; pa->setX(2); A b = a; b.setX(5); cout << "a" << a.getX() << endl; cout << "a*" << pa->getX() << endl; cout << "b" << b.getX() << endl; return 0; } ```
`this` is a *pointer* to the current object i.e., inside methods (or constructor) of `class A`, `this` is of type `A *`. (Note that, if the method is tagged as `const`, `this` is of type `A const *`.) Hence the use of `->` (designed only for pointers) and not `.` (designed only for class objects `A` or references to class objects `A&`).
In C++, `this` is a pointer to the self object. It's a relic leftover from early versions of C++, before it had references. If `this` were added to the language now, it probably would be a reference, for which you'd use the `.` notation.
Why do we use 'this->' and not 'this.' to access members?
[ "", "c++", "visual-c++", "" ]
I need to figure out how to communicate between ViewModels. I'm new to MVVM so please be kind. Here's a dumbed down example class definitions(assume that I have hooked the Child.PropertyChanged event in the ParentViewModel): ``` public class ParentViewModel : ViewModelBase { public ChildViewModel Child { get; set; } } public class ChildViewModel : ViewModelBase { String _FirstName; public String FirstName { get { return _FirstName; } set { _FirstName = value; OnPropertyChanged("FirstName"); } } } ``` Here's what you see in the resource dictionary ``` <DataTemplate DataType="{x:Type vm:ParentViewModel}"> <vw:ParentView/> </DataTemplate> <DataTemplate DataType="{x:Type vm:ChildViewModel}"> <vw:ChildView/> </DataTemplate> ``` and the code-behind of the ChildView: ``` public partial class ChildView : UserControl { public QueueView() { InitializeComponent(); DataContext = new ChildViewModel(); } } ``` The obvious problem is that when the ChildView gets instantiated (via selection from the DataTemplate) it creates a new ChildViewModel class and the ParentViewModel doesn't have access to it. So how can I instantiate the DataContext of the View to be the original ViewModel that caused the DataTemplate to be selected? An obvious fix is to mmerge the properties in the ChildViewModel into the ParentViewModel, but I would rather separate it because for reuse. I'm sure the answer is trivial, I just would like to know what it is. :) Thanks in advance.
You should simply remove the line: ``` DataContext = new ChildViewModel(); ``` The `DataContext` of the view will be set automatically by WPF. `DataTemplates` always have their data context set to the data for the template (in this case the ViewModel): ``` <DataTemplate DataType="{x:Type vm:ChildViewModel}"> <vw:ChildView/> </DataTemplate> ``` The end result is that you can build your view model objects separately (both parent and child classes) and then display them later by simply plugging them into content controls.
The easiest way to communicate between ViewModels using the MVVM approach is to use the Mediator pattern (EventAggregator in Prism). A good example of this approach can be seen in the following links: 1. [MVVM Mediator Pattern by Sacha Barber](http://sachabarber.net/?p=477) 2. [MVVM + Mediator by marlon grech](http://marlongrech.wordpress.com/2009/04/08/mvvm-mediator-acb-cool-wpf-app-the-mvvm/) Also check out the MVVM [sample](http://blogs.msdn.com/llobo/archive/2009/05/01/download-m-v-vm-project-template-toolkit.aspx) project framework.
MVVM Pattern, ViewModel DataContext question
[ "", "c#", "wpf", "mvvm", "viewmodel", "datacontext", "" ]
I have an application in PHP/MySQL. I am searching for an automated way upgrading database behind the application. I don't need to have the compatibility with older versions once it is upgraded. I have read [jeff's](https://blog.codinghorror.com/get-your-database-under-version-control/) and [K. Scott Allen's](http://odetocode.com/Blogs/scott/archive/2008/02/03/11746.aspx) articles on this. I am still not sure how to implement this for a PHP/MySQL application. Is there any simple and good process for this?
I have a "Schema" object that I use - but you could do the same without classes.. What you want to do is create a '`db_schema_versions`' table: ``` CREATE TABLE db_schema_versions ( `table` varchar(255) NOT NULL PRIMARY KEY, `version` INT NOT NULL ) ``` After your database can track what version # it is on - it can do SQL upgrades automatically. You should lock your schema table while upgrading schema. This way you wont have two requests at the same moment trying to upgrade your schema. So - keep track of the version you are upgrading from - build a big switch - something like this: ``` class SNTrack_Db_Schema extends MW_Db_Schema_Abstract { protected $table = "sntrack_db_schema"; protected $version = 5; protected function upgrade($fromVersion) { // don't break switch($fromVersion) { case 0: $this->db->query('CREATE TABLE sntrack_inbound_shipment ( `id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT, `from` VARCHAR(255) NOT NULL, `date` DATE NOT NULL, `invoice` VARCHAR(255) NOT NULL, `notes` TEXT )'); $this->setVersion(1); case 1: $this->db->query('ALTER TABLE sntrack_details ADD `shipment_id` INT'); $this->db->query('ALTER TABLE sntrack_product ADD `inventory` INT NOT NULL DEFAULT 0'); $this->db->query('CREATE TABLE sntrack_inventory_shipment ( `shipment_id` INT NOT NULL, `product_id` INT NOT NULL, `qty` INT NOT NULL, PRIMARY KEY (`shipment_id`, `product_id`) )'); $this->setVersion(2); ...etc ```
Try to use this tool for schema migration: <https://github.com/idler/MMP/>
How to automate migration (schema and data) for PHP/MySQL application
[ "", "php", "mysql", "deployment", "migration", "" ]
I want to create a c++ application that works together with a website. In order to keep the application synchronized with the website I want to be able to read some cookies from the user's default browser. Is there any way to do this?
Not in the general sense - there's no real defined format for cookie storage, so each browser is free to keep the cookie database wherever, and in whatever style, it prefers. You could implement cookie reading functions for the mainstream browsers (IE, Firefox), but that would leave some people out. It would also be non-robust - what happens when the user clears their cookie cache, or uses more than one browser? If you want to keep your application synchronised with a website, I'd recommend that you have it call directly into web services (RESTful, etc) on that site, with a username/identifier your application users configure. This way, you're not tied to an arbitrary 3rd party that is, at best, only "maybe" right.
Yes, fairly trivial. Define a webservice <http://example.com/capturecookie>?*tracking-guid*. It returns the cookie sent the last time for that GUID. From you application, pick a random guid. Call that webservice with your random GUID first in the default browser (See other S.O. topics for that) and then with the same GUID from inside your application. The second time, you'll get back the cookies from the first. Note that the exact notion of "cookies of a webbrowser" is necessarily imprecise. For instance, my default webbrowser (Opera) is set to drop all cookies when it exists, except cookies from whitelisted sites. So whether example.com has cookies depends a lot on whether Opera is running.
Reading cookies from default browser in C++
[ "", "c++", "browser", "" ]
I use onLongClick and onClick events of a button to get user inputs. Whenever; the user long click and triggers onLongClick event, the onClick event is also triggered. I couldn't find my problem. The code of two methods are shown in below: ``` @Override public void onClick(View v) { switch(((Button) v).getId()) { case R.id.enter: EntertheNumber(); break; case R.id.clear: CleartheNumber(); break; case R.id.number_zero: case R.id.number_one: case R.id.number_two: case R.id.number_three: case R.id.number_four: case R.id.number_five: case R.id.number_six: case R.id.number_seven: case R.id.number_eight: case R.id.number_nine: AddtotheNumber(mEditor, (Button) v); break; } @Override public boolean onLongClick(View view) { if(SMBGuesstheNumber.bDisplayFlagList) { theActiveButton = (Button) view; showDialog(R.id.display_flaglist); } return false; } ``` Actually, my project is Open Source. So, you can find all the code at <http://code.google.com/p/guessthenumber/> Thank you.
I'm not sure what order these events occur but the onLongClick handler returns a bool to indicate whether the event was handled. You should return true if you handled it so that other click events will not be called. I don't know if this will prevent prevent the onClick() from firing though. You may also turn these events off and on using setClickable(boolean) and setLongClickable(boolean) You can find this information and more about UI events [here](http://developer.android.com/guide/topics/ui/ui-events.html).
here is a brief summary regarding touch event: <http://rxwen.blogspot.com/2010/10/android-touch-event-summary.html>
LongClick event also triggers Click event
[ "", "java", "android", "events", "event-handling", "" ]
I have to begin a medium-sized project in Java, but I'm not a big fan of ORMs in general so the question is: Should I design the project with an ORM in mind (for later use) or not? The RDBMS is Oracle 10g and the queries will be *very* coupled to Oracle syntax/functions (i.e. text, mining, CONNECT BY, etc...). Thanks a lot.
You might want to look at this earlier question which discusses the benefit of ORMs: [What are the advantages of using an ORM?](https://stackoverflow.com/questions/398134/what-are-the-advantages-of-using-an-orm/398182) The most relevant part (taken from the accepted answer): > If you have complex, hand-tuned SQL, > there's not much point in using an > ORM. If you are constantly reaching past the ORM and writing your own SQL, the ORM might just end up getting in the way.
Since Im not allowed to comment your post Ill comment like this(lack of points). Would be good for the discussion WHY you dont like ORM. Imo, I would go for it. And if you for some reason find a query that is slow by the ORM, then I would make it myself. Just because you use an ORM most of your tasks does not mean you have to use it for all. But yes, it would be preferred.
ORM: Yes or no?
[ "", "java", "orm", "" ]
I'm using the Google Maps API and have added markers. Now I want to add a 10 mile radius around each marker, meaning a circle that behaves appropriately while zooming. I have no idea how to do that and it seems it's not something common. [I found one example that looks good](http://www.freemaptools.com/radius-around-point.htm), and you can have a look at Google Latitude, too. There they use markers with a radius, just like I want them. ~~**Update:** Google Latitude uses [an image](http://www.google.com//ig/modules/friendview/fv_content/purple_circle.png) that is scaled, how would that work?~~ (feature deprecated)
Using the Google Maps API V3, create a Circle object, then use bindTo() to tie it to the position of your Marker (since they are both google.maps.MVCObject instances). ``` // Create marker var marker = new google.maps.Marker({ map: map, position: new google.maps.LatLng(53, -2.5), title: 'Some location' }); // Add circle overlay and bind to marker var circle = new google.maps.Circle({ map: map, radius: 16093, // 10 miles in metres fillColor: '#AA0000' }); circle.bindTo('center', marker, 'position'); ``` You can make it look just like the Google Latitude circle by changing the fillColor, strokeColor, strokeWeight etc ([full API](http://code.google.com/apis/maps/documentation/javascript/reference.html#Circle)). See more [source code and example screenshots](http://seriouscodage.blogspot.com/2010/11/visualizing-data-as-circles-in-google.html).
It seems that the most common method of achieving this is to draw a [GPolygon](http://code.google.com/apis/maps/documentation/reference.html#GPolygon) with enough points to simulate a circle. The example you referenced uses this method. [This page](http://esa.ilmari.googlepages.com/circle.htm) has a good example - look for the function *drawCircle* in the source code.
Draw radius around a point in Google map
[ "", "javascript", "google-maps", "geometry", "drawing", "" ]
Basically I wanna know if all the types in a particular namespace implements a particular interface like `IEnumerable`. I know I can do: ``` foreach type ... if type is IEnumerable ... ``` But I don't wanna cast the type just to query if it implements an interface, because the cast will be thrown away either way.
Using the **is** operator is not a cast, it is a test, which sounds like what you want. Type casting in C# is done either using the forced casting operator (name?) like so: ``` ((IEnumerable)someCollection) ``` or the safe casting operator: ``` someCollection as IEnumerable ```
Assuming I've read you correctly, you want a list of types in an enumeration that implement an particular interface or supertype. Perhaps [Enumerable.OfType(this IEnumerable source)](http://msdn.microsoft.com/en-us/library/bb360913.aspx) is useful? ``` var enumerables = myListOfThingsToCheck.OfType<IEnumerable>(); ```
Collecting types that implement a particular interface without casting?
[ "", "c#", ".net", "interface", "" ]
In order to allow only a single instance of an application running I'm using mutex. The code is given below. Is this the right way to do it? Are there any flaws in the code? How to show the already running application when user tries to open the application the second time. At present (in the code below), I'm just displaying a message that another instance is already running. ``` static void Main(string[] args) { Mutex _mut = null; try { _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName); } catch { //handler to be written } if (_mut == null) { _mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName); } else { _mut.Close(); MessageBox.Show("Instance already running"); } } ```
I did it this way once, I hope it helps: ``` bool createdNew; Mutex m = new Mutex(true, "myApp", out createdNew); if (!createdNew) { // myApp is already running... MessageBox.Show("myApp is already running!", "Multiple Instances"); return; } ```
``` static void Main() { using(Mutex mutex = new Mutex(false, @"Global\" + appGuid)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } GC.Collect(); Application.Run(new Form1()); } } ``` Source : <http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx>
Run single instance of an application using Mutex
[ "", "c#", "mutex", "" ]
I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it? I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running. How can i check (using python) if my script is running?
Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up. ``` #/usr/bin/env python import os import sys pid = str(os.getpid()) pidfile = "/tmp/mydaemon.pid" if os.path.isfile(pidfile): print "%s already exists, exiting" % pidfile sys.exit() file(pidfile, 'w').write(pid) try: # Do some actual work here finally: os.unlink(pidfile) ``` Then you can check to see if the process is running by checking to see if the contents of /tmp/mydaemon.pid are an existing process. Monit (mentioned above) can do this for you, or you can write a simple shell script to check it for you using the return code from ps. ``` ps up `cat /tmp/mydaemon.pid ` >/dev/null && echo "Running" || echo "Not running" ``` For extra credit, you can use the atexit module to ensure that your program cleans up its pidfile under any circumstances (when killed, exceptions raised, etc.).
A technique that is handy on a Linux system is using domain sockets: ``` import socket import sys import time def get_lock(process_name): # Without holding a reference to our socket somewhere it gets garbage # collected when the function exits get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: # The null byte (\0) means the socket is created # in the abstract namespace instead of being created # on the file system itself. # Works only in Linux get_lock._lock_socket.bind('\0' + process_name) print 'I got the lock' except socket.error: print 'lock exists' sys.exit() get_lock('running_test') while True: time.sleep(3) ``` It is atomic and avoids the problem of having lock files lying around if your process gets sent a SIGKILL You can [read in the documentation for `socket.close`](https://docs.python.org/2/library/socket.html#socket.socket.close) that sockets are automatically closed when garbage collected.
Check to see if python script is running
[ "", "python", "process", "daemon", "" ]
I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language. What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic language? I understand that at a low level they would not cut it but C or C++ would be fine for that and Python, for example, could be the layer on top to interact with it. I mean, there is Jython or CPython. I was just wondering why we do not see more dynamic language support in today's mobile OS's.
In general it's all of these things. Memory, speed, and probably most importantly programmer familiarity. Apple has a huge investment in Objective C, Java is known by basically everyone, and C# is very popular as well. If you're trying for mass programmer appeal it makes sense to start with something popular, even if it's sort of boring. There aren't really any technical requirements stopping it. We could write a whole Ruby stack and let the programmer re-implement the slow bits in C and it wouldn't be that big of a deal. It would be an investment for whatever company is making the mobile OS, and at the end of the day I'm not sure they gain as much from this. Finally, it's the very beginning of mobile devices. In 5 years I wouldn't be at all surprised to see a much wider mobile stack.
Contrary to the premise of the question: One of the first mainstream mobile devices was the [Newton](http://en.wikipedia.org/wiki/Apple_Newton), which was designed to use a specialized dynamic language called [NewtonScript](http://en.wikipedia.org/wiki/NewtonScript) for application development. The Newton development environment and language made it especially easy for applications to work together and share information - almost the polar opposite of the current iPhone experience. Although many developers writing new Newton applications from scratch liked it a lot - NewtonScript "feels" a lot like Ruby - the Newton had some performance issues and porting of existing code was not easy, even after Apple later added the ability to incorporate C code into a NewtonScript program. Also, it was very hard to protect one's intellectual property on the Newton - other developers could in most cases look inside your code and even override bits of it at a whim - a security nightmare. **The Newton was a commercial failure.** Palm took a few of Apple's best ideas - and improved upon them - but tossed dynamic language support as part of an overall simplification that eventually led to PalmOS gaining a majority of the mobile market share (for many years) as independent mobile software developers flocked to the new platform. There were many reasons *why* the Newton was a failure, but some probably blame NewtonScript. Apple is "thinking different" with the iPhone, and one of the early decisions they seem to have made is to leverage as much as possible off their existing core developer base and make it easy for people to develop in Objective C. If iPhone gets official support for dynamic languages, that will be a later addition after long and careful consideration about how best to do it while still providing a secure and high-performance platform. And 5 minutes after they do, others will follow. :-)
Python/Ruby as mobile OS
[ "", "python", "ruby", "mobile", "operating-system", "dynamic-languages", "" ]
I have a (for me) complex object with about 20 data member, many of which are pointer to other classes. So for the constructor, I have a big long, complex initialization list. The class also has a dozen different constructors, reflecting the various ways the class can be created. Most of these initialized items are unchanged between each of these different constructors. My concern here is that I now have a large chuck of copied (or mostly copied) code which, if I need to add a new member to the class, may not make it into each of the constructor initialization lists. ``` class Object { Object(); Object(const string &Name); Object (const string &Name, const string &path); Object (const string &Name, const bool loadMetadata); Object (const string &Name, const string &path, const bool loadMetadata); } Object::Object() : name(), parent_index (0), rowData (new MemoryRow()), objectFile (), rows (new MemoryColumn (object_constants::RowName, OBJECTID, object_constants::ROWS_OID)), cols (new MemoryColumn (object_constants::ColName, OBJECTID, object_constants::COLS_OID)), objectName (new MemoryColumn(object_constants::ObjName, STRING, object_constants::short_name_len, object_constants::OBJECTNAME_OID)), parent (new MemoryColumn(object_constants::ParentName, STRING, object_constants::long_name_len, object_constants::PARENT_OID)), parentIndex (new MemoryColumn(object_constants::ParentIndex, OBJECTID, object_constants::PARENTINDEX_OID)), childCount (new MemoryColumn (object_constants::ChildCount, INTEGER, object_constants::CHILD_COUNT_OID)), childList (new MemoryColumn (object_constants::ChildList, STRING, object_constants::long_name_len, object_constants::CHILD_OID)), columnNames (new MemoryColumn (object_constants::ColumnNames, STRING, object_constats::short_name_len, object_constants::COLUMN_NAME)), columnTypes (new MemoryColumn (object_constants::ColumnTypes, INTEGER, object_constants::COLUMN_TYPE)), columnSizes (new MemoryColumn (object_constants::ColumnSizes, INTEGER, object_constants::COLUMN_SIZE)) {} ``` Then repeat as above for the other constructors. Is there any smart way of using the default constructor for this, then modifying the results for the other constructors?
How about refactor the common fields into a base class. The default constructor for the base class would handle initialization for the plethora of default fields. Would look something like this: ``` class BaseClass { public: BaseClass(); }; class Object : public BaseClass { Object(); Object(const string &Name); Object (const string &Name, const string &path); Object (const string &Name, const bool loadMetadata); Object (const string &Name, const string &path, const bool loadMetadata); }; BaseClass::BaseClass() : parent_index (0), rowData (new MemoryRow()), objectFile (), rows (new MemoryColumn (object_constants::RowName, OBJECTID, object_constants::ROWS_OID)), cols (new MemoryColumn (object_constants::ColName, OBJECTID, object_constants::COLS_OID)), objectName (new MemoryColumn(object_constants::ObjName, STRING, object_constants::short_name_len, object_constants::OBJECTNAME_OID)), parent (new MemoryColumn(object_constants::ParentName, STRING, object_constants::long_name_len, object_constants::PARENT_OID)), parentIndex (new MemoryColumn(object_constants::ParentIndex, OBJECTID, object_constants::PARENTINDEX_OID)), childCount (new MemoryColumn (object_constants::ChildCount, INTEGER, object_constants::CHILD_COUNT_OID)), childList (new MemoryColumn (object_constants::ChildList, STRING, object_constants::long_name_len, object_constants::CHILD_OID)), columnNames (new MemoryColumn (object_constants::ColumnNames, STRING, object_constats::short_name_len, object_constants::COLUMN_NAME)), columnTypes (new MemoryColumn (object_constants::ColumnTypes, INTEGER, object_constants::COLUMN_TYPE)), columnSizes (new MemoryColumn (object_constants::ColumnSizes, INTEGER, object_constants::COLUMN_SIZE)) {} ``` Your Object constructors should look a little more manageable, now: ``` Object::Object() : BaseClass() {} Object::Object (const string &Name): BaseClass(), name(Name) {} Object::Object (const string &Name, const string &path): BaseClass(), name(Name), path_(path){} Object::Object (const string &Name, const bool loadMetadata): BaseClass(), name(Name){} Object::Object (const string &Name, const string &path, const bool loadMetadata): BaseClass(), path_(path) {} ``` Similar in nature to Iraimbilanja's answer, but avoids adding an inner-class for accessing data, which might impact a lot of existing code. If you've already got a class hierarchy, though, it may be difficult to factor it into a base class.
Now a couple of years later we have C++ 11. If you can use it in your project you have two options: When the common initialization values are only known at runtime you can use delegating constructors, which means one constructor calls another. ``` // function that gives us the init value at runtime. int getInitValue(); class Foo { const int constant; int userSet; public: // initialize long member list with runtime values Foo() : constant(getInitValue()) , userSet(getInitValue()) {} // other constructors with arguments Foo( int userSetArg) : Foo() , userSet(userSetArg) { } }; ``` or you can initialize the members directly in the class definition if their values are known at compile time. ``` class Foo { const int constant = 0; int userSet = 0; public: Foo( int userSetArg) : userSet(userSetArg){} } ```
Handling a class with a long initialization list and multiple constructors?
[ "", "c++", "constructor", "initialization", "" ]
I have a rather annoying issue that I solved using a simple recursive method in Java. However, I'm looking for a better way to do this. The initial problem involved the presence of whitespace within a Quoted Printable/Base64 encoded Mime header - which as I read the RFC 2047 specification - isn't allowed. This means that decoding fails for a MIME header when whitespace is present, e.g. ``` =?iso-8859-1?Q?H=E4 ll and nothing?= ``` or more pertinently: ``` =?iso-8859-1?Q?H=E4 ll?= preserve this text =?iso-8859-1?Q?mo nk ey?= ``` The goal is to only remove the whitespace between the =? ?= boundaries (or re-encode using =20). Other text outside this should be preserved. I'm looking for alternative approaches to solving this my target language for this is Java. Any ideas on the simplest, cleanest approach to this?
You could build a simple state machine to track if you are between =? and ?= , then read the input char by char and output it char by char converting whitespaces when needed...
Regular expressions <http://java.sun.com/docs/books/tutorial/essential/regex/>. \s = whitespace \S = non-whitespace \? = escaped question mark . = all characters, similar to \* in weaker pattern matching. Might be easiest to do a multi-part find and replace using something like this: Pull out this part: =\?.\?= Globally replace \s in that part with empty string. Put the part back. You might be able to get it down to a single search and replace if you play with the regex long enough...
Replace an Expression Within Text Boundaries
[ "", "java", "email", "text", "mime", "replace", "" ]
I'm using C# (.Net 2.0), and I have a fairly large text file (~1600 lines on average) that I need to check periodically to make sure a certain line of text is there. What is the most efficient way of doing this? Do I really have to load the entire file into memory each time? Is there a file-content-search api of some sort that I could use? Thanks for any help/advice.
Well, you can always use the [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) to give you an event when the file has changed, that way you only scan the file on demand.
If the line of text is always going to be the same then using RegEx to match the text of the line is probably more efficient than looping through a file to match the text using String.Equals() or ==. That said, I don't know of anyway in c# to find text in a file with out opening the file into memory and reading the lines. This [link](http://dotnetperls.com/Content/Regex-File-Tutorial.aspx) is a nice tutorial on using RegEx to match lines in a file using c#.
Most efficient way to make sure a line exists in a plain text file
[ "", "c#", ".net", "file-io", "performance", "" ]
Once upon a time there was a class: ``` public class Scope<C extends Cloneable & Comparable<C>> implements Comparable<Scope<C>>, Cloneable, Serializable { private C starts; private C ends; ... @SuppressWarnings("unchecked") @Override public Object clone() { Scope<C> scope; try { scope = (Scope<C>) super.clone(); scope.setStarts((C) starts.clone()); // The method clone() from the type Object is not visible scope.setEnds((C) ends.clone()); // The method clone() from the type Object is not visible } catch (CloneNotSupportedException e) { throw new RuntimeException("Clone not supported"); } return scope; } } ``` In Object we have: ``` protected native Object clone() throws CloneNotSupportedException; ``` And Cloneable interface is: ``` public interface Cloneable { } ``` How should I clone this?
# Solution Use the [Java Deep-Cloning](https://github.com/kostaskougios/cloning) library. *The cloning library* is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects. ``` Cloner cloner=new Cloner(); XX clone = cloner.deepClone(someObjectOfTypeXX); ``` # Addendum A previous answer had the following drawbacks: * It adds a lot of code * It requires you to list all fields to be copied and do this * This will not work for Lists when using `clone()`; the `clone()` for `HashMap` notes: *Returns a shallow copy of this `HashMap` instance: the keys and values themselves are not cloned*, so you end up doing it manually. Serialization is also bad because it may require adding `Serializable` everywhere.
This is one reason why [no one likes `Cloneable`](https://stackoverflow.com/questions/709380/java-rationale-of-the-cloneable-interface). It's supposed to be a marker interface, but it's basically useless because you can't clone an arbitrary `Cloneable` object without reflection. Pretty much the only way to do this is to create your own interface with a *public* `clone()` method (it doesn't have to be called "`clone()`"). [Here's an example](https://stackoverflow.com/questions/240774/mandatory-cloneable-interface-in-java/240895#240895) from another StackOverflow question.
Cloning with generics
[ "", "java", "clone", "" ]
I'm not sure how to modify the CustomRules.js file to only show requests for a certain domain. Does anyone know how to accomplish this?
This is easy to do. On the filters tab, click "show only if the filter contains, and then key in your domain. ![enter image description here](https://i.stack.imgur.com/HRoUS.png)
**edit** Turns out it is quite easy; edit `OnBeforeRequest` to add: ``` if (!oSession.HostnameIs("www.google.com")) {oSession["ui-hide"] = "yup";} ``` filters to google, for example. --- (original answer) I honestly don't know if this is something that Fiddler has built in (I've never tried), but it is certainly something that [Wireshark](http://www.wireshark.org/) will do pretty easily - of course, you get different data (in particular for SSL) - so YMMV.
Filtering fiddler to only capture requests for a certain domain
[ "", "c#", ".net", "windows", "fiddler", "" ]
If I have a hello.php file like this: ``` Hello, <?php echo $foo; ?>! ``` I would like to do something like this in some php code: ``` $text = renderPhpToString('hello.php', array('foo'=>'World')); ``` and end up with ``` $text == 'Hello, World!' ``` Is this possible with standard PHP 5? Obviously I want more complex templates with loops and so forth..
You could use some function like this: ``` function renderPhpToString($file, $vars=null) { if (is_array($vars) && !empty($vars)) { extract($vars); } ob_start(); include $file; return ob_get_clean(); } ``` It uses the output buffer control function [`ob_start()`](http://docs.php.net/ob_start) to buffer the following output until it’s returned by `ob_get_clean()`. **Edit**    Make sure that you validate the data passed to this function so that `$vars` doesn’t has a `file` element that would override the passed `$file` argument value.
As Gumbo said you have to check for the $file variable, its a subtle bug that has already bitten me. I would use func\_get\_arg( i ) and have no variables at all, and a minor thing, i would use require. ``` function renderPhpToString( ) { if( is_array( func_get_arg(1) ) ) { extract( func_get_arg(1) ); } ob_start(); require func_get_arg( 0 ); return ob_get_clean(); } ```
Can you render a PHP file into a variable?
[ "", "php", "" ]
if a condition occurs i have to stop the execution of the current method call and return to the state before the method call .how can i do it .. suppose a i am executing some sample method and a condition occurs and i am prompting a message box and then i want to return to state before this function call
You can use the [Memento pattern](http://www.dofactory.com/Patterns/PatternMemento.aspx) to implement object rollback. From [here](http://en.wikipedia.org/wiki/Memento_pattern) ... > The caretaker is going to do something > to the originator, but wants to be > able to undo the change. The caretaker > first asks the originator for a > memento object. Then it does whatever > operation (or sequence of operations) > it was going to do. To roll back to > the state before the operations, it > returns the memento object to the > originator. Once you receive the event that indicates that you should roll back, you can undo the change and return to the caller. Here is some [info. and links](http://msmvps.com/blogs/peterritchie/archive/2007/08/22/thead-abort-is-a-sign-of-a-poorly-designed-program.aspx) on why you should not use Thread.Abort.
If I'm understanding you correctly, you wish to undo changes you have made to certain variables if some condition is true? If that's the case, you will want to store a copy of all your variables (or your class as a whole). Then, if your condition comes up true, you'll have to revert all those variables to their initial state before returning from your function. It would be something like this: ``` // In order to clone your variable, you may need to inherit from // ICloneable and implement the Clone function. bool MyFunction(ICloneable c) { // 1. Create a copy of your variable ICloneable clone = c.Clone(); // 2. Do whatever you want in here ... // 3. Now check your condition if (condition) { // Copy all the attributes back across to c from your clone // (You'll have to write the ResetAttributes method yourself) c.ResetAttributes(clone); // Put a message box up MessageBox.Show("This failed!"); // Now let the caller know that the function failed return false; } else { // Let the caller know that the function succeeded return true; } } ```
how to stop the execution of current method call
[ "", "c#", "" ]
I'm importing a module which raises the following error in some conditions: RuntimeError: pyparted requires root access I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?
> I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised? If the error is caused by a specific condition, then I think the easiest way to catch the error is to test for the condition, and you can raise a more specific error yourself. After all the 'error' exists before the error is thrown, since in this case its a problem with the environment. I agree with those above - text matching on an error is kind of a terrifying prospect.
You can check attributes of the exception to differentiate from other possible `RuntimeError` exceptions. For example, re-raise the error if it does not match a predefined message text. ``` try: import pypatred except RuntimeError,e: if e.message == 'RuntimeError: pyparted requires root access': return 'pyparted - no root access' raise ``` Of course, direct text comparison is just an example, you could search for included substrings or regular expressions. It is worth noting that the `.message` attribute of exceptions is [deprecated starting with Python 2.6](http://docs.python.org/dev/whatsnew/2.6.html#other-language-changes). You can find the text in `.args`, usually `args[0]`. > ... For 2.6, the `message` attribute is being deprecated in favor of the `args` attribute.
Catch only some runtime errors in Python
[ "", "python", "exception", "try-catch", "runtime-error", "" ]
I have a list of addresses contained in a parent object called Branch. Branch may or may not have these addresses defined and I need to get a flat hierarchy or these branch and address. ``` var x = from p in CurrentBranchList where p.ScheduledForDeletion == false from c in p.Addresses where c.ScheduledForDeletion == false && c.AddressTypeId == 3 select new { BranchId = p.BranchId, Name = p.Name, Address = (c == null) ? "" : c.Address1 + " " + c.Address2, City = (c == null) ? "" : c.City, State = (c == null) ? 0 : c.StateId }; ``` The above is what I tried but if the Address is missing I get no information about the Branch...I'm still trying to figure out how to get this going with Linq. In SQL I would have just left joined the two tables to get that info. Can anyone help me on this...I'm sure it's a pretty easy thing. Thanks. PS. I know this is very similar to ([[Linq query to return a flatened list of parent child](https://stackoverflow.com/questions/277634/linq-query-to-return-a-flatened-list-of-parent-child)](https://stackoverflow.com/questions/277634/linq-query-to-return-a-flatened-list-of-parent-child)) but in that one the child always exists. --- **EDIT - WORKING SOLUTION** The following is code that seemed to work for me. I can't go against a database for the source because the objects contained in the CurrentBranchList are edited in memory and persistence is performed in a single operation. ``` var x = from p in CurrentBranchList join c in CurrentBranchList.SelectMany(b => b.Addresses) on p.EntityId equals c.EntityId into ur where p.ScheduledForDeletion == false from u in ur.DefaultIfEmpty() select new { BranchId = p.BranchId, Name = p.Name, Address = (u == null) ? "" : u.Address1 + " " + u.Address2, City = (u == null) ? "" : u.City, State = (u == null) ? 0 : u.StateId }; ``` **Thank you for your help.** Those links really helped me understand what needed to happen. I also tried Daniel Brückner's solution and that appears to be more elegant and require less typing. :-) Seems to work in the couple scenarios I tried. Here's what that looks like. ``` var xx = CurrentBranchList.SelectMany(b => b.Addresses.DefaultIfEmpty().Select(a => new { BranchId = b.BranchId, Name = b.Name, Address = (a == null) ? "" : a.Address1 + " " + a.Address2, City = (a == null) ? "" : a.City, State = (a == null) ? 0 : a.StateId })); ```
``` IQueryable<Branch> branches = GetBranches(); var result = braches. SelectMany(b => b.Addresses. DefaultIfEmpty(). Select(a => new { Branch = b, Address = a })); ```
You need a left outer join rather than an inner join. [Here's how](http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx).
LINQ: Get the Parent object properties and a single child property as a flat structure
[ "", "c#", "linq", "" ]
After seeing the 13th Floor back in the day I have been obsessed to a degree with writing a simulator like that. I have written several simulations with a human base class that have a male and female subclass. They have a routine called runYear and they interact. They date, work, die, have kids, get sad, commit suicide, divorce, etc. It will run for thousands of "years" and depending on seed parameters grow very large or die off. My question is: I have really maxed out what I can do with this and I am looking to rewrite this from the ground up, but I want to have a foundation going forward. Are there any good books or articles anyone can point me to that would help me better understand how I need to design this or what key foundations I should include? On a technical point: 1. should I look at using a Object Oriented database to store this information? 2. I was planning on writing this in C#(For comfort reasons), would learning LISP be better? 3. Are there any other opensource simulators anyone has run across like this I can maybe get some ideas from Any other ideas/suggestions would be be awesome. Erik
Most complex thing about this kind of simulators is not how to implement it, but how you model your creatures, and their interactions with each other and environment. Just use those tools that you are most comfortable with. I wouldn't most likely use any kind of database in the beginning, I would use datastructures that my programming language uses and maybe write and read the datastructures to plain files when persistance is needed. Here are few links about this kind of simulations. Most of them are not human level, instead they work on a bit "lower" level, think of insects, bacteria and DNA. * [Wikipedia: Artificial Life](http://en.wikipedia.org/wiki/Artificial_life) * [Wikipedia: Life Simulation Game](http://en.wikipedia.org/wiki/Life_simulation_game) * [Wikipedia: Multi-agent Systems](http://en.wikipedia.org/wiki/Multi-agent_system) A couple of examples about existing systems: * [Breve - 3d life simulator](http://www.spiderland.org/breve/) * [Darwinbots](http://www.darwinbots.com/WikiManual/index.php?title=Main_Page) * [Creatures, a commercial artificial life game](http://en.wikipedia.org/wiki/Creatures_(artificial_life_program))
[Swarm](http://www.swarm.org/index.php/Main_Page)
Resources on human simulator design. (think 13th floor)
[ "", "c#", "simulation", "" ]
I have a class that uses functors as units of work. It accepts a reference to a functor in its Run() method. To allow this class to operate on any functor, all these functors must derive from my base functor class which looks like this: ``` class baseFunctor{ public: virtual void operator()()=0; virtual baseFunctor Clone()=0; }; ``` This works, however obviously it restricts these functors to having an operator method that returns void and accepts no parameters. I need to be able to accept a functor in my class that can take any type of parameters and return anything. Its apparently do-able but I can't seem to find a way to do it. I have considered using templates, multiple inheritance, but I keep getting thwarted by the fact that the class that needs to run this functor must be able to accept any type, so will accept the base class type, and so will not know the actual type of the functor. Any suggestions of what avenue to look at would be appreciated.
How will the class that calls the functor know what parameters to provide and what to do with the return value, if any?
If you are open to using the Boost library (www.boost.org), you might find Boot.Bind and Boost.Function of particular interest. I have used them in the past to achieve something very much along the lines of what you are discussing. If you use Boost.Bind, you can perform currying on the functors to account for differences between the number of arguments the functor expects and the number of arguments the Run method expects (i.e., zero). The code that creates the functor would have to bind any arguments to specific values and thus create a zero-argument functor that can be passed to Run(). MV
Derived Functor with any return type and any parameters
[ "", "c++", "templates", "inheritance", "functor", "" ]
I'm a bit of a Linq newbie, and I couldn't find any documentation to help me with what seems to be a pretty trivial problem - so your help will be much appreciated! I have a table `Table1` in database `DB1`, which has a "pseudo" foreign key `Table2ID` to table `Table2` in database `DB2`, on the same server. "Pseudo", because obviously I can't have an *actual* FK spanning two databases. Now I'm playing around with the O/R designer, and I love the way all the relationships are generated when I bring database objects into the designer... very cool! And I want my `Table1` object to have a relationship to `Table2`, just like it has relationships with all the "real" foreign key-related objects in `DB1`. But I can't bring `Table2` into my db diagram, because it's in the wrong DB. To synthesize this, I tried creating a view `Table2` in `DB1`, which is simply `select * from DB2..Table2`. Aha, now I can drop a `Table2` object into my diagram. I can even make a parent/child relationship between `Table1` and `Table2`. But when I look at the generated code, `Table1` still has no relationship to `Table2`, which I find most perplexing. Am I missing a step somewhere? Is there a better/recommended way of doing this? Thanks! --- ## Later... Along the lines of what one person suggested, I tried filling in the partial class of `Table1` with all the methods required to access `Table2`, by copying all the structures for a related object within the same DB. This actually worked for reads, but as soon as I tried to update or insert a record, I got an exception: `An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.` So it looks like the designers of Linq have actually thought about this scenario, and decided that you are **not allowed** to connect objects in different databases. That's really a shame... :( --- ## ... and even later... Thanks to @williammandra.com, I found that you need to create the primary key on a view manually. But there's still another problem: for some reason when you load a value from the view `Table2` and set it on the new record `Table1`, then commit changes, it tries to insert a **new** record into `Table2`, which obviously causes a PK violation. Any idea why this happens, and how to get around it?
Views don't have primary keys (without it the O/R designer can't create the relationship). Your solution to use a view gets you halfway there.... The step you are missing is setting the "Primary Key" property to true in the O/R designer for the key field in the Table2 view. You still have to create the association manually, but once you save the dbml the relationship will show up in the generated code.
You could create two dbml's, one for each db. Then join the tables in your query: ``` var tb1 = DataContext1.Table1 var tb2 = DataContext2.Table2 var result = (from t1 in tb1 join t2 in tb2 on tb1.column equals tb2.column where ... select ... ) ``` You could also set tb2 = to your view rather than another datacontext...
How do you use Linq to connect tables in different databases?
[ "", "c#", "linq", "linq-to-sql", "view", "or-designer", "" ]
I need help with a character encoding problem that I want to sort once and for all. Here is an example of some content which I pull from a XML feed, insert into my database and then pull out. As you can not see, a lot of special html characters get corrupted/broken. How can I once and for all stop this? How am I able to support all types of characters, etc.? I've tried literally every piece of coding I can find, it sometimes corrects it for most but still others are corrupted.
``` header('Content-type: text/html; charset=UTF-8') ; /** * Encodes HTML safely for UTF-8. Use instead of htmlentities. * * @param string $var * @return string */ function html_encode($var) { return htmlentities($var, ENT_QUOTES, 'UTF-8'); } ``` Those two rescued me and I think it is now *working*. I'll come back if I continue to encounter problems. Should I store it in the DB, eg as "&" or as "&"?
To **absolutely once and for all** make sure you will never have problems with encoding again: **Use UTF-8 everywhere and on everything!** That is (if you use mysql and php): * Set all the tables in your database to collation "utf8\_general\_ci" for example. * Once you establish the database connection, run the following SQL query: "SET NAMES 'utf8'" * Always make sure the settings of your editor are set to UTF-8 encoding. * Have the following meta tag in the section of your HTML documents: *<meta http-equiv="content-type" content="text/html; charset=utf-8">* And couple of bonus tips: * When you use PHP for string manipulation, use [the multibyte functions](http://php.net/mbstring). * You might check <http://docs.kohanaphp.com/core/utf8> as well at some point. OR: You can just use one simple server side configuration file that takes care of all encoding stuff. In this case you wont need header and/or meta tags at all or php.ini file modification. Just add your wanted character set encoding to .htaccess file and put it into your www root. If you want to fiddle with character set strings and use your php code for that - thats another story. Database collation must ofcourse be correct. Footnote: UTF-8 is not *the* encoding solution its an *a* solution. It doesn't matter what character set/encoding one is using as long as the used environment has been taking to consideration.
PHP character encoding problems
[ "", "php", "xml", "utf-8", "character-encoding", "" ]
This is C#/.NET 2.0. So I have string that contains the future contents of an XML file. It contains metadata and binary data from image files. I would like to somehow determine how big the XML file will be once I write the data in the string to the file system. I've tried the following and neither works: ``` Console.Out.WriteLine("Size: " + data.Length/1024 + "KB"); ``` and ``` Console.Out.WriteLine("Size: " + (data.Length * sizeof(char))/1024 + "KB"); ``` Neither works (the actual size of the resulting file deviates from what is returned from either of these methods). I'm obviously missing something here. Any help would be appreciated. XML Serialization: ``` // doc is an XMLDocument that I've built previously StringWriter sw = new StringWriter(); doc.Save(sw); string XMLAsString = sw.ToString(); ``` Writing to file system (XMLAsString passed to this function as variable named data): ``` Random rnd = new Random(DateTime.Now.Millisecond); FileStream fs = File.Open(@"C:\testout" + rnd.Next(1000).ToString() + ".txt", FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); app.Diagnostics.Write("Size of XML: " + (data.Length * sizeof(char))/1024 + "KB"); sw.Write(data); sw.Close(); fs.Close(); ``` Thanks
You're missing how the encoding process works. Try this: ``` string data = "this is what I'm writing"; byte[] mybytes = System.Text.Encoding.UTF8.GetBytes(data); ``` The size of the array is exactly the number of bytes that it should take up on disk if it's being written in a somewhat "normal" way, as UTF8 is the default encoding for text output (I think). There may be an extra EOF (End Of File) character written, or not, but you should be really close with that. Edit: I think it's worth it for everybody to remember that characters in C#/.NET are NOT one byte long, but two, and are unicode characters, that are then *encoded* to whatever the output format needs. That's why any approach with `data.Length*sizeof(char)` would not work.
In NTFS, if your file system is set to compress, the final file might be smaller than what your actual file might be. Is that your problem?
Determining size of a future file while data is still in memory
[ "", "c#", "" ]
I'm configuring the admin site of my new project, and I have a little doubt on how should I do for, on hitting 'Save' when adding data through the admin site, everything is converted to upper case... Edit: Ok I know the .upper property, and I I did a view, I would know how to do it, but I'm wondering if there is any property available for the field configuration on the admin site :P
If your goal is to only have things converted to upper case when saving in the admin section, you'll want to [create a form with custom validation](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin) to make the case change: ``` class MyArticleAdminForm(forms.ModelForm): class Meta: model = Article def clean_name(self): return self.cleaned_data["name"].upper() ``` If your goal is to always have the value in uppercase, then you should [override save](http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods) in the model field: ``` class Blog(models.Model): name = models.CharField(max_length=100) def save(self, force_insert=False, force_update=False): self.name = self.name.upper() super(Blog, self).save(force_insert, force_update) ```
Updated example from documentation suggests using args, kwargs to pass through as: > Django will, from time to time, extend the capabilities of built-in > model methods, adding new arguments. If you use \*args, \*\*kwargs in > your method definitions, you are guaranteed that your code will > automatically support those arguments when they are added. ``` class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def save(self, *args, **kwargs): do_something() super(Blog, self).save( *args, **kwargs) # Call the "real" save() method. do_something_else() ```
Changing case (upper/lower) on adding data through Django admin site
[ "", "python", "django", "admin", "case", "" ]
I want to check if a class is a subclass of another without creating an instance. I have a class that receives as a parameter a class name, and as a part of the validation process, I want to check if it's of a specific class family (to prevent security issues and such). Any good way of doing this?
[`is_subclass_of()`](http://php.net/is_subclass_of) will correctly check if a class *extends* another class, but will not return `true` if the two parameters are the same (`is_subclass_of('Foo', 'Foo')` will be `false`). A simple equality check will add the functionality you require. ``` function is_class_a($a, $b) { return $a == $b || is_subclass_of($a, $b); } ```
You can use [`is_a()`](http://php.net/manual/en/function.is-a.php) with the third parameter `$allow_string` that has been added in PHP 5.3.9. It allows a string as first parameter which is treated as class name: ### Example: ``` interface I {} class A {} class B {} class C extends A implements I {} var_dump( is_a('C', 'C', true), is_a('C', 'I', true), is_a('C', 'A', true), is_a('C', 'B', true) ); ``` ### Output: ``` bool(true) bool(true) bool(true) bool(false) ``` Demo: <http://3v4l.org/pGBkf>
Checking if a class is a subclass of another
[ "", "php", "class", "oop", "inheritance", "" ]
Can you tell me how to add an animation gif to a button in c#. Just by adding gif to resources and setting as button image didn't work very well (next frames apear over the previous ones). The problem seems to be in a way how c# is treating transparency but I don't know how to fix it. Thanks in advance. --- edit --- After playing with the gif the issue was with transparency in gif. Next frame was drawn over the previous one so elements I wanted to become transparent in the middle of the animation just didn't do it properly (they still have the color of the previous frame). Solution was to create white areas on the next frame to cover the previous one. White was my transparent color so everything looked just fine after that :) I hope someone will see it useful. Happy programming :)
I've got it to work. 1 of 2 things worked for me: 1. I've reedited the gif adding property to every frame to undraw itself. 2. I've changed the version of VS (I was using free professional student version, now I m using one from MSDN subscription) Thanks for input guys. It guided me to conclusion that that it might be something wrong with VS itself not with my programming style :)
Just a note to everyone. Gif animation will play automaticaly if used on the .Image property but NOT on the .BackGroundImage one. Just in case someone is trying it that way.
How to add animated gif to a button?
[ "", "c#", "animation", "button", "gif", "animated-gif", "" ]
How do you take a java library that is for the desktop or an applet and make it so you can use its functions for a web page? I know not all things are meant for the web, but can you call a "regular" java class in an apache/tomcat setup server and it "work"? Do you have to so something to it to get it work with a web page? I was interested in jgrapht for the web but it looks like all desktop or applet and I don't know that it would be possible to return its graphics to the browser, but maybe its libraries and a generated .png rendered by the browser. Although there is debate on applets being alive or dead, I am not interested in using one at the moment, as it appears it is dead, albeit with new possible life in the latest update 6u10. I don't know that I want to invest in JavaFX either.
Johnny, the thing is that you have to decide what you mean to do. You could, for example, use JGraphT in server side code; the graph could be visualized in a bunch of different ways, like JGaph or graphviz. Then you would output the visualization in some form that works on the web and put it into your web page. In JGraph, that probably means a print interface that generates SVG or PNG. Or you could emit the graph structure as JSON with a simple walk of the graph and interpret it on the fly in the browser using Javascript. It's hard to answer the question generally, because it strongly depends on how you mean to use it.
Yes, it is possible to use a java class or jar file in a web appliaction, but it also depends on what you want to do with it. For example if the library is for mathematics and you want to return results back to the users on a web based application, this is definitely possible. There are many other examples I can give but they are all the same. As for displaying charts, I have successfully used JFreeChart in a web application using Apache Wicket (which rocks btw). So to answer your question, you don't really need to "port" the library, you just need to use it and display it's output to a web page instead of a java desktop GUI. Of course their might be some libraries that are specifically designed for Java GUI stuff like Swing or AWT. But for the most part there is no difference in using a Java library in a J2EE environment or a J2SE environment.
How can a java library be ported to the web?
[ "", "java", "port", "" ]
I'm resizing some images to the screen resolution of the user; if the aspect ratio is wrong, the image should be cut. My code looks like this: ``` protected void ConvertToBitmap(string filename) { var origImg = System.Drawing.Image.FromFile(filename); var widthDivisor = (double)origImg.Width / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; var heightDivisor = (double)origImg.Height / (double)System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height; int newWidth, newHeight; if (widthDivisor < heightDivisor) { newWidth = (int)((double)origImg.Width / widthDivisor); newHeight = (int)((double)origImg.Height / widthDivisor); } else { newWidth = (int)((double)origImg.Width / heightDivisor); newHeight = (int)((double)origImg.Height / heightDivisor); } var newImg = origImg.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero); newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp); } ``` In most cases, this works fine. But for some images, the result has an *extremely* poor quality. It looks like the would have been resized to something very small (thumbnail size) and enlarged again.. But the resolution of the image is correct. What can I do? Example orig image: [alt text http://img523.imageshack.us/img523/1430/naturaerowoods.jpg](http://img523.imageshack.us/img523/1430/naturaerowoods.jpg) Example resized image: [![alt text](https://i.stack.imgur.com/pW0AO.png)](https://i.stack.imgur.com/pW0AO.png) Note: I have a WPF application but I use the WinForms function for resizing because it's easier and because I already need a reference to System.Windows.Forms for a tray icon.
Change the last two lines of your method to this: ``` var newImg = new Bitmap(newWidth, newHeight); Graphics g = Graphics.FromImage(newImg); g.DrawImage(origImg, new Rectangle(0,0,newWidth,newHeight)); newImg.Save(this.GetBitmapPath(filename), System.Drawing.Imaging.ImageFormat.Bmp); g.Dispose(); ```
I cannot peek into the .NET source at the moment, but most likely the problem is in the `Image.GetThumbnailImage` method. Even MSDN says that "it works well when the requested thumbnail image has a size of about 120 x 120 pixels, but it you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image". For true resizing (i.e. not thumbnailing), you should use the `Graphics.DrawImage` method. You may also need to play with the `Graphics.InterpolationMode` to get a better quality if needed.
Image resizing - sometimes very poor quality?
[ "", "c#", "image", "resize", "image-scaling", "" ]
I try to answer [this question](https://stackoverflow.com/questions/803936/clear-remove-javascript-event-handler) a few minutes ago and prepared this example for myself : ``` <script> function trialMethod() { alert('On Submit Run!'); return true; } function trialMethod2() { alert('On Submit Run trialMethod2!'); return true; } </script> <form id="aspnetForm" onsubmit="trialMethod();"> <input type="submit"> </form> ``` Why the first unbind doesn't work : ``` <input type="button" id="btnTrial1" value="UNBIND 1" onclick="$('#aspnetForm').unbind('submit', trialMethod);"> ``` But this one works for the trialMethod2 method : ``` <input type="button" id="btnTrial2" value="UNBIND 2" onclick="$('#aspnetForm').bind('submit', trialMethod2).unbind('submit', trialMethod2);"> ```
The first unbind scenario doesn't work, because of jQuery's event model. jQuery stores every event handler function in an array that you can access via `$("#foo").data('events')`. The `unbind` function looks just for given function in this array. So, you can only `unbind()` event handlers that were added with `bind()`
**No one should ever mix their markup with their interaction code if they are using jQuery.** Add some javascript to the page like this: ``` $(function() { $('#aspnetForm').bind('submit',function() { trialMethod(); }); $('#btnTrial2').bind('click',function() { $('#aspnetForm').unbind('submit'); }); $('#btnTrial2').bind('click',function() { $('#aspnetForm').bind('submit', trialMethod2).unbind('submit'); }); }); ``` Now, with that out of the way... Everything should work now (even though you will now be double-binding the `#aspnetForm` before unbinding it completely when the second button is pressed). The problem was that the form was never really 'bound' to begin with. You can unbind `onsubmit` parameters in the markup.
Unbind jQuery even handler
[ "", "javascript", "jquery", "jquery-events", "" ]
Can I achieve ``` if (a == "b" || "c") ``` instead of ``` if (a == "b" || a== "c") ``` ?
No, you can do: ``` if (new[] { "b", "c" }.Contains(a)) ``` if you have the [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query) extensions available, but that's hardly an improvement. --- In response to the comment about performance, here's some basic timing code. Note that the code must be viewed with a critical eye, I might have done things here that skew the timings. The results first: ``` ||, not found: 26 ms ||, found: 8 ms array.Contains, not found: 1407 ms array.Contains, found: 1388 ms array.Contains, inline array, not found: 1456 ms array.Contains, inline array, found: 1427 ms switch-statement, not interned, not found: 26 ms switch-statement, not interned, found: 14 ms switch-statement, interned, not found: 25 ms switch-statement, interned, found: 8 ms ``` All the code was executed twice, and only pass nr. 2 was reported, to remove JITting overhead from the equation. Both passes executed each type of check one million times, and executed it both where the element to find was one of the elements to find it in (that is, the if-statement would execute its block), and once where the element was not (the block would not execute). The timings of each is reported. I tested both a pre-built array and one that is built every time, this part I'm unsure how much the compiler deduces and optimizes away, there might be a flaw here. In any case, it appears that using a switch-statement, with or without interning the string first, gives roughly the same results as the simple or-statement, which is to be expected, whereas the array-lookup is much more costly, which to me was also expected. Please tinker with the code, and correct (or comment) it if there's problems. And here's the source code, rather long: ``` using System; using System.Linq; using System.Diagnostics; namespace StackOverflow826081 { class Program { private const Int32 ITERATIONS = 1000000; static void Main() { String a; String[] ops = CreateArray(); Int32 count; Stopwatch sw = new Stopwatch(); Int32 pass = 0; Action<String, Int32> report = delegate(String title, Int32 i) { if (pass == 2) Console.Out.WriteLine(title + ": " + sw.ElapsedMilliseconds + " ms"); }; for (pass = 1; pass <= 2; pass++) { #region || operator a = "a"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { if (a == "b" || a == "c") { count++; } } sw.Stop(); report("||, not found", count); sw.Reset(); a = "b"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { if (a == "b" || a == "c") { count++; } } sw.Stop(); report("||, found", count); sw.Reset(); #endregion #region array.Contains a = "a"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { if (ops.Contains(a)) { count++; } } sw.Stop(); report("array.Contains, not found", count); sw.Reset(); a = "b"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { if (ops.Contains(a)) { count++; } } sw.Stop(); report("array.Contains, found", count); sw.Reset(); #endregion #region array.Contains a = "a"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { if (CreateArray().Contains(a)) { count++; } } sw.Stop(); report("array.Contains, inline array, not found", count); sw.Reset(); a = "b"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { if (CreateArray().Contains(a)) { count++; } } sw.Stop(); report("array.Contains, inline array, found", count); sw.Reset(); #endregion #region switch-statement a = GetString().Substring(0, 1); // avoid interned string sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { switch (a) { case "b": case "c": count++; break; } } sw.Stop(); report("switch-statement, not interned, not found", count); sw.Reset(); a = GetString().Substring(1, 1); // avoid interned string sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { switch (a) { case "b": case "c": count++; break; } } sw.Stop(); report("switch-statement, not interned, found", count); sw.Reset(); #endregion #region switch-statement a = "a"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { switch (a) { case "b": case "c": count++; break; } } sw.Stop(); report("switch-statement, interned, not found", count); sw.Reset(); a = "b"; sw.Start(); count = 0; for (Int32 index = 0; index < ITERATIONS; index++) { switch (a) { case "b": case "c": count++; break; } } sw.Stop(); report("switch-statement, interned, found", count); sw.Reset(); #endregion } } private static String GetString() { return "ab"; } private static String[] CreateArray() { return new String[] { "b", "c" }; } } } ```
Well, the closest to that you can get is: ``` switch (a) { case "b": case "c": // variable a is either "b" or "c" break; } ```
OR operator in C#
[ "", "c#", "operators", "logical-operators", "operator-precedence", "" ]
I want to be able to distinguish between a generic and regular (non-generic) version of a class. Much like the .NET framework does with it's generic and non-generic versions of several of it's interfaces and collection classes. ([Queue](http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx), [Queue(T)](http://msdn.microsoft.com/en-us/library/7977ey2c.aspx)) I generally like to follow the convention of one class per file (as in Java). Is there a common convention for naming files containing a single generic class? I'm mostly interested in Windows (NTFS specifically) but it seems like a good convention would be (at least a little) portable.
At Microsoft, they use `ClassNameOfT.cs`.
Just found this question after looking for what conventions other people use for generic class filenames. Lately I've been using `ClassName[T].cs`. I really like this convention, and I think it's superior to the others for the following reasons: * The type parameters jump out at you a little more than they do with the Microsoft convention (e.g., `ClassNameOfT.cs`). * It allows you to have multiple type parameters without too much confusion: `Dictionary[TKey, TValue].cs` * It doesn't require you to create any special folders, or to have your generic classes in a special namespace. If you only have a few generic classes, having a special namespace dedicated to them just isn't practical. I borrowed this convention from [Boo](http://boo.codehaus.org/)'s generic syntax, albeit slightly modified (Boo uses `ClassName[of T]`). Some developers seem to have a phobia of filenames that contain anything but letters and underscores, but once you can get past that this convention seems to work extremely well.
Convention for Filenames of Generic Classes
[ "", "c#", "generics", "" ]
Has anyone here used either of the following (or any other tool) to convert your vb6 code to a .net language? [**Artinsoft's upgrade companion**](http://www.artinsoft.com/pr_vbcompanion.aspx) (converts to c# and vb.net) [**vbmigration partner**](http://www.vbmigration.com/) (converts to vb.net) How effective were they and what size project did you convert? How much work was left to do afterwards? How happy are you with the resultant .net project. What was the support like? Is there a support forum anywhere for users of tools like these, neither vendor seems to offer one. What did they charge, their prices are not published and I have heard wildly differing prices from different sources for both the above examples
I think you've already seen the [question](https://stackoverflow.com/questions/638152/best-development-tools-for-upgrading-from-vb6-0) about tools for migrating VB6 to VB.NET. Both have published special offer prices for the UK market on their **basic** products on this Microsoft UK [page](http://msdn.microsoft.com/en-gb/dd408373.aspx). Of course you need to know the limitations of the basic products and the prices for your market to make a realistic judgement, so you probably do need to contact them :( * Artinsoft Upgrade Companion Developer Edition [£199](http://www.artinsoft.com/visual-basic-upgrade-companion-developers.aspx) for up to 50,000 lines of code. **EDIT** Now offering a [free version](http://www.artinsoft.com/artinsoft-renews-its-efforts-to-ease-the-transition-from-microsoft-visual-basic-6-to-microsoft-net-framework.aspx) that can do up to 10,000 lines of code. * Code Architects’ Visual Basic Migration Partner Professional Edition [£399](http://www.vbmigration.com/campaignuk.aspx). They told me this was also for up to 50,000 lines of code. The built-in Microsoft upgrade wizard is pathetic - [according to the guy who wrote it](http://www.devx.com/vb/Article/16822) - of course he is from Artinsoft so he wants to sell you something better. Microsoft UK also [say](http://msdn.microsoft.com/en-gb/dd408373) the Artinsoft and Code Architects tools are better than the built-in upgrade wizard. **EDIT**: I contacted Code Architects for a quote, they responded very fast. Unlike this Stack Overflow [question](https://stackoverflow.com/questions/264375/upgrading-a-large-vb6-app-to-net-opinions-on-vb-migration-partner) by *Angry Hacker* who had a worse experience. But then Francesco Balena popped up on Stack Overflow to answer his question within 12 hours, which is more encouraging.
I am Eugenio La Mesa, general manager at Code Architects. I read a few comments on our VB Migration Partner and conversion tools in general, and thought I might add some hopefully useful hints. First, our conversion software does support all VB6 graphic properties and methods – with the only exception of DrawMode and ClipControls. We even support the AutoRedraw property and user-defined ScaleMode coordinates, therefore the migration of a CAD-like program to VB.NET is quite in the reach of our software. The Code Sample section at www.vbmigration.com contains many examples of graphic-intensive VB6 apps that have been converted to .NET with minimal effort. Second, let me clarify our price structure. We sell two different editions of VB Migration Partner: the Professional Edition can convert VB6 apps with max. 50,000 lines of code, whereas the Enterprise Edition has no size limitation and supports a few additional advanced features, such as integration with source code control software and generation of .NET components that are binary-compatible with the original VB6 DLL, which allows you to implement staged migrations of N-tiered COM-based applications. The price of the Professional Edition for £399 is a special promotion up to June 30th 2009, during a Microsoft UK marketing campaign, for UK only and for applications up to 50K lines of code (LOCs). The price of the Enterprise Edition may vary because it depends on several factors, including number of licenses and number of LOCs to be migrated. This explains why you may see different price quotations. Also, we have recently slightly decreased the list price as our answer to the economic situation. We are also planning to take a few features out of the main product and offer them separately, which would result in a more flexible price structure. Quite honestly, for applications with 25-50K LOCs we usually recommend a manual rewrite. In fact, our focus is on the enterprise market segment, where you often finds VB6 apps with several hundred thousand LOCs, if not millions. In those cases, a manual rewrite is seldom a viable option: it requires too many skilled VB6/.NET developers, it takes too long, or just costs too much. We have recently published a case study related to an application with 650K LOCs; one of our customers is currently migrating a monster app with about 15 million LOCs!
Conversion tool comparisons for visual basic 6.0
[ "", "c#", "vb.net", "vb6", "vb6-migration", "" ]
C# 2008 I am using the code below to login to a softphone. However, the login progess is a long process as there are many things that have to be initialized and checks to be made, I have only put a few on here, as it would make the code to long to post. In the code below I am checking if the CancellationPending if the CancelAsync has been called in my cancel button click event, before doing each check. Is this correct? Also if the check fails I also call the CancelAsync and set the e.Cancel to true. I would like to know if my method I have used here is the best method to use. Many thanks for any advice, ``` private void bgwProcessLogin_DoWork(object sender, DoWorkEventArgs e) { /* * Perform at test to see if the background worker has been * cancelled by the user before attemping to continue to login. * * Cancel background worker on any failed attemp to login */ // Start with cancel being false as to reset this if cancel has been set to true // in the cancel button. e.Cancel = false; NetworkingTest connection_test = new NetworkingTest(); if (!this.bgwProcessLogin.CancellationPending) { // Check local LAN or Wireless connection if (!connection_test.IsNetworkConnected()) { // Update label if (this.lblRegistering.InvokeRequired) { this.lblRegistering.Invoke(new UpdateRegisterLabelDelegate(UpdateRegisterLabel), "No network connection"); } else { this.lblRegistering.Text = "No network connection"; } // Failed attemp this.bgwProcessLogin.CancelAsync(); e.Cancel = true; return; } // Report current progress this.bgwProcessLogin.ReportProgress(0, "Network connected"); } else { // User cancelled e.Cancel = true; return; } // Test if access to Server is available if (!this.bgwProcessLogin.CancellationPending) { if (!connection_test.IsSIPServerAvailable()) { // Update label if (this.lblRegistering.InvokeRequired) { this.lblRegistering.Invoke(new UpdateRegisterLabelDelegate(UpdateRegisterLabel), "Server unavailable"); } else { this.lblRegistering.Text = "Server unavailable"; } // Failed attemp this.bgwProcessLogin.CancelAsync(); e.Cancel = true; return; } // Report current progress this.bgwProcessLogin.ReportProgress(1, "Server available"); } else { // User cancelled e.Cancel = true; return; } . . . } private void bgwProcessLogin_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Check for any errors if (e.Error == null) { if (e.Cancelled) { // User cancelled login or login failed } else { // Login completed successfully } } else { // Something failed display error this.statusDisplay1.CallStatus = e.Error.Message; } } private void bgwProcessLogin_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.lblRegistering.Text = e.UserState.ToString(); } private void btnCancel_Click(object sender, EventArgs e) { // Cancel the logging in process this.bgwProcessLogin.CancelAsync(); this.lblRegistering.Text = "Logged out"; } ```
There is maybe only one problem: if one of the operation in DoWork event handler would last for a long time. In this case you could abort your pending operation ONLY after that operation finished. If all operations in DoWork event can't last very long (for instance, no more than 5 seconds), its all OK, but if one of the operations can last for long time (5 minutes, for instance) in this case user have to wait until this operation finished. If DoWork contains long lasting operations you can use something like AbortableBackgroundWorker. Something like this: ``` public class AbortableBackgroundWorker : BackgroundWorker { private Thread workerThread; protected override void OnDoWork(DoWorkEventArgs e) { workerThread = Thread.CurrentThread; try { base.OnDoWork(e); } catch (ThreadAbortException) { e.Cancel = true; //We must set Cancel property to true! Thread.ResetAbort(); //Prevents ThreadAbortException propagation } } public void Abort() { if (workerThread != null) { workerThread.Abort(); workerThread = null; } } } ``` In this case you can truly abort pending operations, but you also have some restrictions (for more information about aborting managed thread and some restrictions see [Plumbing the Depths of the ThreadAbortException Using Rotor](http://ondotnet.com/pub/a/dotnet/2003/02/18/threadabort.html)). P.S. I agree with Oliver that you should wrap InvokeRequired in more usable form.
You are doing it the right way, I believe. You will find thread members that allow you to terminate or abort a thread, but you don't want to use them for something like this. It might look a little weird to have all of the "cancelled" checks in your code, but that allows you to control exactly when you exit your thread. If you were to "rudely" abort the worker thread, the thread has no control of when it exits, and there could be corrupted state.
C# cancelling DoWork of background worker
[ "", "c#", "background", "worker", "" ]
I have a table containing a unique ID field. Another field (REF) contains a reference to another dataset's ID field. Now I have to select all datasets where REF points to a dataset that doesn't exist. ``` SELECT * FROM table WHERE ("no dataset with ID=REF exists") ``` How can I do this?
3 ways ``` SELECT * FROM YourTable y WHERE NOT EXISTS (SELECT * FROM OtherTable o WHERE y.Ref = o.Ref) SELECT * FROM YourTable WHERE Ref NOT IN (SELECT Ref FROM OtherTable WHERE Ref IS NOT NULL) SELECT y.* FROM YourTable y LEFT OUTER JOIN OtherTable o ON y.Ref = o.Ref WHERE o.Ref IS NULL ``` See also [Five ways to return all rows from one table which are not in another table](http://wiki.lessthandot.com/index.php/5_ways_to_return_rows_from_one_table_not_in_another_table)
Try this: ``` SELECT * FROM TABLE WHERE NOT EXISTS (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID) ```
How to do a Select in a Select
[ "", "sql", "" ]
I have the following string: > FirstName=John&LastName=Doe&City=London&ConfirmationId=WXASL320330 I want to extract the confirmationId from it. I have done a split on it and passed in the & character, but this returns ConfirmationId=WXASL320330 and I just WXASL320330. What is the best way of doing this? The string is actually part of a property called RawProcessorResult that PayPal returns.
The easiest way is to use the built-in [`HttpUtility.ParseQueryString()`](http://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring.aspx) method: ``` string queryString = "FirstName=John&LastName=Doe&City=London&ConfirmationId=WXASL320330"; string confirmationID = System.Web.HttpUtility.ParseQueryString(queryString)["ConfirmationId"]; // returns "WXASL320330" ```
Another split on '='
How do I extract a string out of a string in c#
[ "", "c#", "string", "" ]
I'm trying to do the following in a proc, but getting an incorrect syntax error: ``` SELECT TOP @NumberOfResultsToReturn * ``` What am I doing wrong here? Thanks.
Add parenthesis: ``` SELECT TOP (@NumberOfResultsToReturn) * ```
SQL Server: Put the argument in parens: ``` SELECT TOP (@NumberOfResultsToReturn) * ```
How to do SELECT TOP @Param in a Stored Procedure?
[ "", "sql", "stored-procedures", "" ]
--- ``` int LinkedList::DoStuff() { Node *Current = next_; while ( Current != NULL ) { Current = Current->next_; length_++; } // At the last iteration we have reached the end/tail/last node return length_; } ``` --- there are no more nodes beyond the last. How can i traverse to the tail-end to the front-head?
Recursion can work, as can building an auxiliary data structure, such as an array with one entry for each element of the original list. If you want a solution for a single-threaded list without requiring O(n) extra storage, the best bet is to reverse the list in place as Michael suggests. I wrote an example for this, [but I'll leave it out given the concern about homework]. One caution about reversing the list: if there are any other data structures that hold pointers to the original list, and you might be accessing them during your traversal, they won't work if they need to access the list while it's reversed, and this might lead to data corruption if they try to modify the list. Update: Ok, here's the (C++) routine to reverse a list in place. It hasn't been tested, though. And I'll note that if this is homework, the poster still needs to figure out how to use this routine correctly to get a complete answer. ``` Node *ReverseList(Node *head) { // Reverse a single-threaded list in place, return new head Node *prev=NULL; Node *cur=head; while (Node *next=cur->next_) { cur->next_ = prev; prev = cur; cur = next; } cur->next_ = prev; return cur; } ```
Unless your linked list is a doubly-linked one, this is difficult to do. Recursion is one way, assuming you don't have lists so big that you'll run out of stack space, something like this (pseudo-code): ``` DoStuffBackwards (currNode) { if (currNode != NULL) { DoStuffBackwards (currNode->next); // Process currNode here. } } DoStuffBackwards (firstNode); ``` This works because you keep calling `DoStuffBackwards()` for the next node until you exhaust the list then, as you roll back up the recursion stack, you process each node.
Traverse from end to front ( C++ LL Q:1 )
[ "", "c++", "linked-list", "" ]
I am aware that MySQL and PostgreSQL[1] do *not* have that concept, so I am interested in finding out of there is an open-source SQL database that does have the concept. [1] It was later pointed out that PostgreSQL does have the rowid pseudo-column.
`PostgreSQL` does have this concept. See [**here**](http://www.commandprompt.com/ppbook/x4636) for a brief list of pseudocolumns in `PostgreSQL`, out of which `ctid` is of interest to you: > `ctid (tuple identifier)` > > The identifier which describes the physical location of the tuple within the database. A pair of numbers are represented by the ctid: the block number, and tuple index within that block. That is direct analog of `Oracle`'s `rowid`. As for `MySQL`, physical location of a row is not available for the front end. In `MyISAM`, `rowid` is just a file offset from the beginning, and that's what is stored in the index leaves. In `InnoDB`, tables are `index organized` by design, that means they always have some kind of a primary key, and the indexes over an `InnoDB` table use that `PRIMARY KEY` as a row pointer. This is also true for `Oracle`'s `index organized` tables, for which a `rowid` is not a physical pointer to a block in a datafile, but rather a such called `logical ROWID`, or `UROWID` If you select a `ROWID` from an `INDEX ORGANIZED` table in `Oracle`, you will see that it has a different format (something like `*BAEBwPICwQL+`). This is in fact an encoded `PRIMARY KEY` value. Note that if you have not defined any column as a `PRIMARY KEY`, `MySQL` will create a hidden surrogate `PRIMARY KEY` over which you will never have any control. That's why you should always create some kind of a `PRIMARY KEY` in an `InnoDB` table: it's free, and you get control over the column.
if neither of them have done that, then no others do.
Is there an open-source SQL database that has the concept of Oracle's "rowid" pseudo-column?
[ "", "sql", "database", "oracle", "rowid", "" ]
I need to be able to parse both CSV and TSV files. I can't rely on the users to know the difference, so I would like to avoid asking the user to select the type. Is there a simple way to detect which delimiter is in use? One way would be to read in every line and count both tabs and commas and find out which is most consistently used in every line. Of course, the data could include commas or tabs, so that may be easier said than done. **Edit:** Another fun aspect of this project is that I will also need to detect the schema of the file when I read it in because it could be one of many. This means that I won't know how many fields I have until I can parse it.
You could show them the results in preview window - similar to the way Excel does it. It's pretty clear when the wrong delimiter is being used in that case. You could then allow them to select a range of delimiters and have the preview update in real time. Then you could just make a simple guess as to the delimiter to start with (e.g. does a comma or a tab come first).
In Python, there is a Sniffer class in the csv module that can be used to guess a given file's delimiter and quote characters. Its strategy is (quoted from csv.py's docstrings): --- [First, look] for text enclosed between two identical quotes (the probable quotechar) which are preceded and followed by the same character (the probable delimiter). For example: ``` ,'some text', ``` The quote with the most wins, same with the delimiter. If there is no quotechar the delimiter can't be determined this way. In that case, try the following: The delimiter *should* occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1. build a table of the frequency of each character on every line. 2. build a table of freqencies of this frequency (meta-frequency?), e.g. 'x occurred 5 times in 10 rows, 6 times in 1000 rows, 7 times in 2 rows' 3. use the mode of the meta-frequency to determine the *expected* frequency for that character 4. find out how often the character actually meets that goal 5. the character that best meets its goal is the delimiter For performance reasons, the data is evaluated in chunks, so it can try and evaluate the smallest portion of the data possible, evaluating additional chunks as necessary. --- I'm not going to quote the source code here - it's in the Lib directory of every Python installation. Remember that CSV can also use semicolons instead of commas as delimiters (e. g. in German versions of Excel, CSVs are semicolon-delimited because commas are used as decimal separators in Germany...)
How should I detect which delimiter is used in a text file?
[ "", "c#", "asp.net", "csv", "text-parsing", "" ]
Say I have a queue full of tasks which I need to submit to an executor service. I want them processed one at a time. The simplest way I can think of is to: 1. Take a task from the queue 2. Submit it to the executor 3. Call .get on the returned Future and block until a result is available 4. Take another task from the queue... However, I am trying to avoid blocking completely. If I have 10,000 such queues, which need their tasks processed one at a time, I'll run out of stack space because most of them will be holding on to blocked threads. What I would like is to submit a task and provide a call-back which is called when the task is complete. I'll use that call-back notification as a flag to send the next task. (functionaljava and jetlang apparently use such non-blocking algorithms, but I can't understand their code) How can I do that using JDK's java.util.concurrent, short of writing my own executor service? (the queue which feeds me these tasks may itself block, but that is an issue to be tackled later)
Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task. You could even write a general wrapper for Runnable tasks, and submit these to `ExecutorService`. Or, see below for a mechanism built into Java 8. ``` class CallbackTask implements Runnable { private final Runnable task; private final Callback callback; CallbackTask(Runnable task, Callback callback) { this.task = task; this.callback = callback; } public void run() { task.run(); callback.complete(); } } ``` --- With [`CompletableFuture`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html), Java 8 included a more elaborate means to compose pipelines where processes can be completed asynchronously and conditionally. Here's a contrived but complete example of notification. ``` import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; public class GetTaskNotificationWithoutBlocking { public static void main(String... argv) throws Exception { ExampleService svc = new ExampleService(); GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking(); CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work); f.thenAccept(listener::notify); System.out.println("Exiting main()"); } void notify(String msg) { System.out.println("Received message: " + msg); } } class ExampleService { String work() { sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */ char[] str = new char[5]; ThreadLocalRandom current = ThreadLocalRandom.current(); for (int idx = 0; idx < str.length; ++idx) str[idx] = (char) ('A' + current.nextInt(26)); String msg = new String(str); System.out.println("Generated message: " + msg); return msg; } public static void sleep(long average, TimeUnit unit) { String name = Thread.currentThread().getName(); long timeout = Math.min(exponential(average), Math.multiplyExact(10, average)); System.out.printf("%s sleeping %d %s...%n", name, timeout, unit); try { unit.sleep(timeout); System.out.println(name + " awoke."); } catch (InterruptedException abort) { Thread.currentThread().interrupt(); System.out.println(name + " interrupted."); } } public static long exponential(long avg) { return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble())); } } ```
In Java 8 you can use [CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html). Here's an example I had in my code where I'm using it to fetch users from my user service, map them to my view objects and then update my view or show an error dialog (this is a GUI application): ``` CompletableFuture.supplyAsync( userService::listUsers ).thenApply( this::mapUsersToUserViews ).thenAccept( this::updateView ).exceptionally( throwable -> { showErrorDialogFor(throwable); return null; } ); ``` It executes asynchronously. I'm using two private methods: `mapUsersToUserViews` and `updateView`.
Java executors: how to be notified, without blocking, when a task completes?
[ "", "java", "callback", "notify", "executor", "" ]
Imagine a user that would like to put a form on their website that would allow a website visitor to upload a file and a simple message, which will immediately be emailed (ie, the file is not stored on the server, or if it is then only temporarily) as a file attachment with the note in the message body. See more details at <http://a2zsollution.com/php-secure-e-mail/> What is the simplest way to accomplish this? Simplest in terms of: * Size (code golf) * Ease of implementation (ideally all in one file, needs few to no external resources) * Not obfuscated for the sake of obfuscation (tradeoffs for size are fine) * Self contained example (if called without a form post, it displays the form) This is nearly the reverse of: [How to get email and their attachments from PHP](https://stackoverflow.com/questions/114953/how-to-get-email-and-their-attachments-from-php). It almost could have been answered in [Compiling email with multiple attachments in PHP](https://stackoverflow.com/questions/720455/compiling-email-with-multiple-attachments-in-php), but it doesn't actually show code.
Just for fun I thought I'd knock it up. It ended up being trickier than I thought because I went in not fully understanding how the boundary part works, eventually I worked out that the starting and ending '--' were significant and off it went. ``` <?php if(isset($_POST['submit'])) { //The form has been submitted, prep a nice thank you message $output = '<h1>Thanks for your file and message!</h1>'; //Set the form flag to no display (cheap way!) $flags = 'style="display:none;"'; //Deal with the email $to = 'me@example.com'; $subject = 'a file for you'; $message = strip_tags($_POST['message']); $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name']))); $filename = $_FILES['file']['name']; $boundary =md5(date('r', time())); $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\""; $message="This is a multi-part message in MIME format. --_1_$boundary Content-Type: multipart/alternative; boundary=\"_2_$boundary\" --_2_$boundary Content-Type: text/plain; charset=\"iso-8859-1\" Content-Transfer-Encoding: 7bit $message --_2_$boundary-- --_1_$boundary Content-Type: application/octet-stream; name=\"$filename\" Content-Transfer-Encoding: base64 Content-Disposition: attachment $attachment --_1_$boundary--"; mail($to, $subject, $message, $headers); } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>MailFile</title> </head> <body> <?php echo $output; ?> <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" <?php echo $flags;?>> <p><label for="message">Message</label> <textarea name="message" id="message" cols="20" rows="8"></textarea></p> <p><label for="file">File</label> <input type="file" name="file" id="file"></p> <p><input type="submit" name="submit" id="submit" value="send"></p> </form> </body> </html> ``` Very barebones really, and obviously the using inline CSS to hide the form is a bit cheap and you'd almost certainly want a bit more feedback to the user! Also, I'd probably spend a bit more time working out what the actual Content-Type for the file is, rather than cheating and using application/octet-stream but that part is quite as interesting.
A combination of this <http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment> with the php upload file example would work. In the upload file example instead of using move\_uploaded\_file to move it from the temporary folder you would just open it: ``` $attachment = chunk_split(base64_encode(file_get_contents($tmp_file))); ``` where `$tmp_file = $_FILES['userfile']['tmp_name'];` and send it as an attachment like the rest of the example. **All in one file / self contained:** ``` <? if(isset($_POST['submit'])){ //process and email }else{ //display form } ?> ``` I think its a quick exercise to get what you need working based on the above two available examples. P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.
Simple PHP form: Attachment to email (code golf)
[ "", "php", "email", "email-attachments", "code-golf", "mail-form", "" ]
Can search engines such as Google index JavaScript generated web pages? When you right click and select view source in a page that is generated by JavaScript (e.g using GWT) you do not see the dynamically generated HTML. I suppose that if a search engine also cannot see the generated HTML then there is not much to index, right?
Your suspicion is correct - JS-generated content cannot be relied on to be visible to search bots. It also can't be seen by anyone with JS turned off - and, last time I added some tests to a site I was working on (which was a large, mainstream-audience site, with hundreds of thousands of unique vistors per month), approx 10% of users were not running Javascript in any form. That includes search bots, PC browsers with JS disabled, many mobiles, blind people using screenreaders... etc etc. This is why content generated via JS (with no fallback option) is a Really Bad Idea. Back to basics. First, create your site using **bare-bones (X)HTML**, on REST-like principles (at least to the extent of requiring POST requests for state changes). Simple semantic markup, and forget about CSS and Javascript. Step one is to get that right, and have your entire site (or as much of it as makes sense) working nicely this way for search bots and Lynx-like user agents. Then add a **visual layer**: CSS/graphics/media for visual polish, but don't significantly change your original (X)HTML markup; allow the original text-only site to stay intact and functioning. Keep your markup clean! Third is to add a **behavioural layer**: Javascript (Ajax). Offer things that make the experience faster, smoother, nicer for users/browsers with Ajax-capable JS... but only those users. Users without Javascript are still welcome; and so are search bots, the visually impaired, many mobiles, etc. This is called **progressive enhancement** in web design circles. Do it this way and your site works, in some reasonable form, for everyone.
> if a search engine also cannot see the generated HTML then there is not much to index That about sums it up. Technically nothing is stopping a search engine from implementing a javascript engine for their bot/spider, but it's just not normally done. They could, but they won't. On the other hand, you can sniff a search engine's user agent and serve it something readable. But search engines don't usually like this and will penalize you pretty severely if they detect differences with what you send to a normal browser.
Can search engines index JavaScript generated web pages?
[ "", "javascript", "html", "gwt", "dynamic", "search-engine", "" ]
As I have said in my previous questions, I'm still new to Java. I'm developing a tile-based game in Java. The movement is on a grid. I'm at the stage where I'm implementing character movement. My plan was to use the code which I pasted in [this question](https://stackoverflow.com/questions/772713/call-repaint-from-another-class-in-java). However, this didn't work, and I was told I should use SwingWorker. Being a problem solver, I've been thinking about this over the day, and I had a thought. I could achieve the same effect by doing things a bit differently. I mentioned that I had a timer that went off every 20 milliseconds, calling a repaint. My idea was that I could have a method call before the repaint in the event for the timer, which would move all of the people 1 unit nearer to their destination (next square/tile). Would that sort of thing work? Later on in the game, there may be 100 or so people. Would 20ms be enough time to loop through all the people and move them one unit closer to their destination? Is 20ms too short a time? Am I just making no sense at all? Your opinions / answers / thoughts are welcome :)
OK, first to answer the 20 millis question. You can get quite a lot of game logic done in 20ms. But I'd say it's too frequently to be updating the display. You should also bear in mind that the OS generally dishes out CPU in the order of 10-20 ms timeslices-- in other words, another process at any moment could easily delay your process by about that amount of time. Have a look, for example, at my article on the [behaviour of Thread.sleep()](http://www.javamex.com/tutorials/threads/sleep.shtml)-- notice from the graph that as the system is moderately busy, the OS can't honour the sleep time we asked for. If you need an average sleep between frames of 100ms, then 20ms or so jitter here and there won't be too bad. But 20ms jitter when you asked for 20ms will probably be more noticeable... So I'd probably start at 10 frames per second (100ms pauses) and see how that looks. As far as the code is concerned, if your game logic will take more or less the same amount of time each tick, then I'd start with logic-repaint-sleep on each tick. Remember you need to synchronize on the things you're painting, so in your game logic thread, you ideally need to avoid holding on to locks for too long.
I agree with pretty much everything Bill said, especially the part about Swing being enigmatic (although not really much more so than other graphics environments). To give a few references, 30 fps (which is what most interlaced screens produce at) is 1 frame every 33 ms. 60 fps is about the highest that humans can perceive (1 frame / 16 ms), and most LCD monitors refresh at 60 or 75 Hz, which would be the absolute fastest you could actually produce. 20 ms/frame is a frame rate of 50 fps, which also coincides with the electric frequency in European territories and is just noticeable by the human eye. The main thing I would recommend against is to just do everything in a tight while loop. This will cause your game speed to be highly dependent on the system on which you play. On a faster system, you may get frame spewing faster than the player can react, even if it plays reasonably on an older one (or you'll have the converse problem on a decrepit machine). Using a timer will allow you to be more consistent in the rate, but you have to make some defensive checks in case you miss a frame deadline. This means that your timer needs to know when the calculations are finished so if another frame ticks by and it hasn't finished, then it will skip the next frame. Even better, you log how long actually passes between calculations and adjust the actual movement traveled by your characters accordingly. Another warning: while the drawing must be done on the AWT thread and the calculations off of it (to keep your program responsive), the state also needs to be updated on the AWT thread. If you let the thread doing the calculations update the game state, then the AWT thread will see this in the middle of a repaint, leading to an effect called tearing. Thus, you may need to make a copy of the state to post to the AWT thread. This is what a SwingWorker is for, which you'll probably use in conjunction with a Timer. Amazingly, most of what I said is actually new when compared to what I posted on your other question.
Should I be using SwingWorker, threading, or a recursive update for this animation?
[ "", "java", "multithreading", "swing", "animation", "swingworker", "" ]
My following C# code is obviously a hack so how do I capture the index value in the Where method? ``` string[] IntArray = { "a", "b", "c", "b", "b"}; int index=0; var query = IntArray.Where((s,i) => (s=="b")&((index=i)==i)); //"&" and "==i" only exists to return a bool after the assignment ofindex foreach (string s in query) { Console.WriteLine("{0} is the original index of {1}", index, s); } //outputs... //1 is the original index of b //3 is the original index of b //4 is the original index of b ```
The `Where` method *only* returns whether or not the item should be included in the result or not. The function can't provide any more information in a sensible way (it *could* capture a local variable and do stuff with it, but that would be horrible). If you want the index in the final result, you'll need to create a projection which includes that index. If you want the *original* index in the final result, you'll need to put that projection before any `Where` clauses. Here's an example of that: ``` using System; using System.Collections.Generic; using System.Linq; public class Test { static void Main() { IEnumerable<char> letters = "aBCdEFghIJklMNopQRsTUvWyXZ"; var query = letters.Select((c, i) => new { Char=c, OriginalIndex=i }) .Where(x => char.IsLower(x.Char)) .Select((x, i) => new { x.Char, x.OriginalIndex, FinalIndex=i}); foreach (var result in query) { Console.WriteLine(result); } } } ``` Results: ``` { Char = a, OriginalIndex = 0, FinalIndex = 0 } { Char = d, OriginalIndex = 3, FinalIndex = 1 } { Char = g, OriginalIndex = 6, FinalIndex = 2 } { Char = h, OriginalIndex = 7, FinalIndex = 3 } { Char = k, OriginalIndex = 10, FinalIndex = 4 } { Char = l, OriginalIndex = 11, FinalIndex = 5 } { Char = o, OriginalIndex = 14, FinalIndex = 6 } { Char = p, OriginalIndex = 15, FinalIndex = 7 } { Char = s, OriginalIndex = 18, FinalIndex = 8 } { Char = v, OriginalIndex = 21, FinalIndex = 9 } { Char = y, OriginalIndex = 23, FinalIndex = 10 } ```
Which index do you want? You have three times b. If you want all indices of b, then: ``` string[] IntArray = { "a", "b", "c", "b", "b" }; var query = IntArray .Select((x, i) => new { value = x, idx = i }) .Where(s => s.value == "b"); ```
Is there a way to capture the index value in a LINQ Where method in C#?
[ "", "c#", "linq", "" ]
I'm trying to build an object that looks something like this: ``` public class MyObject { private IList<AnotherObject> items; public List<AnotherObject> Items { return items.AsEnumerable().ToList<AnotherObject>(); } } ``` I'm using NHibernate as my DAL and have it mapping directly to the items field and all that works fine. I'm also using Windows Workflow and the replicator activity doesn't work with the generic IList. (<http://social.msdn.microsoft.com/Forums/en-US/windowsworkflowfoundation/thread/2ca74b60-fd33-4031-be4b-17a79e9afe63>) This is basically forcing me to use the List<> wrapper instead of the IList<>. This of course breaks the direct NHibernate mapping as NHibernate's IList implementation can't be cast directly to a List. \*\* EDIT: The Windows Workflow requirement actually means I'm going to lose type-safe access to the list no matter what as it requires an IList. Now the goal is to serialize/deserialize this object. This works fine with binary serialization but the underlying NHibernate proxy objects explode with nhibernate errors when I try to deserialize them. So I tried xml serialization. The serialization works fine and gives me my nice concrete class definitions in the serialized xml file which strips out the nhibernate proxies completely. However, when attempting to deserialize this, I'm unable to add the items to the list as the items.AsEnumerable.ToList call won't let items get added to the underlying list via the .Add method. Does anyone have any thoughts on this? Am I going about this the wrong way? \*\* EDIT: The NHibernate concrete class is NHibernate.Collection.Generic.PersistentGenericBag which does indeed implement IList directly. However, I lost all the type-safe benefits of the generic list. This puts me back in the realm of having to write a wrapper for each child object and I really wanted to avoid that if possible.
On option is to create your own CustomList implementation that is wrapper around an instance that implements IList i.e: ``` public CustomList<AnotherObject> Items { return new CustomList<AnotherObject>(items); } ``` i.e. when you add to your `CustomList<T>` it adds to the backing list. It sounds like so long as your class implements `IList` as well as `IList<T>` you will be fine.
Yes, unfortunately you can't go about it this way. Calling `ToList()` creates a brand new instance of the list, so when you add items to that instance they aren't going to be reflected in the original list (as you've clearly discovered). I don't use NHibernate, but I would be curious to see if your container implements `IList` (the non-generic version). From the thread you referenced, it appears that `System.Collections.IList` is what's actually required (and that's implemented by `List<T>`, which is why it works). Does your container implement `IList`?
How to deserialize Enumerable.ToList<>() to List<>
[ "", "c#", "nhibernate", "xml-serialization", "workflow-foundation", "" ]
My boss for some reason wants to try to implement A/B Testing (or Split Testing) in JavaScript. Anyone know of any good JavaScript packages/libraries/solutions to implement A/B Testing?
Here's this: <http://ejohn.org/blog/genetic-ab-testing-with-javascript/> Are you trying to test the marketability of your site or the performance of your code or what? Assuming marketability, you could simply have some JS that appends a class name to your body tag (+ whatever else) based on a random number. Then record the random choice and outcome (when the visitor clicks something, also record which random layout they were presented with) via whatever analytics engine you use. You could also consider using cookies to ensure returning visitors get the same treatment. I don't know of a code quality a/b framework for JS but the idea would be similar. Define what constitutes higher quality (lower milliseconds of execution time?), run the variations of the code and see which comes out ahead. Tools like JMeter and JSUnit might be helpful for these purposes.
I have found this simple, open-source JS tool quite useful: <https://github.com/jamesyu/cohorts> It doesn't have all the features you might want, but it's free, flexible, pretty well and tidily written, and you can always hack on it to support additional requirements. Supports Google Analytics (via event tracking) and other back-ends.
Good Javascript A/B (Split) Testing package/library?
[ "", "javascript", "ab-testing", "" ]
I'm attempting to refactor an existing Winform application to use the MVP Passive View pattern. The application's UI, business logic and data storage code have been freely intermingled for years. It looks like it either started out with separate layers or someone attempted to separate it into layers. In any case the layer boundaries weren't respected. Since the forms directly manipulate the domain objects and the data source(and vice versa), my first task is to create presenter/controller objects and delegate those responsibilities. The application is a .NET 1.1 app and I'm developing in VS.NET 2003 with a rather limited refactoring add-in. I used a test generator for the existing code to create the boiler plate unit tests then went through and hand edited each test. Granted, this winds up testing what the code does, not necessarily what it's suppose to do. For new classes I'm doing TDD. **Any tips, resources, pitfalls to look out for with a refactoring effort of this scale?** A couple of resources I already have at my disposal: * Collection of programming books; *Refactoring*, *PEAA*, *WELC* * The internet (obviously) * Large quantities of caffeinated beverages Update: As an example what steps would you take to turn this: ``` private void OneOfManyFormEventHandlers(object sender, System.EventArgs e) { string LocalVariable; decimal AnotherLocal; if (!this._SomeDomainObject.SomeMethod(ClassField, out LocalVariable, out AnotherLocal)) { MessageBox.Show("An error occurred calling method"); return; } this.FormControl.Value = LocalVariable; this.AnotherFormContorl.Value = AnotherLocal; this.AnotherPrivateMethod(); } ``` Into this: ``` private void OneOfManyFormEventHandlers(object sender, System.EventArgs e) { this.FormPresenter.DoSomething(); } ```
The approach I've taken is too move the code out of the event handlers first. Essentially I've placed a class next to the form, which implements the event handlers and holds the UI state beside the controls. Through this move I have gained a pretty clear seperation of the form and the actual interaction with the remaining app and was able to introduce tests at that level. Another result of this was that the view becomes passive pretty quickly. I refactor the presenter (which now holds the event handlers) in a seperate step and introduce domain objects only after I've moved all uses of these objects out of all forms. So my steps would be: 1. Remove the UI dependency from the logic 2. Create domain objects (if not available already) 3. Refactor the presenters to use the domain objects 4. Introduce services according to your design choice while you're at it While I did this I started introducing tests at the newly introduced boundaries to ensure that I'm not breaking working code or to find bugs in the existing code I'm moving.
If you have the time, I'd recommend **first** writing some smoke tests using WinForms test frameworks like [White](http://www.codeplex.com/white) on the existing application. This way you'll be able to check for any newly introduced bugs when you start refactoring the code.
Refactoring WinForm ClickNCode to MVP Passive View
[ "", "c#", "winforms", "refactoring", "mvp", "" ]
I asked a question in which one of the response contained the following LINQ code: ``` var selected = lstAvailableColors.Cast<ListItem>().Where(i => i.Selected).ToList(); selected.ForEach( x => { lstSelectedColors.Items.Add(x); }); selected.ForEach( x => { lstAvailableColors.Items.Remove(x);}); ``` Can someone explain the above LINQ to a total newbie?
The LINQ operators use what's called a [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface), so you can read the first line as a series of function calls. Assuming that `lstAvailableColors` is `IEnumerable<T>`, the idea is that each available color flows through the LINQ operators. Let's break it down: ``` var selected = lstAvailableColors // each item is cast to ListItem type .Cast<ListItem>() // items that don't pass the test (Selected == true) are dropped .Where(i => i.Selected) // turn the stream into a List<ListItem> object .ToList(); ``` EDIT: As JaredPar pointed out, the last line above (`ToList()`) is very important. If you didn't do this, then each of the two `selected.ForEach` calls would re-run the query. This is called [deferred execution](http://blogs.msdn.com/charlie/archive/2007/12/09/deferred-execution.aspx) and is an important part of LINQ. You could rewrite this first line like this: ``` var selected = new List<ListItem>(); foreach (var item in lstAvailableColors) { var listItem = (ListItem)item; if (!listItem.Selected) continue; selected.Add(listItem); } ``` The last two lines are just another way to write a foreach loop and could be rewritten as: ``` foreach (var x in selected) { lstSelectedColors.Items.Add(x); } foreach (var x in selected) { lstAvailableColors.Items.Remove(X); } ``` Probably the hardest part of learning LINQ is learning the flow of data and the syntax of [lambda expressions](http://msdn.microsoft.com/en-us/library/bb397687.aspx).
Explanation from original question. The LINQ version works in two parts. The first part is the first line which finds the currently selected items and stores the value in a List. It's very important that the line contain the .ToList() call because that forces the query to execute immediately vs. being delayed executed. The next two lines iterate through each value which is selected and remove or add it to the appropriate list. Because the selected list is already stored we are no longer enumerating the collection when we modify it.
Explain this LINQ code?
[ "", "c#", ".net", "linq", "" ]
I have 2 different Java projects, one has 2 classes: `dynamicbeans.DynamicBean2` and `dynamic.Validator`. On the other project, I load both of these classes dynamically and store them on an `Object` ``` class Form { Class beanClass; Class validatorClass; Validator validator; } ``` I then go ahead and create a `Validator` object using `validatorClass.newInstance()` and store it on `validator` then I create a bean object as well using `beanClass.newInstance()` and add it to the session. ``` portletRequest.setAttribute("DynamicBean2", bean); ``` During the lifecycle of the `Form` project, I call `validator.validate()` which loads the previously created bean object from the session (I'm running Websphere Portal Server). When I try to cast this object back into a `DynamicBean2` it fails with a ClassCastException. When I pull the object back out of the session using ``` faces.getApplication().createValueBinding("#{DynamicBean2}").getValue(faces); ``` and check the class of it using `.getClass()` I get `dynamicbeans.DynamicBean2`. This is the class I want to cast it to however when I try I get the ClassCastException. Any reason why I'm getting this?
I am not quite following your description of the program flow, but usually when you get ClassCastExceptions you cannot explain you have loaded the class with one classloader then try to cast it to the same class loaded by another classloader. This will not work - they are represented by two different Class objects inside the JVM and the cast will fail. There is an [article about classloading in WebSphere](http://www.ibm.com/developerworks/websphere/library/techarticles/0112_deboer/deboer.html). I cannot say how it applies to your application, but there are a number of possible solutions. I can think of at least: 1. Change the context class loader manually. Requires that you can actually get a reference to an appropriate class loader, which may not be possible in your case. ``` Thread.currentThread().setContextClassLoader(...); ``` 2. Make sure the class is loaded by a class loader higher in the hierarchy. 3. Serialize and deserialize the object. (Yuck!) There is probably a more appropriate way for your particular situation though.
I was getting this problem after adding a dependency to `spring-boot-devtools` in my Springboot project. I removed the dependency and the problem went away. My best guess at this point is that `spring-boot-devtools` brings in a new classloader and that causes the issue of class casting problems between different classloaders in certain cases where the new classloader is not being used by some threads. Reference: [A dozer map exception related to Spring boot devtools](https://stackoverflow.com/questions/33955542/a-dozer-map-exception-related-to-spring-boot-devtools)
ClassCastException when casting to the same class
[ "", "java", "reflection", "classcastexception", "websphere-portal", "" ]
I am not very familiar with databases and what they offer outside of the CRUD operations. My research has led me to **triggers**. Basically it looks like triggers offer this type of functionality: > (from [Wikipedia](http://en.wikipedia.org/wiki/Database_trigger)) > > There are typically three triggering events that cause triggers to "fire": > > * INSERT event (as a new record is being inserted into the database). > * UPDATE event (as a record is being changed). > * DELETE event (as a record is being deleted). My question is: is there some way I can be notified in Java (preferably including the data that changed) by the database when a record is Updated/Deleted/Inserted using some sort of trigger semantics? What might be some alternate solutions to this problem? How can I listen to database events? **The main reason I want to do this is a scenario like this**: I have 5 client applications all in different processes/existing across different PCs. They all share a common database (Postgres in this case). Lets say one client changes a record in the DB that all 5 of the clients are "interested" in. I am trying to think of ways for the clients to be "notified" of the change (preferably with the affected data attached) instead of them querying for the data at some interval.
Using Oracle you can setup a Trigger on a table and then have the trigger send a JMS message. Oracle has two different JMS implementations. You can then have a process that will 'listen' for the message using the JDBC Driver. I have used this method to push changes out to my application vs. polling. If you are using a Java database (H2) you have additional options. In my current application (SIEM) I have triggers in H2 that publish change events using JMX.
Don't mix up the database (which contains the data), and events on that data. Triggers are one way, but normally you will have a persistence layer in your application. This layer can choose to fire off events when certain things happen - say to a JMS topic. Triggers are a last ditch thing, as you're operating on relational items then, rather than "events" on the data. (For example, an "update", could in reality map to a "company changed legal name" event) If you rely on the db, you'll have to map the inserts & updates back to real life events.... which you already knew about! You can then layer other stuff on top of these notifications - like event stream processing - to find events that others are interested in. James
Getting events from a database
[ "", "java", "database", "database-design", "events", "triggers", "" ]
I'm trying to build a way to get the key for a given piece of text in a given `.resx` file at runtime. Currently, I can open and read the file (Using `ResXResourceReader`) but I have to use a `foreach` to go over the entire file. This could be a performance issue, as some of our `.resx` files are fairly large (in the order of 2000 strings) and we may be doing this frequently. I'd like to use LINQ to Objects to query this, as I assume the `where` method is relatively optimized, however I've been unable to do so. The `ResXResourceReader` class has two methods `AsQueryable()` and `GetEnumerator()`, but neither allow LINQ against their result (so `from n in reader.AsQueryable() where` fails). How can I LINQ against something provided by the `ResXResourceReader`, or is it even worth the time?
The following code returns an IEnumerable object that allows you to use LINQ to query the contents of a resource file: ``` ResXResourceReader reader = new ResXResourceReader(myfile); IEnumerable<DictionaryEntry> enumerator = reader.OfType<DictionaryEntry>(); ```
Have you considered just doing some pre-processing? You could load the Resx file, then loop over the key-value pairs, and then store them *reversed* in a hash table (i.e. the key in the hash table is actually the value of the resource, and the value in the hash table is the key of the resource). Then the translations of value->key would be fast. The only concern is how you handle duplicates (multiple resources with the same value).
LINQ to resx file?
[ "", "c#", "linq", "ienumerable", "iqueryable", "resx", "" ]
I am trying to use YFrog's API. I think I am using it correctly to try and send a HTTP POST request that is of content type XML. However, as the response body, I am always getting a 404 error for some reason. [Here](https://i.stack.imgur.com/Sv4th.png) is their API. Here is my attempt of PHP code to upload. ``` $data = array('media' => 'http://img253.imageshack.us/my.php?image=bfab82a545d414uo.jpg', 'username' => 'asc', 'password' => 'asc', 'message' => 'hi'); $url = 'http://example.com/api/uploadAndPost'; $req = new HTTPRequest($url); $req->addHeaders(array("Content-Type" => "text/xml")); $req->setMethod(HTTP_METH_POST); $req->addQueryData($data); $req->send(); echo $req->getResponseBody(); ``` Also for the media it says "Binary image data" does that mean a URL of the image location can not be passed to it? What does it mean?
I think that the problem is basically that ImagesHack does not return a binary file when you give the URL posted above. For me, it returns an HTML document. I think you should try passing a binary file as the "media" parameter. The photo that your trying to get is located at <http://img253.imageshack.us/img253/172/bfab82a545d414uo.jpg>, use this URL instead. This is the response that I get with the one you originally tried: ``` HEAD /my.php?image=bfab82a545d414uo.jpg HTTP/1.1 Host: img253.imageshack.us HTTP/1.1 200 OK X-Powered-By: PHP/5.2.6 Set-Cookie: nopopunder=1; expires=Thu, 07-May-2009 11:10:21 GMT; path=/; domain=.imageshack.us X-UA-Compatible: IE=EmulateIE7 Content-type: text/html ```
You need to use addPostFields and addPostFile instead of addQueryData. An example of how to use both is [here](http://usphp.com/manual/en/function.httprequest-send.php) @MC is correct in that you can't send along a URL pointer to a file somewhere else, you need to actually be uploading those bytes. So you'll want to download a local copy first, passing the path to your local copy of that file to the addPostFile method.
Am I using Yfrog's API correctly to make a HTTP request with POST data?
[ "", "php", "xml", "api", "" ]
Is there an existing Linux/POSIX C/C++ library or example code for how to rebind a socket from one physical interface to another? For example, I have ping transmitting on a socket that is associated with a physical connection A and I want to rebind that socket to physical connection B and have the ping packets continue being sent and received on connection B (after a short delay during switch-over). I only need this for session-less protocols. Thank you Update: I am trying to provide failover solution for use with PPP and Ethernet devices. I have a basic script which can accomplish 90% of the functionality through use of iptables, NAT and routing table. The problem is when the failover occurs, the pings continue being sent on the secondary connection, however, their source IP is from the old connection. I've spoken with a couple of people who work on commercial routers and their suggestion is to rebind the socket to the secondary interface. Update 2: I apologise for not specifying this earlier. This solution will run on a router. I cannot change the ping program because it will run on the clients computer. I used ping as just an example, any connection that is not session-based should be capable of being switched over. I tested this feature on several commercial routers and it does work. Unfortunately, their software is proprietary, however, from various conversations and testing, I found that they are re-binding the sockets on failover.
As of your updated post, the problem is that changing the routing info is not going to change the source address of your ping, it will just force it out the second interface. [This answer](https://stackoverflow.com/questions/172905/using-linux-how-to-specify-which-ethernet-interface-data-is-transmitted-on) contains some relevant info. You'll need to change the ping program. You can use a socket-per-interface approach and somehow inform the program when to fail over. Or you will have to close the socket and then bind to the second interface. You can get the interface info required a couple of ways including calling ioctl() with the SIOCGIFCONF option and looping through the returned structures to get the interface address info.
I do't think that's quite a well-defined operation. the physical interfaces have different MAC addresses, so unless you have a routing layer mapping them (NAT or the like) then they're going to have different IP addresses. Ports are identified by a triple of `<IP addr, Port number, protocol>` so if your IP address changes the port is going to change. What are you really trying to do here?
Rebind a socket to a different interface
[ "", "c++", "c", "linux", "sockets", "" ]
I have a method to replace every character except those I specify. For example, ``` ReplaceNot("test. stop; or, not", ".;/\\".ToCharArray(), '*'); ``` would return ``` "****.*****;***,****". ``` Now, this is not an instance of premature optimization. I call this method quite a few times during a network operation. I found that on longer strings, it is causing some latency, and removing it helped a bit. Any help to speed this up would be appreciated. ``` public static string ReplaceNot(this string original, char[] pattern, char replacement) { int index = 0; int old = -1; StringBuilder sb = new StringBuilder(original.Length); while ((index = original.IndexOfAny(pattern, index)) > -1) { sb.Append(new string(replacement, index - old - 1)); sb.Append(original[index]); old = index++; } if (original.Length - old > 1) { sb.Append(new string(replacement, original.Length - (old + 1))); } return sb.ToString(); } ``` Final #'s. I also added a test case for a 3K character string, ran at 100K times instead of 1M to see how well each of these scales. The only surprise was that the regular expression 'scaled better' than the others, but it is no help since it is very slow to begin with: ``` User Short * 1M Long * 100K Scale John 319 2125 6.66 Luke 360 2659 7.39 Guffa 409 2827 6.91 Mine 447 3372 7.54 DirkGently 1094 9134 8.35 Michael 1591 12785 8.04 Peter 21106 94386 4.47 ``` Update: I made the creation of the regular expression for Peter's version a static variable, and set it to RegexOptions.Compiled to be fair: ``` User Short * 1M Long * 100K Scale Peter 8997 74715 8.30 ``` Pastebin link to my testing code, please correct me if it is wrong: [<http://pastebin.com/f64f260ee>](http://pastebin.com/f64f260ee)
Alright, on a ~60KB string, this will perform about 40% faster than your version: ``` public static string ReplaceNot(this string original, char[] pattern, char replacement) { int index = 0; StringBuilder sb = new StringBuilder(new string(replacement, original.Length)); while ((index = original.IndexOfAny(pattern, index)) > -1) { sb[index] = original[index++]; } return sb.ToString(); } ``` The trick is to initialize a new string with all replacement characters, since most of them will be replaced.
Can't you use Regex.Replace like so: ``` Regex regex = new Regex(@"[^.;/\\]"); string s = regex.Replace("test. stop; or, not", "*"); ```
Inverse String.Replace - Faster way of doing it?
[ "", "c#", "performance", "string", "stringbuilder", "" ]
So I've got a simple form through which I can either "add" a new Thing, or "update" an existing Thing. What I would like is to have one controller that can process both adding and updating. On the outset this seems simple enough, until I consider the problem of using setDisallowedFields in my InitBinder so that the "id" field is not allowed when adding a new Thing. Currently I have two controllers with what could be identical code except for the InitBinder method. Any suggestions or advice? (I'm open to the argument that I should want to maintain two controllers also, if you can give me good reasons)
Actually, you should disallow the "id" field both when adding AND updating. Otherwise a malicious user could tamper with the value of the "id" request parameter of an update request and thereby update a different record to the one shown by the form (assuming there's no ACLs or other domain-level security). However if you simply disallow the "id" field, the controller will treat the ID as being null, which will work when inserting but not when updating (e.g. it might try to insert a new record instead of updating, depending on what persistence mechanism you're using). So you want the controller to remember the non-editable values of your domain object (not just IDs, but all disallowed fields) between requests so that it can send all the correct values to the service layer or other business logic. This is done using the type-level @SessionAttributes annotation, as follows (other annotations omitted for clarity): ``` @SessionAttributes("thing") // the name of your domain object in the model public class ThingController { public void setDisallowedFields(WebDataBinder binder) { binder.setDisallowedFields("id", "someOtherUneditableField"); } // request handling methods go here as before } ``` For even better security, set the allowed fields rather than the disallowed fields. Either way you need the @SessionAttributes annotation to fill in whatever existing field values are ignored from the request.
The method signature to `initBinder` takes in the `HttpServletRequest`: ``` protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) ``` So perhaps you can have `initBinder()` check the request parameters to determine if you should conditionally set `setDisallowedFields`? (If this doesn't help, perhaps I'm not understanding the problem correctly...)
Spring MVC, one controller for "add" and "update" when using setDisallowedFields?
[ "", "java", "spring-mvc", "" ]
Love this website! My issue is as follows: I'm reading a zip file that's coming over a network from an HTTP "PUT" request. The request header tells me that the Content-Length is (say) 1Mb. The following code creates the ZipInputStream, and saves the zip contents to files in the current directory: ``` ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry ze; long totalBytesRead = 0; while ((ze = zis.getNextEntry()) != null) { BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(ze.getName())); byte[] buffer = new byte[4096]; int i; while ((i = zis.read(buffer)) != -1) { totalBytesRead+=i; outStream.write(buffer,0,i); } outStream.close(); } inputStream.close(); ``` When all is said and done, `totalBytesRead` is equal to about 1.5Mb (depending on compression of the files, could be anything though!). What I'd like to know is if there is a way to find out how many actual bytes have been read from the original `inputStream`? Both `ze.getSize()` and `ze.getCompressedSize()` return -1 for every zipped entry (i.e. it doesn't know). I need this info for a progress bar to show how many bytes of the transmitted zip file have been read off the network. Suggestions? Should I perhaps subclass ZipInputStream and try to find out how many bytes it's reading from it's wrapped InputStream? Thanks in advance!
Sure, that seems reasonable. There are basically two options: read all the bytes, store them (in memory or a file), count them, then decompress them; or count them as they come in. The former seems inefficient, and the latter will require a subclass of `InputStream` which has the ability to count the bytes it reads. I can't think of one in the standard library, but implementations probably exist out there - then again it'd be pretty easy to write your own.
``` import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * */ /** * @author clint * */ public class ByteCountingInputStream extends FilterInputStream { public int totalRead = 0; /** * @param in */ protected ByteCountingInputStream(InputStream in) { super(in); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see java.io.FilterInputStream#read() */ @Override public int read() throws IOException { int ret = super.read(); totalRead++; return ret; } /* (non-Javadoc) * @see java.io.FilterInputStream#read(byte[], int, int) */ @Override public int read(byte[] b, int off, int len) throws IOException { int ret = super.read(b, off, len); totalRead += ret; return ret; } /* (non-Javadoc) * @see java.io.FilterInputStream#read(byte[]) */ @Override public int read(byte[] b) throws IOException { int ret = super.read(b); totalRead += ret; return ret; } /* (non-Javadoc) * @see java.io.FilterInputStream#skip(long) */ @Override public long skip(long n) throws IOException { //What to do? return super.skip(n); } /** * @return the totalRead */ protected int getTotalRead() { return this.totalRead; } } ``` This goes in between like ``` ZipInputStream zis = new ZipInputStream(new ByteCountingInputStream(inputStream)); ```
ZipInputStream doesn't report *actual* (i.e. compressed) bytes read
[ "", "java", "inputstream", "unzip", "" ]
I was wondering if it is possible to save C# code fragments to a text file (or any input stream), and then execute those dynamically? Assuming what is provided to me would compile fine within any Main() block, is it possible to compile and/or execute this code? I would prefer to compile it for performance reasons. At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.
The best solution in C#/all static .NET languages is to use the [CodeDOM](http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx) for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.) Here's a nice short example take from [LukeH's blog](http://blogs.msdn.com/lukeh/archive/2007/07/11/c-3-0-and-codedom.aspx), which uses some LINQ too just for fun. ``` using System; using System.Collections.Generic; using System.Linq; using Microsoft.CSharp; using System.CodeDom.Compiler; class Program { static void Main(string[] args) { var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true); parameters.GenerateExecutable = true; CompilerResults results = csc.CompileAssemblyFromSource(parameters, @"using System.Linq; class Program { public static void Main(string[] args) { var q = from i in Enumerable.Range(1,100) where i % 2 == 0 select i; } }"); results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText)); } } ``` The class of primary importance here is the `CSharpCodeProvider` which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it. [Here](https://simeonpilgrim.com/blog/2007/12/04/compiling-and-running-code-at-runtime/) is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the `System.Reflection` namespace.
[You can compile a piece C# of code into memory and generate assembly bytes](http://www.tugberkugurlu.com/archive/compiling-c-sharp-code-into-memory-and-executing-it-with-roslyn) with Roslyn. It's already mentioned but would be worth adding some Roslyn example for this here. The following is the complete example: ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; namespace RoslynCompileSample { class Program { static void Main(string[] args) { // define source code, then parse it (to the type used for compilation) SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@" using System; namespace RoslynCompileSample { public class Writer { public void Write(string message) { Console.WriteLine(message); } } }"); // define other necessary objects for compilation string assemblyName = Path.GetRandomFileName(); MetadataReference[] references = new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location) }; // analyse and generate IL code from syntax tree CSharpCompilation compilation = CSharpCompilation.Create( assemblyName, syntaxTrees: new[] { syntaxTree }, references: references, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { // write IL code into memory EmitResult result = compilation.Emit(ms); if (!result.Success) { // handle exceptions IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (Diagnostic diagnostic in failures) { Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()); } } else { // load this 'virtual' DLL so that we can use ms.Seek(0, SeekOrigin.Begin); Assembly assembly = Assembly.Load(ms.ToArray()); // create instance of the desired class and call the desired function Type type = assembly.GetType("RoslynCompileSample.Writer"); object obj = Activator.CreateInstance(type); type.InvokeMember("Write", BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, new object[] { "Hello World" }); } } Console.ReadLine(); } } } ```
Is it possible to dynamically compile and execute C# code fragments?
[ "", "c#", "compilation", "dynamic-compilation", "" ]
I want to create a bunch of forms that all have the same properties and initialize the properties in the forms constructor by assigning the constructor's parameters. I tried creating a class that inherits from form and then having all of my forms inherit from that class, but I think since I couldn't call InitializeComponent(), that I was having some problems. What is some C# code on how to do this?
The parent's `InitializeComponent` should be called by having your constructor call `base()` like this: ``` public YourFormName() : base() { // ... } ``` (Your parent Form should have a call to `InitializeComponent` in its constructor. You didn't take that out, did you?) However, the road you're going down isn't one that will play nicely with the designer, as you aren't going to be able to get it to instantiate your form at design time with those parameters (you'll have to provide a parameterless constructor for it to work). You'll also run into issues where it assigns parent properties for a second time, or assigns them to be different from what you might have wanted if you use your parametered constructor in code. Stick with just having the properties on the form rather than using a constructor with parameters. For Forms, you'll have yourself a headache.
An alternate pattern from inheritance here would be to use a factory to create the forms. This way your factory can set all the properties
Windows Form inheritance
[ "", "c#", ".net", "windows", "winforms", "inheritance", "" ]
I am doing a project where I want a person to enter the name of any artist/band into a text box where it will seach my mysql database for the event information and display the results/content on another page. The code below is within my index.php where it should get the information from search.php (below also). I've looked all over and I'm not sure why it's not working and I can't figure out what to do. Help would be great! (I really need to pass this class!) :) (index.php) ``` <form name="search" action="search.php" method="get"> <div align="center"><input type="text" name="q" /> <p><input type="submit" name="Submit" value="Search" /></p> </form> ``` (search.php) ``` <?php //Get the search variable from URL $var=@&_GET['q']; $trimmed=trim($var); //trim whitespace from the stored variable //rows to return $limit=10; //check for an empty string and display a message. if($trimmed=="") { echo"<p>Please enter a name.</p>"; exit; } //check for a search parameter if(!isset($var)) { echo"<p>We don't seem to have a search parameter!</p>"; exit; } //connect to database mysql_connect("localhost","root","password"); //specify database mysql_select_db("itour") or die("Unable to select database"); //Build SQL Query $query = "select * from events where artist_name like \"%trimmed%\" order by date"; $numresults=mysql_query($query); $numrows=mysql_num_rows(numresults); //If no results, offer a google search as an alternative if ($numrows==0) { echo"<h3>Results</h3>"; echo"<p>Sorry, your search: &quot;" .$trimmed . "&quot; returned zero results</p>"; //google echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank\" title=\"Look up ".$trimmed ." on Google\"> Click here</a> to try the search on google</p>"; } //next determine if s has been passed to script, if not use 0 if(empty($s)) { $s=0; } //get results $query .=" limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); //display what was searched for echo"<p>You searched for: &quot;" .$var . "&quot;</p>"; //begin to show results set echo "Results"; $count = 1 + $s; //able to display the results returned while ($row=mysql_fetch_array($result)) { $title = $row["artist_name"]; echo"$count.)&nbsp;$title"; $count++; } $currPage = (($s/$limit) + 1; echo"<br />"; //links to other results if ($s>=1){ //bypass PREV link if s is 0 $prevs=($s-$limit); print"&nbsp;<a href=\"$PHP_SELF?s=$prevs&q=$var\">&lt;&lt; Prev 10</a>&nbsp;&nbsp;"; } //calculate number of pages needing links $pages = intval($numrows/$limit); //$pages now contains int of pages needed unless there is a remainder from diviison if($numrows%$limit){ //has remainder so add one page $pages++; } //check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1){ //not last page so give NEXT link $news = $s+$limit; echo "&nbsp;<a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 &gt;&gt;</a>"; } $a = $s +($limit); if($a > $numrows){$a = $numrows;} $b = $s + 1; echo "<p>Showing results $b to $a of $numrows</p>"; ?> ```
You are missing a $ symbol. I think ``` $var=@&_GET['q']; ``` should probably be ``` $var=@$_GET['q']; ``` unless you really want a reference, in which case it should be this: (the error suppression is not needed at this point if you want a reference, but you should check $var is set before trying to access it) ``` $var=& $_GET['q']; ``` I would be tempted to write it a bit more like this. ``` if (!isset($_GET['q'])) { echo"<p>We don't seem to have a search parameter!</p>"; exit; } $trimmed = trim($_GET['q']); if($trimmed=="") { echo"<p>Please enter a name.</p>"; exit; } ```
Your where clause is goofy...try changing it to: WHERE artist\_name like '%$trimmed%' just putting trimmed will be interpreted literally as the string "trimmed". However, using the variable $trimmed in your double-quoted string will give the actual variable's value.
Searching MySQL with PHP
[ "", "php", "mysql", "search", "" ]
I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default. Anyways, the program takes an input file, parses it, and creates an output file. The input file is in a specific format: ``` UI - 26474845 TI - the title (can be any number of lines) AB - the abstract (can also be any number of lines) ``` When the program throws an error, it gives you the reference information you need to track the error - namely, the UI, which section (title or abstract), and the line number relative to the beginning of the title or abstract. I want to log the offending sentences from the input file with a function that takes the reference number and the file, finds the sentence, and logs it. The best way I could think of doing it involves moving forward through the file a specific number of times (namely, n times, where n is the line number relative to the beginning of the seciton). The way that seemed to make sense to do this is: ``` i = 1 while i <= lineNumber: print original.readline() i += 1 ``` I don't see how this would make me lose data, but Python thinks it would, and says `ValueError: Mixing iteration and read methods would lose data`. Does anyone know how to do this properly?
You get the ValueError because your code probably has `for line in original:` in addition to `original.readline()`. An easy solution which fixes the problem without making your program slower or consume more memory is changing ``` for line in original: ... ``` to ``` while True: line = original.readline() if not line: break ... ```
Use `for` and [enumerate](http://docs.python.org/library/functions.html#enumerate). Example: ``` for line_num, line in enumerate(file): if line_num < cut_off: print line ``` **NOTE**: This assumes you are already cleaning up your file handles, etc. Also, the [takewhile](http://docs.python.org/library/itertools.html#itertools.takewhile) function could prove useful if you prefer a more functional flavor.
Mixing files and loops
[ "", "python", "python-2.7", "file", "loops", "while-loop", "" ]
I have a question about a SQL statement generated by a LINQ2SQL query. I have two database tables (`VisibleForDepartmentId` is a foreign key): ``` AssignableObject Department ---------------------- ------------ AssignableObjectId ┌────> DepartmentId AssignableObjectType │ VisibleForDepartmentId ───┘ ``` And the following mapping information (note that `AssignableObject` is abstract): ``` <Database Name="SO_755661" Class="DataClassesDataContext"> <Table Name="dbo.AssignableObject" Member="AssignableObjects"> <Type Name="AssignableObject" Modifier="Abstract"> <Column Name="AssignableObjectId" Type="System.Int32" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" /> <Column Name="AssignableObjectType" Type="System.String" DbType="VarChar(50) NOT NULL" CanBeNull="false" AccessModifier="Private" IsDiscriminator="true"/> <Column Name="VisibleForDepartmentId" Type="System.Int32" DbType="Int" CanBeNull="true" /> <Association Name="Department_AssignableObject" Member="VisibleForDepartment" ThisKey="VisibleForDepartmentId" OtherKey="DepartmentId" Type="Department" IsForeignKey="true" /> <Type Name="Asset" InheritanceCode="Asset" IsInheritanceDefault="true" /> <Type Name="Role" InheritanceCode="Role" /> </Type> </Table> <Table Name="dbo.Department" Member="Departments"> <Type Name="Department"> <Column Name="DepartmentId" Type="System.Int32" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" /> <Column Name="Name" Type="System.String" DbType="VarChar(50) NOT NULL" CanBeNull="false" /> <Association Name="Department_AssignableObject" Member="AssignableObjects" ThisKey="DepartmentId" OtherKey="VisibleForDepartmentId" Type="AssignableObject" /> </Type> </Table> </Database> ``` And the following code: ``` var loadOptions = new DataLoadOptions(); loadOptions.LoadWith<Asset>(a => a.VisibleForDepartment); dataContext.LoadOptions = loadOptions; var assets = from a in dataContext.Assets select a; ``` This results in a SQL query with two identical left outer joins: ``` SELECT t0.AssignableObjectType, t0.AssignableObjectId, t0.VisibleForDepartmentId, t2.test, t2.DepartmentId, t2.Name, t4.test AS test2, t4.DepartmentId AS DepartmentId2, t4.Name AS Name2 FROM dbo.AssignableObject AS t0 LEFT OUTER JOIN ( SELECT 1 AS test, t1.DepartmentId, t1.Name FROM dbo.Department AS t1 ) AS t2 ON t2.DepartmentId = t0.VisibleForDepartmentId LEFT OUTER JOIN ( SELECT 1 AS test, t3.DepartmentId, t3.Name FROM dbo.Department AS t3 ) AS t4 ON t4.DepartmentId = t0.VisibleForDepartmentId ``` Why are there two outer joins where one would have been sufficient? Kind regards, Ronald
I found out what causes these duplicated outer joins. They occur when a persistent class is inherited by two or more subclasses. For each subclass a new outer join is added to the generated SQL statement if you use `LoadWith`. In my example, `AssignableObject` has two subclasses: `Asset` and `Role`. This results in two outer joins with the `Department` table. If I add another subclass, a third outer join is added. I'm not sure whether SQL Server is smart enough to realize that the outer joins are duplicated. I've [posted this](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=434254) on Microsoft Connect. **EDIT**: Apparently my issue was a duplicate of [another issue](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361683) and it won't be fixed in the next release of LINQ2SQL.
Do you accidentally have 2 foreign key relationships defined on your database between the same 2 columns on the same 2 tables ?
Too many outer joins in LINQtoSQL generated SQL
[ "", "c#", "linq", "linq-to-sql", "t-sql", "outer-join", "" ]
How to Debug java Script Error Using Firebug? ## Duplicate [**How can I set breakpoints in an external JS script in Firebug**](https://stackoverflow.com/questions/32633/how-can-i-set-breakpoints-in-an-external-js-script-in-firebug/)
[Debug using FireBug](http://thecodecentral.com/2007/08/01/debug-javascript-with-firebug). Just check the line on which the error is occuring, then, just before that line, write a "debugger" call. ``` debugger; //Will invoke FireBug's debugger. var err = abcs; //Line containing error ```
To debug an error in firebug : * 1- select inspect tab from menu * 2- Set break point in the line that causes error * 3- Refrsh the page * 4- use F10 to step by step debug and F5 to end debgging It's like debgging of visual studio
How to debug Javascript error?
[ "", "javascript", "firefox", "debugging", "firebug", "" ]
I have a variable that is definited by a POST call from a form where it is inputed into a text field. Is there any way to convert this variable to an interger? From the form: ``` Lenght: <input name="length" value="10" type="text" id="lenght" size="2" /> ``` From the php code: ``` $length = $_POST['lenght']; $url = substr($url, 0, $length); ``` This doesn't seem to work and the only reason why I think it isn't working is because $lenght is defined as text and not an interger.
Two things: 1. It doesn't work because you misspelled length <-> lenght 2. The correct way to convert a string to an integer is using the function intval. --- ``` $length = intval($_POST['length']); $url = substr($url, 0, $length); ```
It likely doesn't work because you misspelled length twice, instead of zero or three times.
How do you change a text variable to an int in PHP?
[ "", "php", "forms", "" ]
Is there a standard way of encoding SQL queries as XML? I mean something like ``` select name from users where name like 'P%' group by name order by name desc ``` might encode as (my 5-minute mockup, probably bobbins)... ``` <?xml version="1.0" encoding="UTF-8"?> <query> <select> <table name="users"> <column name="name"/> </table> </select> <from> <table name="users"/> </from> <where> <operator name="like"> <column name="name"/> <value>P%</value> </operator> </where> <aggregation> <groupby> <column name="name"/> </groupby> </aggregation> <order> <order-by> <column name="name" order="desc"/> </order-by> </order> </query> ``` ...which would make it easy to build, store, validate structure and content (by producing a schema based on the database schema) etc.
I'm unaware of any such standard. What you have so far looks pretty workable. I question why you want to do this, though. I think this is a inner platform (an anti-pattern). Also, it's specifically re-inventing SQL, which is a well-known instance of that anti-pattern. To top it all off, it's programming in XML, which is widely regarded as a bad idea. The SQL grammar is simple enough that you can probably build a parser for it in short order using normal parser-generator tools (there are likely some already existing on the web that are open source). That would be a much cleaner way of verifying your SQL syntax.
I have been trying to do the same thing. To answer the question in the comments as to why I would want to. Well, I want to define a base query with the set of available columns and filter conditions and I want to allow a user to select the columns they want to display and enable and disable certain expressions in the where clause. I have played around with a few variations of an XML schema and got some decent results. I was even able to apply an XSLT to extract the SQL text based on the users' preferences. I have also gone looking for SQL parsers. <http://www.sqlparser.com> has one but its commercial and it's API is heavily Delphi styled and not very accessible in my opinion. As others have said it is feasible to use something like ANTLR to generate C# code that will parse SQL. You can find a few SQL grammars [here](http://www.antlr.org/grammar/list). The most recent MS SQL Gramar listed there is MS SQL 2000. I haven't had time to play around with this stuff. I was hoping that there would be a decent M Grammer in the Oslo SDK that would be able to parse queries, but I have not found one yet.
Is there a standard XML query encoding for SQL?
[ "", "sql", "xml", "standards", "" ]
I am running the following script on a cronjob... ``` cd /etc/parselog/ php run_all.php >/dev/null ``` and am getting the following errors: ``` [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './pdo.so' - ./pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './mysql.so' - ./mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './mysql.so' - ./mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './mysqli.so' - ./mysqli.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './odbc.so' - ./odbc.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './pdo.so' - ./pdo.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './pdo_mysql.so' - ./pdo_mysql.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './pdo_odbc.so' - ./pdo_odbc.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Warning: PHP Startup: Unable to load dynamic library './pdo_sqlite.so' - ./pdo_sqlite.so: cannot open shared object file: No such file or directory in Unknown on line 0 [05-May-2009 20:30:12] PHP Fatal error: Call to undefined function mysql_connect() in /etc/parselog/stats_downloads.php on line 5 ``` However, when I run the same script from the command line, logged in- it works perfectly without error. This is my $PATH string at the prompt: ``` $PATH = /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin ``` Any ideas or suggestions? I am certain when running the cronjob, it does not have a lib path or something included. I even tried adding the exact path
Tip 1: Ensure you have exactly the same $PATH in the cron job: ``` cd /etc/parselog/ export PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin php run_all.php >/dev/null ``` Tip 2: Make sure all other environment variables match as well. Dump the environment with the command `env`, and add the corresponding exports to your cron job.
Generally when something fails during cron but runs on the command line it's permissions, working directory, or environment variables. It looks like the php executable itself isn't loading the libraries, the problem might not be in your script.
PHP Errors on a cronjob, works fine at prompt
[ "", "php", "linux", "cron", "" ]
What would be a good mini-project to get intimate with JavaScript, as an advanced 'introduction' to the language? I want to actually code an application in JS, not hook up bits of it to enhance a web application.
Although not a project, watch the Douglas Crockford videos at YUI theater. The biggest web based Javascript projects are going to deal with the DOM. Do some nifty stuff with JQuery. Make a table with rows that highlight when you hover. Make them update themselves through AJAX and JSON when you click on them. If you're really looking for something magical and usefull write a scrollable table with fixed headers and footers for IE8. If you want to stay away from the WEB use the JDK 1.6 and run Javascript code in that. You could do TONS with that.
A lot of stuff you could learn by doing an RSS reader on a page. Google shows what can be done. The whole lection concentrates on javascript, network access, security restrictions and medium data mangeling. If you have the ability to do any sort of backend programming than AJAX is really neat to do. You can get a lot of good effects with less efforts. A good thing to build on up.
Introductory JavaScript programming task for an expert developer
[ "", "javascript", "" ]
What are some really good reasons to ditch `std::allocator` in favor of a custom solution? Have you run across any situations where it was absolutely necessary for correctness, performance, scalability, etc? Any really clever examples? Custom allocators have always been a feature of the Standard Library that I haven't had much need for. I was just wondering if anyone here on SO could provide some compelling examples to justify their existence.
As I mention [here](https://stackoverflow.com/questions/657783/how-does-intel-tbbs-scalableallocator-work), I've seen Intel TBB's custom STL allocator significantly improve performance of a multithreaded app simply by changing a single ``` std::vector<T> ``` to ``` std::vector<T,tbb::scalable_allocator<T> > ``` (this is a quick and convenient way of switching the allocator to use TBB's nifty thread-private heaps; see [page 59 in this document](https://citeseerx.ist.psu.edu/doc/10.1.1.71.8289))
One area where custom allocators can be useful is game development, especially on game consoles, as they have only a small amount of memory and no swap. On such systems you want to make sure that you have tight control over each subsystem, so that one uncritical system can't steal the memory from a critical one. Other things like pool allocators can help to reduce memory fragmentation. You can find a long, detailed paper on the topic at: [EASTL -- Electronic Arts Standard Template Library](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html)
Compelling examples of custom C++ allocators?
[ "", "c++", "memory-management", "std", "memory-alignment", "allocator", "" ]
This is a real noob question. When I set up JAVA\_HOME using the command line interface I used set JAVA\_HOME = C:\Program Files\Java\jdk1.6.0\_13 However when I open the JAVA\_HOME variable from System>Advanced>Environment Variables the change is not visible. Are these two different settings? I have this question every time I set up a new Jdk and have never fully understood why the two seem to be different.
The variable you set on command line is for *that* command shell and any other processes it starts. When you set it from System/Advanced/Environment Variables it affects any other process you start, including command shell, after setting it. Depending on where you set it, it will be available to the same user or any other use who logs in as well.
The JAVA\_HOME you set by command line is set only for that session of the shell.
Is there a difference between setting JAVA_HOME through cmd line or GUI
[ "", "installation", "java", "" ]
I'm reading Heads First C# (it's very interesting and user-friendly), but I wondered if anyone had a useful metaphor for describing how Name spaces, Classes, methods, properties, etc. all 'fit together'? Is Class a Parent and a Method a child, etc. Or is it more complicated? Could a Name Space be a house, and a Class be a room (Bathroom) and a method be what can be done in that room (wash, etc.) and the properties be what can be done when doing that activity, use soap, hot water... ...I'll get my coat.
I would say: * **Namespace**: A category or brand of cars. Note that the brand really doesn't have to dictate how the car is built. You can't say a Honda always have four doors, or that it always has 4wd. Such specifics is up to the class to dictate. [Rich.Carpenter's post](https://stackoverflow.com/questions/819793/namespaces-then-classes-then-methods-is-there-a-metaphor/819813#819813) explains the purpose of namespaces very well. * **Class**: Blueprint for how to build a specific car. * **Object**: An actual car (instance) created from the car blueprint (the class) * **Method**: Something a user of the car can make it do. `Start()`, `IncreaseThrottle()`, `Brake()`, `OpenDoor()`, etc. * **Property**: Attributes, information and building blocks which the car contains. E.g. Total running miles, color, steering wheel dimension, stereo system etc etc. Some concepts which could seem more advanced to you. Maybe overkill right now, but read it if you're interested: * **Inheritance**: When a class is based on another class and adds some more specific details. A line of inheritance usually goes from the most common and general aspect, all the way down to a point where it makes no more sense to be more specific. Example of this in the context of animals: *Animal->Mamal->Rodent->Rat->RattusNorvegicus* * **Aggregates**: Properties that "builds" the object. E.g. "This car is an aggregation of four wheels, a chassis, an engine, etc". * **Attribute**: Properties that describe the object, usually not part of its physical construction. E.g. Color, top speed, engine volume etc. * **Encapsulation**: The concept of concealing certain properties from the user, or to protect certain properties from being used incorrectly (and thereby damaging the object). E.g. You don't expose the gear-property of a car class to be altered freely. You encapsulate it and make sure `Clutch()` is called before `SetGear()`. * **Overriding**: If a class inherits from another class, it also inherits methods from that class. Overriding is basically when the *inheriting* class replaces the implementation of such a method with its own required behaviour. Example of usage in next point. * **Polymorphism**: A difficult concept to grasp until you start using it practically. It means referring to a very specific kind of object, by using a generic reference which allows you to ignore the specific type (when you don't need to know it). E.g. If you want to "read" the license plate number property of every vehicle in a parking lot, you don't really care what the brand is, or even if it's a trailer or motorcycle or whatever. To be able to do this, we make sure the license plate number is a property in the most general class in the inheritance line (probably the `Vehicle` class). So you only have to deal with all the objects in a list by referring to them as their `Vehicle` class and then calling `Vehicle::GetLicensePlateNumber()`. Any vehicle requiring some special handling to retrieve the number can implement this behaviour by overriding the method and make it behave as required. So, a wide range of object types can be used as if they were of the same type, but can behave differently.
Think of classes as descriptions of objects and methods as actions those object can perform. For example, I design a new car. The plans or blueprints (classes) for that car are what is used to create actual, physicial cars (objects). Those plans indicate that the car should have a functional horn. Therefore, I have designed honking functionality (a method) into the car. Those plans also indicate that the car have four wheels. Wheels would be a property of the car with an instantiated (assigned to the property when the object is created) value of 4. Color would be another possible property. Properties describe object qualities or characteristics (color, height, width, etc.). Now, I work for Toyota (not really, but bear with me). Toyota would be the namespace that includes my car blueprint. Since Ford, GM, etc. can all have their very own car designs (classes) as well with the very same names (car) and methods (honk), the namespaces of Toyota, Ford and GM keep those blueprints (classes) separate and distinct, as you can have multiple versions of classes and methods with the same name in an application when they have different namespaces. Hope that helps.
What is the difference between a namespace, a class, an object and an instance?
[ "", "c#", "oop", "namespaces", "" ]
I am trying to write some complicated acceptance tests for my C# code. I notice that when I am writing my tests I am doing a lot of explicit casting to satisfy the C# compiler. I like the type-safety I get in my production code with a statically-typed language like C#, but for my tests I would be happy to use a dynamically-typed language (e.g. IronPython or IronRuby) to avoid all the explicit casting. If my test calls a method that doesn't exist on an object, it would be OK for the code to fail at run time (it's just a failing test). I am currently using MS Test as my unit testing framework, and it would be convenient if I could continue to use it. What dynamic (DLR-based) language can I use that will integrate with MS Test? Feel free to suggest a different testing framework, if you think that would help.
I recommend IronPython -- among its advantages is the excellent book "IronPython in Action" which will lead you through every important aspect, including testing.
I prefer C# for unit testing... If you are looking for dynamic language you can try iron-python for that....
What dynamic language can I use for .NET unit tests?
[ "", "c#", ".net", "unit-testing", "mstest", "dynamic-language-runtime", "" ]
I'm going to change my C# style in programming(I've been using 'public static' for variables,methods - everything). My question: ``` public class WinSock { public Socket sock; public byte[] data; ..... } var data = new byte[2058]; data = WinSock.data; ``` or this one: ``` private class WinSock { private Socket sock; private byte[] data; ..... public byte[] getdata() { get {return data;} } } WinSock ws = new WinSock(); var data = new byte[2058]; data = ws.getdata(); ``` In both cases the data and sock variables can be accessed from other classes. Which of the two declarations is better?
The second one is closer to what's generally considered to be better. In Object Oriented Programming we encapsulate the variables in the classes and only expose as little as needed outside the class. Name your properties with an initial capital letter, and as a data member rather than a method, i.e. `Data` rather than `getdata`. ``` public class WinSock { private Socket _socket; private byte[] _data; public Socket Socket { get { return _socket; } } public byte[] Data { get { return _data; } } } ``` (One way to name the private member variables is to use an underscore. There are some other conventions commonly used, but the important thing is really to pick one and stick to it.) In C# 3 there is also a shortcut syntax for properties: ``` public class WinSock { public Socket Socket { get; private set; } public byte[] Data { get; private set; } } ```
Generally, making fields public is never a good idea. Since getdata is a property, it should be called Data. ``` private class WinSock { private Socket sock; private byte[] data; ..... public byte[] Data { get { return data; } } } ``` The public interface, consisting of public properties and methods, should ensure that the state (the fields) is never inconsistent. The class is responsible for the fields. it should not allow anyone to write directly into it. This is what encapsulation is about.
Which declaration is better?
[ "", "c#", "oop", "" ]
The `Expander` control in WPF does not stretch to fill all the available space. Is there any solutions in XAML for this?
All you need to do is this: ``` <Expander> <Expander.Header> <TextBlock Text="I am header text..." Background="Blue" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=ActualWidth}" /> </Expander.Header> <TextBlock Background="Red"> I am some content... </TextBlock> </Expander> ``` <http://joshsmithonwpf.wordpress.com/2007/02/24/stretching-content-in-an-expander-header/>
Non stretchable `Expander`s is usually the problem of non stretchable parent controls.. Perhaps one of the parent controls has defined a `HorizontalAlignment` or `VerticalAlignment` property? If you can post some sample code, we can give you a better answer.
How can I make a WPF Expander Stretch?
[ "", "c#", "wpf", "expander", "stretch", "" ]
I'm interested in parsing a fairly large text file in Java (1.6.x) and was wondering what approach(es) would be considered best practice? The file will probably be about 1Mb in size, and will consist of thousands of entries along the lines of; ``` Entry { property1=value1 property2=value2 ... } ``` etc. My first instinct is to use regular expressions, but I have no prior experience of using Java in a production environment, and so am unsure how powerful the java.util.regex classes are. To clarify a bit, my application is going to be a web app (JSP) which parses the file in question and displays the various values it retrieves. There is only ever the one file which gets parsed (it resides in a 3rd party directory on the host). The app will have a fairly low usage (maybe only a handful of users using it a couple of times a day), but it is vital that when they do use it, the information is retrieved as quickly as possible. Also, are there any precautions to take around loading the file into memory every time it is parsed? Can anyone recommend an approach to take here? Thanks
If it's going to be about 1MB and literally in the format you state, then it sounds like you're overengineering things. Unless your server is a ZX Spectrum or something, just use regular expressions to parse it, whack the data in a hash map (and keep it there), and don't worry about it. It'll take up a few megabytes in memory, but so what...? **Update:** just to give you a concrete idea of performance, some measurements I took of the [performance of String.split()](http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml) (which uses regular expressions) show that on a 2GHz machine, it takes **milliseconds to split 10,000 100-character strings** (in other words, about 1 megabyte of data -- actually nearer 2MB in pure volume of bytes, since Strings are 2 bytes per char). Obvioualy, that's not quite the operation you're performing, but you get my point: things aren't that bad...
If it is a proper grammar, use a parser builder such as the [GOLD Parsing System](http://www.devincook.com/). This allows you to specify the format and use an efficient parser to get the tokens you need, getting error-handling almost for free.
Parsing Large Text Files in Real-time (Java)
[ "", "java", "regex", "parsing", "" ]